有什么办法可以解决此错误“未定义Google”

时间:2019-10-22 10:01:18

标签: javascript google-maps laravel-5

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

代码段:

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);

4 个答案:

答案 0 :(得分:0)

在使用Gmap3时,我遇到了同样的错误“未定义google”。问题是我在包含“ 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
   });
});

答案 1 :(得分:0)

您应该添加此行

<脚本src =“ https://maps.googleapis.com/maps/api/jskey=YOUR_API_KEY&libraries=places&callback=initialize”

删除此行google.maps.event.addDomListener(窗口,“加载”,初始化);

答案 2 :(得分:0)

您不需要Google API即可计算距离。如果您具有经度和纬度,则可以通过数学方法进行计算-

访问:

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

答案 3 :(得分:0)

我能够通过删除

  • google.maps.event.addDomListener(窗口,“加载”,初始化);
  • &callback =初始化”
  • 异步延迟

,然后添加

  • &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

希望这会有所帮助!