【问题标题】:Is there any way to fix this error 'google is not defined'有没有办法解决这个错误“谷歌未定义”
【发布时间】:2020-02-18 10:55:18
【问题描述】:

我正在使用Distant Matrix API 来计算地点和建议之间的距离。我在索引刀片上使用了一个脚本,它提示'google is not defined'

代码 sn-p:

function initialize() {
  var input = document.getElementById('searchloc');
  var options = {
    types: ['geocode'], // this should work!
    componentRestrictions: {country: "ae"}
  };
  var autocomplete = new google.maps.places.Autocomplete(input, options);     
}

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

【问题讨论】:

    标签: javascript google-maps laravel-5


    【解决方案1】:

    我在使用 Gmap3 时遇到了同样的错误“谷歌未定义”。问题是我在包含“google”之前包含了“gmap3”,所以我颠倒了顺序:

    <script src="https://maps.googleapis.com/maps/api/js?sensor=false" type="text/javascript"></script>
    <script src="/assets/gmap3.js?body=1" type="text/javascript"></script>
    

    在窗口加载函数中也调用你的函数,

    $(function(){
       $(window).load(function(){
           //Here is my logic now
       });
    });
    

    【讨论】:

    • 实际上我得到了肯定的结果,只有我刷新页面几次
    【解决方案2】:

    你应该添加这一行

    删除这一行 google.maps.event.addDomListener(window, 'load', initialize);

    【讨论】:

      【解决方案3】:

      您不需要 Google API 来计算距离。如果你有纬度和经度,你可以在数学上做 -

      访问:

      https://www.geodatasource.com/developers/javascript

      【讨论】:

      • 我的代码依赖于此,所以我无法更改代码,但谢谢
      【解决方案4】:

      我可以通过删除做到这一点:

      • google.maps.event.addDomListener(window, 'load', initialize);
      • &callback=initialize"
      • 异步延迟

      然后通过添加

      • &libraries=places
      • onload="initialize()"

      所以整个代码如下所示:

      <body onload="initialize()">
          <input type="text" id="searchloc" />
          <script>
            var map;
            function initialize() {
                var input = document.getElementById('searchloc');
                var options = {
                  types: ['geocode'], // this should work!
                  componentRestrictions: {country: "ae"}
                };
                var autocomplete = new google.maps.places.Autocomplete(input, options); 
            }
          </script>
          <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBJSAn2t5Aosg0yhwXxbf6tRvQXmS8vDKU&libraries=places"></script>
        </body>
      

      演示链接:https://jsbin.com/dutewup/edit?html,output

      希望这会有所帮助!

      【讨论】:

        猜你喜欢
        • 2020-12-13
        • 1970-01-01
        • 1970-01-01
        • 2021-05-28
        • 2021-06-05
        • 1970-01-01
        • 2020-02-25
        • 1970-01-01
        • 2021-05-07
        相关资源
        最近更新 更多