Prevent Google maps JS executing multiple times caused by Rails Turbolinks

前端 未结 5 1315
盖世英雄少女心
盖世英雄少女心 2021-02-19 07:30

I\'m currently working on Rails app that is getting the following error:

You have included the Google Maps API multiple times on this page. This may ca

相关标签:
5条回答
  • 2021-02-19 07:53

    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.

    0 讨论(0)
  • 2021-02-19 08:03

    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

    0 讨论(0)
  • 2021-02-19 08:08

    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.

    0 讨论(0)
  • 2021-02-19 08:15

    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.

    0 讨论(0)
  • 2021-02-19 08:18

    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

    0 讨论(0)
提交回复
热议问题