Google Maps API V3 - 为所有标记添加事件监听器?

时间:2022-11-23 08:12:49

There's got to be a way to add a listener to ALL MARKERS, currently I'm adding a listener to each one using a loop which feels really wrong...

必须有一种方法可以为ALL MARKERS添加一个监听器,目前我正在使用一个感觉非常错误的循环为每个监听器添加一个监听器......

This feels wrong:

这感觉不对:

google.maps.event.addListener(unique_marker_id, 'click', function(){
    //do something with this marker...                   
});   

10 个解决方案

#1


37  

In both Marker and MarkerWithLabel case, you might just as well use the this keyword to refer the object to which the event handler is attached:

在Marker和MarkerWithLabel的情况下,您也可以使用this关键字来引用附加事件处理程序的对象:

google.maps.event.addListener(marker, 'click', function () {
   // do something with this marker ...
   this.setTitle('I am clicked');
});

this here is referring to the particular marker object.

这里指的是特定的标记对象。

#2


28  

You need to add the listener to each marker, but you can make it easy by e.g. defining a function like

您需要将侦听器添加到每个标记,但是您可以通过例如定义像这样的函数

function createMarker(pos, t) {
    var marker = new google.maps.Marker({       
        position: pos, 
        map: m,  // google.maps.Map 
        title: t      
    }); 
    google.maps.event.addListener(marker, 'click', function() { 
       alert("I am marker " + marker.title); 
    }); 
    return marker;  
}

and call it appropriately:

并适当地称呼它:

var m1 = createMarker(new google.maps.LatLng(...), "m1");
var m2 = createMarker(new google.maps.LatLng(...), "m2");

or in a loop, etc.

或循环等

#3


4  

I managed to do this using FusionTablesLayer. It's a bit of work setting everything up correctly, but once you're done, it's ultra-fast, even with thousands of markers.

我设法使用FusionTablesLayer完成了这项工作。正确设置一切都是一项工作,但是一旦完成,它就会超快,即使有数千个标记。

You basically create a public table in Google Docs and query it from your webpage. The map is pre-generated on Googles' servers, which is why it performs so well.

您基本上是在Google文档中创建一个公共表格,并从您的网页查询它。该地图是在Googles的服务器上预先生成的,这就是它表现良好的原因。

A complete demo page:

完整的演示页面:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>Google Maps Demo</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
  <meta charset="UTF-8">
  <style type="text/css">
    html, body, #map_canvas
    {
      margin: 0;
      padding: 0;
      height: 100%;
    }
  </style>
  <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
  <script type="text/javascript">
    function initialize() 
    {
      var denmark = new google.maps.LatLng(56.010666, 10.936890);

      map = new google.maps.Map(document.getElementById('map_canvas'), {
        center: denmark,
        zoom: 7,
        mapTypeId: 'roadmap'
      });

      layer = new google.maps.FusionTablesLayer({
        query: {
          select: 'Coordinates',
          from: '1234567'
        }
      });
      layer.setMap(map);

      google.maps.event.addListener(layer, 'click', function (event) { 
        alert('Hello World!'); });

    }
  </script>
</head>
<body onload="initialize()">
  <div id="map_canvas"></div>
</body>
</html>

Check out this article for more info, "Too Many Markers!" by Luke Mahe and Chris Broadfoot from the Google Geo APIs Team.

查看这篇文章了解更多信息,“太多标记!”来自Google Geo API团队的Luke Mahe和Chris Broadfoot。

#4


4  

If you're using GoogleMaps v3.16 or later, you can add the event handler to the whole map.data layer.

如果您使用的是GoogleMaps v3.16或更高版本,则可以将事件处理程序添加到整个map.data图层。

var map = new google.maps.Map(document.getElementById("map-canvas"), options);
map.data.loadGeoJson('http://yourserver.com/path/to/geojson.json');
map.data.addListener('click', function(e) {
    // this - instance of the layer object, in this case - map.data
    // e.feature - instance of the feature object that initiated the event
    // e.latLng - the position of the event
});

