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...                   
});   

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.


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.


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.

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.

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.


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

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


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

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


This simplest way is this:

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

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:

    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.


/* 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());              
    });
}

What i've Done is, when adding new marker on map and before pushing it into markers = [] array, i just add listener to it marker.addListener('click', () => { // Do Something here});

Complete Code:

// Adds a marker to the map and push to the array.
    function addMarker(location) {
        var marker = new google.maps.Marker({
            position: location,
            icon: {
                url: "http://maps.google.com/mapfiles/ms/icons/blue-dot.png"
            },
            animation: google.maps.Animation.DROP,
            map: map
        });
        marker.addListener("click",
            () => {
                console.log("Marker Click Event Fired!");
            });
        markers.push(marker);

    }

LINK i followed!

It was really hard for me to find a specific answer to my need. But this one is working now and everywhere for me! Regards! :)


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 ...
  });
}

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);
        });
      }
    }

Need Your Help

Android Process Scheduling

android multithreading scheduler dalvik cgroups

I am trying to get a better understanding so I can scope the reliability impact from potential interoperability issues when creating an android app/service. I would like to figure out how process

Convert a completed project to a DLL

c# winforms dll

How can I convert a completed C# project to a DLL, in order to use it in other projects?