Prevent Google maps JS executing multiple times caused by Rails Turbolinks

扶醉桌前 提交于 2019-12-04 01:35:23

Instead of <script async defer src="https://maps.googleapis.com/maps/api/js?signed_in=false&callback=initMap"></script> make it a regular <script></script> tag and add the following below your initMap function:

if(window.google){
  initMap();
} else{
  $.ajax('https://maps.googleapis.com/maps/api/js?signed_in=false&callback=initMap', {
    crossDomain: true,
    dataType: 'script'
  });
}

If you aren't using jquery then just use XMLHttpRequest instead.

Adding data-turbolinks-eval="false" to the script tag will tell turbolinks not to re-evaluate it.

<script async defer src="https://maps.googleapis.com/maps/api/js?signed_in=false&callback=initMap" data-turbolinks-eval="false"></script>

See https://github.com/turbolinks/turbolinks#working-with-script-elements

Worked in our case, where all our script tags were in <head> as per turbolinks docs.

Try this too....

google.maps.event.addDomListener(window, 'turbolinks:load', initialize);

And remeber, all google script have to stay after Turbolink, like this:

= 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'

See more at: https://github.com/turbolinks/turbolinks

I had faced the same problem, unfortunately this might be of no help to you after so many months.

I moved:

<script type="text/javascript" src="http://maps.google.com/maps/api/js?libraries=places"></script>

in head tag after <%= csrf_meta_tags %>, and moved the:

<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>

after /body tag.

By doing so I resolved this issue:

You have included the Google Maps API multiple times on this page. This may cause unexpected errors.

Added data-no-turbolink to the link in navigation bar, the page where I have map. This helped me keep using turbolinks in all pages without that error and as well as let me generate the map when that page was accessed.

adding data-turbolinks-eval=false to the script tag solves the problem

See the docks of the turbolinks gem for more details https://github.com/turbolinks/turbolinks-classic#evaluating-script-tags

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!