see: https://developers.google.com/maps/documentation/javascript/examples/layer-data-event

请参阅:https://developers.google.com/maps/documentation/javascript/examples/layer-data-event

#5


0  

I managed to get an answer here: Google Maps and Their Markers

我设法得到了一个答案:谷歌地图和他们的标记

and a demo here: http://jsfiddle.net/salman/bhSmf/

和演示:http://jsfiddle.net/salman/bhSmf/

#6


0  

This simplest way is this:

这种最简单的方法是这样的:

google.maps.event.addListener(marker, 'click', function() {
var marker = this;
alert("Tite for this marker is:" + this.title);
});

#7


0  

To Expand on Jiri answer purley for those searching who also wish to add a custom label etc. In the spirit of Jiri post, in shorthand version:

为了那些想要添加自定义标签等的搜索,请扩展Jiri回答purley。以Jiri文章的精神,简写版本:

    var m1 = createMarker({lat: -25.363, lng: 131.044}, "m1", "<div id=\"content\"><div id=\"siteNotice\"></div>  <h1 id=\"firstHeading\" class=\"firstHeading\">m1</h1> <div id=\"bodyContent\">Some info</div> </div>");

function createMarker(pos, t, d) {
    var marker = new google.maps.Marker({       
        position: pos, 
        map: map, 
        title: t      
    }); 
    google.maps.event.addListener(marker,"click", function() { 
        alert("I am marker " + marker.title); 
    new google.maps.InfoWindow({ content: d }).open(map, marker);

    }); 
    return marker;  
}

Remove alert, just there to show the action etc. as with Jiri's info, you can add m2, m3 etc. I thought this simply finished things off.

删除警报,只是在那里显示动作等,与Jiri的信息一样,你可以添加m2,m3等我认为这简单地完成了一些事情。

#8


0  

/* Note: I have a set of data, and it is named by the variable data.
 * The variable data is an array
 */

//Here I get the length of the data
var dataLength = data.length;

//Then I iterate through all my pieces of data here
//NOTICE THAT THE KEYWORD let IS SO IMPORTANT HERE
for(let markerIterator = 0; markerIterator < dataLength; markerIterator++) {
    /* This creates a new google maps marker based on my data's latitude and 
     * longitude
     */
    var marker = new google.maps.Marker({
        position: { lat: data[markerIterator].latitude, lng: 
        data[markerIterator].longitude },
        map: map
    });

    google.maps.event.addListener(marker, 'click', function () {
        /* This will spit out the unique markerIterator value for each marker when 
         * clicked. It is a unique value because I defined markerIterator with the 
         * keyword let!
         */
        console.log(markerIterator); 

        // Use the keyword this to refer to each unique marker, for example:
        map.setCenter(this.getPosition());              
    });
}

#9


-1  

var map;
function initialize_map(locations) {
  var options = {
    zoom: 8,
    center: new google.maps.LatLng(59.933688,30.331879),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById("map-canvas"), options);
  var bounds = new google.maps.LatLngBounds();
  for (i = 0; i < locations.length; i++) {
    marker = new google.maps.Marker({
      position: new google.maps.LatLng(locations[i][lat], locations[i][lng]),
      map: map,
      title: locations[i][title]
    });
    set_event(marker);
    bounds.extend(marker.position);
  }
  map.fitBounds(bounds);
}
function set_event(marker) {
  google.maps.event.addListener(marker, 'click', function() {
    // do something with this marker ...
  });
}

#10


-1  

You can do something like this:

你可以这样做:

   function setMarkers(map, locations) {
      var image = ['circle_orange.png','circle_blue .png'];
      for (var i = 0; i < locations.length; i++) {
        var stations = locations[i];
        var myLatLng = new google.maps.LatLng(stations[1], stations[2]);
        var marker = new google.maps.Marker({
          position: myLatLng,
          map: map,
          icon: image[stations[3]],
          title: stations[0],
          zIndex: stations[3],
          optimized: false
        });
        var infowindow = new google.maps.InfoWindow({
            content: "No data available"
        });
        google.maps.event.addListener(marker, 'mouseover', function() {
        infowindow.setContent("We can include any station information, for example: Lat/Long: "+ stations[1]+" , "+stations[2]);
        infowindow.open(map, this);
        });
      }
    }

