gpt4 book ai didi

javascript - gmaps4rails replaceMarkers 不工作(javascript)

转载 作者:行者123 更新时间:2023-11-30 13:28:25 25 4
gpt4 key购买 nike

堆栈详细信息 ruby 1.9.2p180, rails 3.0.9,gmaps4rails 1.0.2,jquery.json-2.3.min.js

背景我是 gmaps4rails 的新手,非常喜欢这个 gem。到目前为止一切正常,但我第一次尝试动态更新标记。我在 application.js 中执行以下操作:

var markers_json = $.toJSON(markers_array);
Gmaps.map.replaceMarkers(markers_json);

这不起作用并给出以下错误

Uncaught TypeError: Cannot read property 'position' of undefined
extendBoundsWithMarkers in gmaps4rails.googlemaps.js:204
Gmaps4Rails.adjustMapToBounds in gmaps4rails.base.js:443
Gmaps4Rails.create_markers in gmaps4rails.base.js:321
Gmaps4Rails.addMarkers in gmaps4rails.base.js:389
Gmaps4Rails.replaceMarkers in gmaps4rails.base.js:381

目前已完成调查

  1. 确认 map 的初始创建是通过提供标记作为 json 字符串完成的。

  2. 已确认我在 replaceMarkers 调用中提供了相同格式的 json 字符串

  3. 确认在源代码中,当在初始页面加载时调用 addMarkers 时,标记采用对象数组的形式,但 replaceMarkers 调用(正如我上面提到的)包含一个 JSON 字符串

其他尝试试图在不转换为 JSON 的情况下传递标记

Gmaps.map.replaceMarkers(markers_array);

但效果不佳。

最佳答案

作为 JS 和 Rails 的新手,我为此伤脑筋了很长一段时间……我无法理解如何将在我的 Controller 中创建的 RAILS jSON 字符串转换为 JSON 对象的 JavaScript 数组。

我尝试只抓取 _to_gmaps4rails 生成的字符串,但它充满了转义字符。我现在知道这是由于 Rails 发生了变化,以防止脚本被数据插入。

我尝试了很多东西,比如在浏览器端解析 JSON,单独传递数据元素等。

事实证明,我所需要的只是防止字符串被转义的 raw() 函数。这是我的工作代码:

在我的 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

在我的 JS 中(从 format.js Ajax 调用返回):

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

希望这对其他人有帮助!

关于javascript - gmaps4rails replaceMarkers 不工作(javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7680059/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com