-
Notifications
You must be signed in to change notification settings - Fork 383
Adding an id to markers and access them later
desnw edited this page Dec 21, 2016
·
10 revisions
Ensure that your JSON being generated in your controller is including the id attribute of your object:
@hash = Gmaps4rails.build_markers(@users) do |user, marker|
marker.lat user.latitude
marker.lng user.longitude
marker.json({ :id => user.id })
marker.infowindow render_to_string(:partial => "/users/my_template", :locals => { :object => user})
end
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 = <%= raw @hash.to_json %> // 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();
Gmaps.store.markers.filter(function(m) { return m.serviceObject.id == id; })[0]
Keep in mind that you are not able to get the latitude/longitude of a marker while it is within a cluster; in that situation, you must first disable clustering, or zoom in enough for the markers to be placed on the map.
This can be done by modifying your handler:
handler = Gmaps.build('Google', { markers: { clusterer: null } });
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);