Search code examples
ruby-on-railsruby-on-rails-3backbone.jsgmaps4rails

backbone.js and gmaps4rails maps initialization


I'm currently trying to bring backbone.js and gmaps4rails together in my rails project but I'm having trouble with the map initialization.

I have log messages to see that my Router works and the view is reached from the backbone side. Now I'm in my views backbone file and try to initialize the Gmaps4RailsGoogle wrapper.

In my rails view, I'm genereating the divs for gmaps4rails like this:

<%= content_tag "div", class: "map_container" do %>
    <%= content_tag "div", id: "map" do %>
    <% end %>
<% end %>

I can't load the maps in my view, here is the code:

  console.log "Loading map..."
  Gmaps.map = new Gmaps4RailsGoogle()
  Gmaps.load_map = ->
    Gmaps.map.map_options.auto_adjust = true
    Gmaps.map.initialize()
    Gmaps.map.markers markers
    Gmaps.map.markers_conf.do_clustering = true
    Gmaps.map.create_markers()
    Gmaps.map.adjustMapToBounds()
    Gmaps.map.callback()

  Gmaps.loadMaps()

I know that the loadMaps() call should be onload, but that seems to have happened already. Where should I place that then?

I see the log but on the console it tells me the following error:

google is not defined
http://localhost:3000/assets/gmaps4rails/gmaps4rails.googlemaps.js?body=1
Line 74

Is it possible to let gmaps4rails genereate all the necessary script includes and then access the variables provided from within backbone.js?

Please let me know what informations would be needed when these are not enough.

Thanks, Kjellski


Solution

  • I've found the answer to the question, or at least parts of it. I'm now using the following call to gmaps in my index.html.erb view from rails:

    <%= gmaps({ "map_options" => { "zoom" => 15,
                                   "auto_adjust" => true,
                                   "detect_location" => true,
                                   "center_on_user" => true }}, false, true) %>
    

    This will generate the needed Gmaps object which I'm actually using from backbone now. My backbone view template is now Empty which feel wrong. To do this right, I would need to set up googlemaps from within my backbone view. I've not found a good answer for that until now, but it's working like this. In my view, I've set the initialize to listen on the collection reset and told it to call my function to add the markers like this:

    initialize: ->
      @collection.on('reset', @loadMarkersOnMap, this)
    
    render: ->
      ...
    
    loadMarkersOnMap: ->
      Gmaps.map.addMarkers @collection.toJSON()
      Gmaps.map.showMarkers()
    

    Hope this helps if someone tries to do the same. I would also like to add a solution for moving the calls to initialze the Gmaps4RailsX properly in my backbone files. Any suggestions?