从Google Maps API V3获取旅行距离和旅行时间

时间:2015-10-23 05:17:13

标签: javascript node.js google-maps

我正在使用Google Maps API V3使用startPosition在2个点endPositiongoogle.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

1 个答案:

答案 0 :(得分:1)

未定义,因为代码是,距离和持续时间是腿对象的属性。 console.log(response.routes[0].legs[0].duration.value); console.log(response.routes[0].legs[0].distance.value);