gmaps4rails replaceMarkers not working (javascript)

谁说我不能喝 提交于 2019-12-01 12:20:10

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!

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!