我刚开始使用路线服务。我已经对几个位置进行了硬编码,以确保它可以正常工作。我不断收到相同的错误(未捕获的TypeError:无法读取未定义的属性“ route”),我不知道为什么。该代码几乎是该文档中代码的精确副本。
<script>
var map;
var directionsService;
var directionsRenderer;
function initMap() {
var directionsService = new google.maps.DirectionsService();
var directionsRenderer = new google.maps.DirectionsRenderer();
var chicago = new google.maps.LatLng(38.627003, -90.199402);
var mapOptions = {
zoom:10,
center: chicago
}
map = new google.maps.Map(document.getElementById('map'), mapOptions);
directionsRenderer.setMap(map);
}
function calcRoute(start, end) {
var request = {
origin: "St Louis, MO",
destination: "Chicago, IL",
travelMode: 'DRIVING'
};
console.log(request);
directionsService.route(request, function(result, status) {
if (status == 'OK') {
directionsRenderer.setDirections(result);
}
});
}
</script>
答案 0 :(得分:0)
没关系!我想到了。我在initMap()中重新声明了directionService和directionRender,这改变了这两个变量的范围!我将其更改为以下内容,并且有效。
var map;
var directionsService;
var directionsRenderer;
function initMap() {
directionsService = new google.maps.DirectionsService();
directionsRenderer = new google.maps.DirectionsRenderer();