异步加载Google Maps API时出现JS错误



如本问题所述,我已将&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);

您试图在加载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,我认为这不是你想要的

最新更新