Search code examples
ruby-on-railsgoogle-mapsgmaps4rails

gmaps4rails v2 - multiple maps


I'm trying to have multiple maps displayed just like it was possible in v1 as explained here: https://github.com/apneadiving/Google-Maps-for-Rails/wiki/(Multiple)-Maps.

I get all maps to be displayed, using unique ids ('map_n', where n is the), but all the markers are displayed on the last one. Here's the code in my "_map.haml" partial:

- map_id = 'map' << "_#{counter}"

.map_container
  .gmaps4rails_map{ id: map_id }

:javascript
  handler = Gmaps.build('Google');
  handler.buildMap({ provider: {}, internal: { id: '#{ map_id }' } }, function(){
    markers = handler.addMarkers([
      {
        "lat": 0,
        "lng": 0,
        "infowindow": "hello!"
      }
    ]);
    handler.bounds.extendWith(markers);
    handler.fitMapToBounds();
    handler.getMap().setZoom(12);
  });

What's the proper way to handle this ?


Solution

  • You simply have to create one handler per map with its dedicated id

    After rereading your question, I feel like its an issue due to variables visibility:

    • handler is attached to the window
    • for each loop the previous instance is replaced by the new one

    So:

    • wrap everything in one function to restrain variables scope

    Or:

    • change handler's name in each loop