【问题标题】:"Google is not defined" error - Trying to create infowindow Google Maps“未定义 Google”错误 - 尝试创建信息窗口 Google 地图
【发布时间】:2017-10-30 22:06:19
【问题描述】:

在 Google Maps API 中,我想在每次放置标记(标记都存储在数组中)时创建一个信息窗口。
声明信息窗口时:

var infowindow = new google.maps.InfoWindow();

我收到错误“未定义谷歌”。

只有在我将这行代码移动到创建标记的函数内时,这才会停止,但是每次我放置一个我理解是不好的做法的标记时,我都会创建变量 infowindow?

我希望在我的 JS 开头声明 infowindow,然后每次放置标记时都使用它。
我在 SO 上的其他答案中找不到任何帮助,我尝试重新排序 JS 文件,但到目前为止没有任何效果。

欢迎任何提示

【问题讨论】:

    标签: javascript android google-maps web google-maps-api-3


    【解决方案1】:

    这是因为谷歌地图是异步加载的,而您在谷歌地图 API 加载之前调用了这一行。

    这是等待加载的方法:

    <!-- include this snippet anywhere -->
    <script>
      var infoWindow;
      function initMap() {
         infoWindow = new google.maps.InfoWindow();
      }
    </script>
    
    <!-- include this script in your footer...or anywhere really -->
    <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap" async defer></script>
    

    例如,如果您尝试执行以下操作:

    <script>
      var infoWindow = new google.maps.InfoWindow();
    </script>
    <script src="https://maps.googleapis.com/maps/api/js key=YOUR_API_KEY&callback=initMap" async defer></script>
    

    然后你会得到一个错误,因为在执行 var infoWindow = ... 时不会定义 google,因为 API 尚未加载。

    您只能在执行回调(例如 initMap)后使用任何 google.maps.XXX

    【讨论】:

    • 这太棒了,不敢相信我没想到,谢谢。
    【解决方案2】:

    我经常看到“未定义谷歌”。我认为 Google Script 与 FF-addon 有问题。 FF 有重启选项,请尝试 Help > restart with the Add-ons Disabled。 :)

    【讨论】:

    • 我也听说过,但这在任何浏览器中都不适合我!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-07
    • 2015-06-10
    • 1970-01-01
    • 2017-09-28
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多