我正在尝试使用gmaps4rails(即使用AJAX回调)动态更新谷歌 Map 上的标记 . 我发现gmaps4rails的文档非常分散且不清楚 .
我已经成功地使用build_markers方法在 Map 上显示标记(根据视频教程v2) .
我的控制器代码:
# GET /telemetry_recordings
def index
@telemetry_recordings = TelemetryRecording.all
@hash = Gmaps4rails.build_markers(@telemetry_recordings) do |telemetry_recording, marker|
marker.lat telemetry_recording.latitude
marker.lng telemetry_recording.longitude
marker.title telemetry_recording.delivery_unit.driver.full_name
marker.infowindow telemetry_recording.delivery_unit.driver.full_name
end
end
我的观看代码:
<script type="text/javascript">
handler = Gmaps.build('Google');
handler.buildMap({ provider: {}, internal: {id: 'map'}}, function(){
markers = handler.addMarkers(<%=raw @hash.to_json %>);
handler.bounds.extendWith(markers);
handler.fitMapToBounds();
});
</script>
现在,为了实现动态更新,我在我的视图中添加了以下脚本:
<script type="text/javascript">
jQuery(function($) {
$('body').on('click', '#replace_markers', function(){
$.getJSON("/telemetry_recordings", function(data){
Gmaps.map.replaceMarkers(data);
});
});
});
</script>
以及一个按钮:
<button id="replace_markers">Refresh</button>
并且,我已将以下代码添加到我的控制器:
respond_to :json, :html
# GET /telemetry_recordings
def index
@json = TelemetryRecording.all.to_gmaps4rails
respond_with @json
end
注意:TelemetryRecording类有3个属性:纬度(float),经度(float)和location_time(DateTime)
这会导致以下错误:
undefined method `to_gmaps4rails' for #<TelemetryRecording::ActiveRecord_Relation:0x55dee78>
根据文档,我已经安装了gmaps4rails gem,在我的application.js文件中添加了// = require下划线和// = require gmaps / google,并在我的视图中包含以下脚本:
<script src="//google-maps-utility-library-v3.googlecode.com/svn/tags/markerclustererplus/2.0.14/src/markerclusterer_packed.js" type="text/javascript"></script>
<script src="//maps.google.com/maps/api/js?v=3.13&sensor=false&libraries=geometry" type="text/javascript"></script>
我在这里正确使用to_gmaps4rails吗? (我的理解是它将具有纬度/经度属性的对象转换为标记数组,例如[{“lat”:“x”,“lng”:“y”},{“lat”:“x”,“ lng“:”y“}] . 为什么不定义?
1 回答
您正在使用v1.x和2.x中的代码 .
to_gmaps4rails
已从代码库中删除 . 所以你的第一枪是好的:在js