Skip to content

Adding an id to markers and access them later

desnw edited this page Dec 21, 2016 · 10 revisions

Adding markers

Here we cannot use handler.addMarkers(...) because we need to set an id on each of the marker. So we have to iterate over each marker, set the id, and add it to the map.

markers = ... // Fetch JSON with markers
Gmaps.store = {} // Initialize storage
Gmaps.store.markers = markers.map(function(m) {
  marker = handler.addMarker(m);
  marker.serviceObject.set('id', m.id); // You can add other attributes using set
  return marker;
});
handler.bounds.extendWith(Gmaps.store.markers);
handler.fitMapToBounds();

Retrieving a specific marker

Gmaps.store.markers.filter(function(m) { return m.serviceObject.id == id; })[0]

Real world example

For instance, here's how to define a function selectMarker(id) that adds a bouncing animation and pans to a specific marker

Gmaps.selectMarker = function(id) {
  $.each(Gmaps.store.markers, function() {
    if (this.serviceObject.id == id) {
      this.panTo();
      this.serviceObject.setAnimation(google.maps.Animation.BOUNCE);
    }
    else this.serviceObject.setAnimation(null);
  });
}

Usage

Gmaps.selectMarker(1);