apneadiving / Google-Maps-for-Rails

Enables easy Google map + overlays creation in Ruby apps
https://apneadiving.github.io/
MIT License
2.26k stars 382 forks source link

Lots of markers and AJAX #197

Closed jerefrer closed 12 years ago

jerefrer commented 12 years ago

Hi there,

I've been using vanilla JS and jQuery to generate my google map with a lot of markers for a while now. But this was ugly code so I decided to move on to this gem seeing that it natively handles clustering and stuff.

The thing is I couldn't manage at this time to render the infoWindows through Ajax (as I did with my JS code). Is there any way to do this ?

Also is there best practises (with this gem) when dealing with lots of markers ?

Sorry if this is not a real issue, didn't know where else to ask :)

Cheers !

apneadiving commented 12 years ago

Hi,

There is no builtin way to render infowindows through ajax but it's not that difficult.

First you have to know which marker has been clicked, so you need the idof the related object. In controller:

@json = User.all.to_gmaps4rails do |user, marker|
    marker.json({ id: user.id })
end

Then in you view, after the call to the gmaps or gmaps4rails helper:

<% content_for :scripts do %>
Gmaps.map.callback = function() {
  for (var i = 0; i <  this.markers.length; ++i) {
     //Gmaps.map.markers[i] is the marker's wrapper
     //Gmaps.map.markers[i].serviceObject is the google map's object
     google.maps.event.addListener(Gmaps.map.markers[i].serviceObject, 'click', loadAndDisplayInfowindow(Gmaps.map.markers[i]) });
  }
};
function loadAndDisplayInfowindow(markerContainer){
  return function(){
     //your code to get the html with ajax, the user id is available in markerContainer.id

     //basic google map code to display infowindow
     var infowindow = new google.maps.InfoWindow({content: yourHTML });
     currentMap = Gmaps.map
     if (currentMap.visibleInfoWindow !== null)
     { currentMap.visibleInfoWindow.close(); }
     infowindow.open(currentMap.map, markerContainer.serviceObject)
     currentMap.visibleInfoWindow = infowindow;

  }
}
<% end %>

If you deal with multiple markers, you'd rather load them via ajax and add them on the fly using Gmaps.map.addMarkers(json).

The json should respect the format explained in this page: https://github.com/apneadiving/Google-Maps-for-Rails/wiki/Markers

apneadiving commented 12 years ago

BTW, please ask questions on stackoverflow next time!

jerefrer commented 12 years ago

Thank you so much for providing such details, managed to make it all work as I intended thanks to your example :)