防止谷歌地图JS由Rails Turbolinks多次执行
我目前正在处理Rails应用程序,它收到以下错误:
您已在此页面上多次添加Google Maps API。 这可能会导致意外错误。
经过一番研究后,我发现Turbolinks导致了这个问题。 单击link_to
,Google地图创建的所有DOM元素都将保留在DOM中。 当渲染新页面时,会添加另一组Google Map DOM元素,从而导致重复和错误。
我可以通过简单地将'data-no-turbolink' => true
到我的link_to
来快速解决这个问题,但这会破坏使用Turbolinks的目的,因为它会强制刷新。
我想知道是否有一个潜在的解决方法来阻止这种复制而不关闭Turbolinks?
map.js:
var initMap = function initMap() { if (typeof mapLatLng != "undefined") { // we can use this to set the map zoom // in different places. // use: window.setZoom = 12; if (typeof setZoom ==! "undefined") { var mapZoom = setZoom; } else { var mapZoom = 14; } var map = new google.maps.Map(document.getElementById('map'), { zoom: mapZoom, center: mapLatLng, disableDefaultUI: true, scrollwheel: false }); var markerSVG = { path: 'M1152 640q0-106-75-181t-181-75-181 75-75 181 75 181 181 75 181-75 75-181zm256 0q0 109-33 179l-364 774q-16 33-47.5 52t-67.5 19-67.5-19-46.5-52l-365-774q-33-70-33-179 0-212 150-362t362-150 362 150 150 362z', fillColor: '#f32e74', fillOpacity: 1, strokeWeight: 0, anchor: new google.maps.Point(870,1650), scale: (0.02, 0.02) }; var mapMarker = new google.maps.Marker({ position: map.getCenter(), map: map, icon: markerSVG, }); } }
视图:
window.mapLatLng = {lat: , lng: };
而不是使其成为常规
标记并添加你的initMap函数下面是:
if(window.google){ initMap(); } else{ $.ajax('https://maps.googleapis.com/maps/api/js?signed_in=false&callback=initMap', { crossDomain: true, dataType: 'script' }); }
如果您不使用jquery,那么只需使用XMLHttpRequest。
向script标签添加data-turbolinks-eval="false"
将告诉turbolinks不要重新评估它。
请参阅https://github.com/turbolinks/turbolinks#working-with-script-elements
在我们的案例中工作,根据turbolinks文档,我们的所有脚本标签都在中。
试试这个….
google.maps.event.addDomListener(window, 'turbolinks:load', initialize)
;
记住,所有google脚本都必须留在Turbolink之后,如下所示:
= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' = javascript_include_tag 'https://maps.googleapis.com/maps/api/js', 'data-turbolinks-track': 'reload' = javascript_include_tag 'gmap', 'data-turbolinks-track': 'reload'
有关详细信息,请访问: https : //github.com/turbolinks/turbolinks
我遇到了同样的问题,不幸的是,经过这么多个月,这可能对你没有任何帮助。
我搬家了:
在<%= csrf_meta_tags%>之后的head标签中,移动了:
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
后/身体标签。
通过这样做,我解决了这个问题:
您已在此页面上多次添加Google Maps API。 这可能会导致意外错误。
添加数据 – 无涡轮链接到导航栏中的链接,即我有地图的页面。 这有助于我在所有页面中继续使用turbolinks而不会出现该错误,并且让我在访问该页面时生成地图。
在脚本标记中添加data-turbolinks-eval=false
可以解决问题
有关详细信息,请参阅turbolinks gem的底座https://github.com/turbolinks/turbolinks-classic#evaluating-script-tags