根据莱尼尔的回答:
var totalDistance = 0;
var totalDuration = 0;
var legs = directionsResult.routes[0].legs;
for(var i=0; i<legs.length; ++i) {
totalDistance += legs[i].distance.value;
totalDuration += legs[i].duration.value;
}
$('#distance').text(totalDistance);
$('#duration').text(totalDuration);
实际上,如果您没有任何航点,这也可以正常工作:
$('#distance').text(directionsResult.routes[0].legs[0].distance.text);
$('#duration').text(directionsResult.routes[0].legs[0].duration.text);
这是一个使用lodash的更完整的示例。不应该太难更换flatBy
,sum
如果你不使用它。
/**
* Computes the total driving distance between addresses. Result in meters.
*
* @param {string[]} addresses Array of address strings. Requires two or more.
* @returns {Promise} Driving distance in meters
*/
export default function calculateDistance(addresses) {
return new Promise((resolve, reject) => {
if(addresses.length < 2) {
return reject(new Error(`Distance calculation requires at least 2 stops, got ${addresses.length}`));
}
const {TravelMode, DirectionsService, DirectionsStatus} = google.maps;
const directionsService = new DirectionsService;
const origin = addresses.shift();
const destination = addresses.pop();
const waypoints = addresses.map(stop => ({location: stop}));
directionsService.route({
origin,
waypoints,
destination,
travelMode: TravelMode.DRIVING,
}, (response, status) => {
if(status === DirectionsStatus.OK) {
let distances = _.flatMap(response.routes, route => _.flatMap(route.legs, leg => leg.distance.value));
return resolve(_.sum(distances));
} else {
return reject(new Error(status));
}
});
});
}
请记住包含 Google Maps API:
<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places"></script>
另外,我很确定他们的服务条款也要求您显示 Google 地图。