Skip to content Skip to sidebar Skip to footer

Gmaps4rails Replacemarkers Not Working (javascript)

stack details ruby 1.9.2p180, rails 3.0.9, gmaps4rails 1.0.2, jquery.json-2.3.min.js Background I am a newbie to gmaps4rails and really like the gem. All is working well so far, bu

Solution 1:

I broke my brain over this for quite a while being new to both JS and Rails ... I was unable to get my head around converting from a RAILS jSON string created in my controller to a JavaScript array of JSON objects.

I tried just grabbing the string generated by _to_gmaps4rails but it was full of escaped characters. I now know this was due to changes in Rails to prevent scripts from getting inserted by data.

I tried lots of things, like parsing the JSON on the browser side, passing the data elements individually, etc.

Turns out all I needed was the raw() function which prevented the string from being escaped. Here's my working code:

in my controller:

@markers = plots.to_gmaps4rails do|plot, marker|
    escaped_comment = ERB::Util.html_escape plot.comment
    marker.infowindow render_to_string(:partial => 'my_partial', :locals => { :plot => plot})
    marker.picture ( {
        "picture" => ActionController::Base.helpers.asset_path(plot.marker) ,          # string,  mandatory"width" =>   64,          # integer, mandatory"height" => 32,          # integer, mandatory
    })
    marker.title   plot.title
    marker.json({ :id => plot.id, :comment => escaped_comment})
end

in my JS (returned from format.js Ajax call):

markers = <%=raw(@markers)%>
Gmaps.map.replaceMarkers(markers)

Hope this helps someone else!

Solution 2:

This issue is resolved by upgrading to gmaps4rails 1.3.0. Another problem I faced was to make sure that the replaceMarkers method is given an array of markers, not a JSON string

Note that when you are creating a new map (on the server side), you must give a JSON string for the markers.

When you are calling replaceMarkers on the client side (in JS), you must give an array of marker objects.

Post a Comment for "Gmaps4rails Replacemarkers Not Working (javascript)"