异步加载Google Maps API的JS错误

时间:2018-12-06 14:41:28

标签: javascript asynchronous google-maps-api-3

this问题中所述,我已向加载Google Maps API的脚本中添加了&callback=initialize

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

1 个答案:

答案 0 :(得分:1)

您正在尝试使用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);

您在这里犯了两个错误:

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