Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Maps API V3 - add event listener to all markers?

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...

This feels wrong:

google.maps.event.addListener(unique_marker_id, 'click', function(){     //do something with this marker...                    });    
like image 847
Haroldo Avatar asked Jul 07 '11 13:07

Haroldo


People also ask

How many markers can Google Maps API handle?

Answers. you can add 200 markers at a time but if you are using google service it will not response more than 10 or 20 at a time and if you have array of collection Lattitude and longitude just try to modify above code.

How is the global namespace referred for marker object in version 3 of the API as compared to version 2?

Probably the most noticeable change in the Maps JavaScript API v3 is the introduction of the google. maps namespace. The v2 API places all objects in the Global namespace by default, which can result in naming collisions. Within v3, all objects are located within the google.

How do you fix Google Maps event addDomListener () is deprecated?

event. addDomListener() is deprecated, use the standard addEventListener() method instead. The feature will continue to work and there is no plan to decommission it.


2 Answers

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:

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.

like image 144
Glenn Mohammad Avatar answered Sep 19 '22 09:09

Glenn Mohammad


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.

like image 23
Jiri Kriz Avatar answered Sep 21 '22 09:09

Jiri Kriz