#1


37  

In both Marker and MarkerWithLabel case, you might just as well use the this keyword to refer the object to which the event handler is attached:

在Marker和MarkerWithLabel的情况下,您也可以使用this关键字来引用附加事件处理程序的对象:

google.maps.event.addListener(marker, 'click', function () {
   // do something with this marker ...
   this.setTitle('I am clicked');
});

this here is referring to the particular marker object.

这里指的是特定的标记对象。

#2


28  

You need to add the listener to each marker, but you can make it easy by e.g. defining a function like

您需要将侦听器添加到每个标记,但是您可以通过例如定义像这样的函数

function createMarker(pos, t) {
    var marker = new google.maps.Marker({       
        position: pos, 
        map: m,  // google.maps.Map 
        title: t      
    }); 
    google.maps.event.addListener(marker, 'click', function() { 
       alert("I am marker " + marker.title); 
    }); 
    return marker;  
}

and call it appropriately:

并适当地称呼它:

var m1 = createMarker(new google.maps.LatLng(...), "m1");
var m2 = createMarker(new google.maps.LatLng(...), "m2");

or in a loop, etc.

或循环等

#3


4  

I managed to do this using FusionTablesLayer. It's a bit of work setting everything up correctly, but once you're done, it's ultra-fast, even with thousands of markers.

我设法使用FusionTablesLayer完成了这项工作。正确设置一切都是一项工作,但是一旦完成,它就会超快,即使有数千个标记。

You basically create a public table in Google Docs and query it from your webpage. The map is pre-generated on Googles' servers, which is why it performs so well.

您基本上是在Google文档中创建一个公共表格,并从您的网页查询它。该地图是在Googles的服务器上预先生成的,这就是它表现良好的原因。

A complete demo page:

完整的演示页面:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>Google Maps Demo</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
  <meta charset="UTF-8">
  <style type="text/css">
    html, body, #map_canvas
    {
      margin: 0;
      padding: 0;
      height: 100%;
    }
  </style>
  <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
  <script type="text/javascript">
    function initialize() 
    {
      var denmark = new google.maps.LatLng(56.010666, 10.936890);

      map = new google.maps.Map(document.getElementById('map_canvas'), {
        center: denmark,
        zoom: 7,
        mapTypeId: 'roadmap'
      });

      layer = new google.maps.FusionTablesLayer({
        query: {
          select: 'Coordinates',
          from: '1234567'
        }
      });
      layer.setMap(map);

      google.maps.event.addListener(layer, 'click', function (event) { 
        alert('Hello World!'); });

    }
  </script>
</head>
<body onload="initialize()">
  <div id="map_canvas"></div>
</body>
</html>

Check out this article for more info, "Too Many Markers!" by Luke Mahe and Chris Broadfoot from the Google Geo APIs Team.

查看这篇文章了解更多信息,“太多标记!”来自Google Geo API团队的Luke Mahe和Chris Broadfoot。

#4


4  

If you're using GoogleMaps v3.16 or later, you can add the event handler to the whole map.data layer.

如果您使用的是GoogleMaps v3.16或更高版本,则可以将事件处理程序添加到整个map.data图层。

var map = new google.maps.Map(document.getElementById("map-canvas"), options);
map.data.loadGeoJson('http://yourserver.com/path/to/geojson.json');
map.data.addListener('click', function(e) {
    // this - instance of the layer object, in this case - map.data
    // e.feature - instance of the feature object that initiated the event
    // e.latLng - the position of the event
});

see: https://developers.google.com/maps/documentation/javascript/examples/layer-data-event

请参阅:https://developers.google.com/maps/documentation/javascript/examples/layer-data-event

#5


0  

I managed to get an answer here: Google Maps and Their Markers

