首页 > 解决方案 > JS 异步加载 Google Maps API 时出错

问题描述

正如这个问题中所解释的,我已添加&callback=initialize到加载 Google Maps API 的脚本中:

<script src="https://maps.googleapis.com/maps/api/js?key=XXXX&amp;callback=initialize&amp;region=it&amp;libraries=places" async defer></script>

地图加载,但方向不再,我收到以下错误:

Uncaught ReferenceError: google is not defined
    at map.html:15

Uncaught (in promise) TypeError: Cannot read property 'push' of undefined
    at initialize (map.html:60)
    at js?key=XXXX&callback=initialize&region=it&libraries=places:130

我究竟做错了什么?

这是功能(我已更改 GPS 坐标并从标签/地址中删除信息以保护隐私):

var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var mkArray=[];

function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var myLatlng = new google.maps.LatLng(41.389835,12.413704);

var mapOptions = {
    zoom:16,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: myLatlng,
    styles: [
        {
            featureType: "poi.business",
            elementType: "labels",
            stylers: [
                    { visibility: "off" }
            ]
        }
    ]
  }

map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions-panel'));

var input = document.getElementById('start');
var options = {
    types: ['geocode'],
    componentRestrictions: {country: 'it'},
    rankBy: google.maps.places.RankBy.DISTANCE
};
var bounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(41.76, 12.33),
    new google.maps.LatLng(42.00, 12.64)
);
var autocomplete = new google.maps.places.Autocomplete(input, options);
autocomplete.setBounds(bounds);

var marker = new google.maps.Marker({
    position: myLatlng,
    map: map,
    title: 'XXXXX'
});
mkArray.push(marker);
}

function calcRoute(callback) {
    var start = document.getElementById('start').value;
    var end = "Address, Rome";
    var request = {
        origin:start,
        destination:end,
        travelMode: google.maps.DirectionsTravelMode.TRANSIT
    };
    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);

        // If a callback was passed, run it
        if(typeof callback === "function") {
            callback();
        }

      }
    });
    for (var i = 0, j = mkArray.length; i < j; i++) 
      mkArray[i].setMap(null);
}

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

标签: javascriptasynchronousgoogle-maps-api-3

解决方案


您正在尝试google在加载对象之前使用它:

var directionsService = new google.maps.DirectionsService()

你需要等待你的回调initialize被执行以使用google对象,所以我最好的建议是做这样的事情(就像你已经做过的那样directionsDisplay):

var directionService;

function initialize() {
   directionsService = new google.maps.DirectionsService();

   // other code here
}

在你的最后一行你想做什么?

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

你在这里犯了2个错误:

  1. google在您的回调被调用之前仍在尝试使用
  2. 您正在尝试为 GMaps API 回调和窗口load事件注册相同的函数。由于第一点,这不起作用,但即使这样做,你最终也会执行initialize两次,我认为这不是你想要的。

推荐阅读