我复制了this question的代码,尝试获取两点的路线。显示了点的标记和方向。但是,我在控制台Uncaught ReferenceError: google is not defined
中收到错误,只是想知道如何摆脱它。
以下是我从上述链接问题的接受答案中获得的JavaScript代码。
function initMap() {
var pointA = new google.maps.LatLng(51.7519, -1.2578),
pointB = new google.maps.LatLng(50.8429, -0.1313),
myOptions = {
zoom: 7,
center: pointA
},
map = new google.maps.Map(document.getElementById('map-canvas'), myOptions),
// Instantiate a directions service.
directionsService = new google.maps.DirectionsService,
directionsDisplay = new google.maps.DirectionsRenderer({
map: map
}),
markerA = new google.maps.Marker({
position: pointA,
title: "point A",
label: "A",
map: map
}),
markerB = new google.maps.Marker({
position: pointB,
title: "point B",
label: "B",
map: map
});
// get route from A to B
calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB);
}
function calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB) {
directionsService.route({
origin: pointA,
destination: pointB,
travelMode: google.maps.TravelMode.DRIVING
}, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
initMap();
错误屏幕截图:
答案 0 :(得分:5)
Google async defer
标记上的script
正在异步(非即时)加载Google脚本。
当您的脚本正在加载并立即执行时。因此,您的脚本甚至在加载到文档之前就引用了Google API。
删除async defer
会在您之前正常加载Google脚本,因此您可以确定它可用。