我正在使用Google Maps API V3使用startPosition
在2个点endPosition
和google.maps.DirectionService
之间绘制步行路线。然后应打印以控制路线的距离和行程持续时间。
问题:虽然代码确实成功绘制了路径,但似乎directionsDisplay.setDirections
缺少回调函数来将距离和行程时间值返回给调用者。
此外,为directions_changed
添加一个监听器似乎不起作用,不会触发监听器!
如何将displayRoute()
的距离值和旅行时间值传递给其来电者?
displayRoute = function(startPosition, endPosition) {
var start = startPosition
var end = endPosition
var map = GoogleMaps.maps.map.instance
var directionsDisplay = new google.maps.DirectionsRenderer({'map': map});
var directionsService = new google.maps.DirectionsService();
var request = {
origin : start,
destination : end,
travelMode : google.maps.TravelMode.WALKING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response)
// ... and triggers listener for 'directions_changed'
}
});
google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
console.log('directions_changed') # not executed
console.log(response.routes[0]) # not executed
return response.routes[0]
});
}
var route = displayRoute(startPos, endPos)
console.log(route.duration.value) # undefined
console.log(route.distance.value) # undefined
答案 0 :(得分:1)
未定义,因为代码是,距离和持续时间是腿对象的属性。
console.log(response.routes[0].legs[0].duration.value);
console.log(response.routes[0].legs[0].distance.value);