-
Notifications
You must be signed in to change notification settings - Fork 382
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]
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);