这里有一些主题试图涵盖这一点:Gmaps4rails:动态加载时地图不显示尤其是这里:通过Ajax使用gmaps4rails渲染谷歌地图,还观看了动态更新 gmap 的截屏视频,但我似乎仍然无法使其工作。
仅当单击显示用户和报价之间方向的按钮时,我才尝试在下拉选项卡中加载地图。在我的 _location.html.erb 部分中,我有:
<%= gmaps({ "direction" => { "data" => { "from" => current_user.location, "to" => @offer.location } } })%>
(地点是地址)
现在,当立即渲染部分时,效果很好。然而,如果我在整个页面最初加载后尝试通过 AJAX 调用渲染部分内容,则不会显示 gmap。是否可以通过 AJAX 调用初始化并渲染 gmap 并显示方向?
原因很简单:该部分包含大量您无法以这种方式加载和执行的 JavaScript。
所以你不能在那里使用 RJS。
正确的方法是 UJS:通过 AJAX 调用获取数据并呈现结果。在下面的代码中,我使用 jQuery。
在您看来添加:
//include google script
<script type="text/javascript" src='http://maps.google.com/maps/api/js?sensor=false&libraries=geometry'></script>
//include gmaps4rails javascript
<%=javascript_include_tag 'gmaps4rails' %>
<script type="text/javascript" charset="utf-8">
//load map when button click (replace with what you want)
$('#ajax_map').click(function(){
//you have to set a size to the div otherwise the map won't display, that's the purpose of these css classes
$('#map_container').addClass('map_container');
$('#gmaps4rails_map').addClass('gmaps4rails_map');
//create the map object
Gmaps4Rails.initialize();
//of course, replace these two with your dynamic data, you'd have to use some $.ajax jQuery method.
Gmaps4Rails.direction_conf.origin = 'toulon, france';
Gmaps4Rails.direction_conf.destination = 'paris, france';
//read the js file, you can customize much more: https://github.com/apneadiving/Google-Maps-for-Rails/blob/master/public/javascripts/gmaps4rails.js
Gmaps4Rails.create_direction();
});
</script>
<div id="map_container">
<div id="gmaps4rails_map"></div>
</div>
<button type="button" id="ajax_map">Ajax Map</button>
在 CSS 中添加以下类:
#map-container {
width: 800px;
}
#gmaps4rails_map {
width: 800px;
height: 400px;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)