我设法得到了一个答案:谷歌地图和他们的标记

and a demo here: http://jsfiddle.net/salman/bhSmf/

和演示:http://jsfiddle.net/salman/bhSmf/

#6


0  

This simplest way is this:

这种最简单的方法是这样的:

google.maps.event.addListener(marker, 'click', function() {
var marker = this;
alert("Tite for this marker is:" + this.title);
});

#7


0  

To Expand on Jiri answer purley for those searching who also wish to add a custom label etc. In the spirit of Jiri post, in shorthand version:

为了那些想要添加自定义标签等的搜索,请扩展Jiri回答purley。以Jiri文章的精神,简写版本:

    var m1 = createMarker({lat: -25.363, lng: 131.044}, "m1", "<div id=\"content\"><div id=\"siteNotice\"></div>  <h1 id=\"firstHeading\" class=\"firstHeading\">m1</h1> <div id=\"bodyContent\">Some info</div> </div>");

function createMarker(pos, t, d) {
    var marker = new google.maps.Marker({       
        position: pos, 
        map: map, 
        title: t      
    }); 
    google.maps.event.addListener(marker,"click", function() { 
        alert("I am marker " + marker.title); 
    new google.maps.InfoWindow({ content: d }).open(map, marker);

    }); 
    return marker;  
}

Remove alert, just there to show the action etc. as with Jiri's info, you can add m2, m3 etc. I thought this simply finished things off.

删除警报,只是在那里显示动作等,与Jiri的信息一样,你可以添加m2,m3等我认为这简单地完成了一些事情。

#8


0  

/* Note: I have a set of data, and it is named by the variable data.
 * The variable data is an array
 */

//Here I get the length of the data
var dataLength = data.length;

//Then I iterate through all my pieces of data here
//NOTICE THAT THE KEYWORD let IS SO IMPORTANT HERE
for(let markerIterator = 0; markerIterator < dataLength; markerIterator++) {
    /* This creates a new google maps marker based on my data's latitude and 
     * longitude
     */
    var marker = new google.maps.Marker({
        position: { lat: data[markerIterator].latitude, lng: 
        data[markerIterator].longitude },
        map: map
    });

    google.maps.event.addListener(marker, 'click', function () {
        /* This will spit out the unique markerIterator value for each marker when 
         * clicked. It is a unique value because I defined markerIterator with the 
         * keyword let!
         */
        console.log(markerIterator); 

        // Use the keyword this to refer to each unique marker, for example:
        map.setCenter(this.getPosition());              
    });
}

#9


-1  

var map;
function initialize_map(locations) {
  var options = {
    zoom: 8,
    center: new google.maps.LatLng(59.933688,30.331879),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById("map-canvas"), options);
  var bounds = new google.maps.LatLngBounds();
  for (i = 0; i < locations.length; i++) {
    marker = new google.maps.Marker({
      position: new google.maps.LatLng(locations[i][lat], locations[i][lng]),
      map: map,
      title: locations[i][title]
    });
    set_event(marker);
    bounds.extend(marker.position);
  }
  map.fitBounds(bounds);
}
function set_event(marker) {
  google.maps.event.addListener(marker, 'click', function() {
    // do something with this marker ...
  });
}

#10


-1  

You can do something like this:

你可以这样做:

   function setMarkers(map, locations) {
      var image = ['circle_orange.png','circle_blue .png'];
      for (var i = 0; i < locations.length; i++) {
        var stations = locations[i];
        var myLatLng = new google.maps.LatLng(stations[1], stations[2]);
        var marker = new google.maps.Marker({
          position: myLatLng,
          map: map,
          icon: image[stations[3]],
          title: stations[0],
          zIndex: stations[3],
          optimized: false
        });
        var infowindow = new google.maps.InfoWindow({
            content: "No data available"
        });
        google.maps.event.addListener(marker, 'mouseover', function() {
        infowindow.setContent("We can include any station information, for example: Lat/Long: "+ stations[1]+" , "+stations[2]);
        infowindow.open(map, this);
        });
      }
    }