gmaps4rails replaceMarkers not working (javascript)

后端 未结 2 1833
执笔经年
执笔经年 2021-01-15 18:32

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 re

2条回答
  •  耶瑟儿~
    2021-01-15 19:13

    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!

提交回复
热议问题