I used to be able to get it like this:
directionsService.route(directionsRequest, function(directionsResult, directionsStatus) {
var directionsRenderer = new google.maps.DirectionsRenderer({
directions: directionsResult,
map: map
});
$('#distance').text(directionsResult.trips[0].routes[0].distance.text)
$('#duration').text(directionsResult.trips[0].routes[0].duration.text)
})
But it looks like they changed their API on me! Looks like trips
is no longer there, and routes
only gives you a bunch of legs... do I really have to iterate over all the legs and sum up the distance now?
As per Leniel's answer:
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);
Actually, this works just fine too, if you don't have any waypoints:
$('#distance').text(directionsResult.routes[0].legs[0].distance.text);
$('#duration').text(directionsResult.routes[0].legs[0].duration.text);
Here's a fuller example using lodash. Shouldn't be too hard to replace flatBy
and sum
if you're not using it.
/**
* 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));
}
});
});
}
Remember to include the Google Maps API:
<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places"></script>
Also, I'm pretty sure their ToS require you to display a Google Map too.
Take a look here:
It looks like you now have to sum up each leg distance.
legs[] contains an array of DirectionsLeg objects, each of which contains information about a leg of the route, from two locations within the given route. A separate leg will be present for each waypoint or destination specified. (A route with no waypoints will contain exactly one DirectionsLeg.) Each leg consists of a series of DirectionSteps.
Mark's answer is in meters for totalDistance
and seconds for totalDuration
.
If you're in the U.S. and want miles with a single decimal point, multiply like so:
var METERS_TO_MILES = 0.000621371192;
$('#distance').text((Math.round( totalDistance * METERS_TO_MILES * 10 ) / 10)+' miles');
And if you want minutes:
$('#distance').text(Math.round( totalDuration / 60 )+' minutes');
you can easily get by using :
Distance by using:
directionsDisplay.directions.routes[0].legs[0].distance.text
Duration by using:
directionsDisplay.directions.routes[0].legs[0].duration.text
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
margin: 0;
padding: 0;
height: 100%;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var chicago = new google.maps.LatLng(26.912417, 75.787288);
var mapOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: chicago
}
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
directionsDisplay.setMap(map);
}
function calcRoute() {
var start = document.getElementById("start").value;
var end = document.getElementById("end").value;
var waypts = [];
var checkboxArray = document.getElementById('waypoints');
for(var i = 0; i < checkboxArray.length; i++) {
if(checkboxArray.options[i].selected == true) {
waypts.push({
location: checkboxArray[i].value,
stopover: true
});
}
}
var request = {
origin: start,
destination: end,
waypoints: waypts,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if(status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
// alert(route.legs[1].duration.text);
var summaryPanel = document.getElementById('directions_panel');
summaryPanel.innerHTML = '';
// For each route, display summary information.
for(var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment + '</b><br>';
summaryPanel.innerHTML += route.legs[i].start_address + ' to ';
summaryPanel.innerHTML += route.legs[i].end_address + '<br>';
summaryPanel.innerHTML += route.legs[i].duration.text + '<br>';
summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>';
}
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<!-- <div id="map-canvas"></div>-->
<div>
<strong>Start: </strong>
<select id="start" onChange="calcRoute();">
<option value="Jaipur">Jaipur</option>
<option value="jagatpura">jagatpura</option>
<option value="malviya nagar, Jaipur">Malviya Nagar</option>
<option value="khatu">Sikar</option>
<option value="Dausa">Dausa</option>
<option value="Luniawas">Luniyawas</option>
<option value="Karoli">Karoli</option>
<option value="Baran">Baran</option>
<option value="Sawai Madhopur">Sawai Madhopur</option>
<option value="Udaipur">Udaipur</option>
<option value="Bikaner">Bikaner</option>
<option value="Churu">Churu</option>
</select>
<strong>End: </strong>
<select id="end" onChange="calcRoute();">
<option value="Jaipur">Jaipur</option>
<option value="bassi">bassi</option>
<option value="goner">goner</option>
<option value="Khaniya">Khaniya</option>
<option value="Luniawas">Luniyawas</option>
<option value="Ajmer">Ajmer</option>
<option value="Karoli">Karoli</option>
<option value="Baran">Baran</option>
<option value="Sawai Madhopur">Sawai Madhopur</option>
<option value="Udaipur">Udaipur</option>
<option value="Bikaner">Bikaner</option>
<option value="Churu">Churu</option>
</select>
</div>
<div>
<strong>Mode of Travel: </strong>
<select id="mode" onChange="calcRoute();">
<option value="DRIVING">Driving</option>
<option value="WALKING">Walking</option>
<option value="BICYCLING">Bicycling</option>
<option value="TRANSIT">Transit</option>
</select>
<select multiple id="waypoints" onChange="calcRoute();">
<option value="bassi">bassi</input>
<option value="chainpura">chainpura</input>
<option value="Kanauta">Kanauta</input>
</select>
</div>
<div id="map-canvas" style="float:left;width:70%; height:40%"></div>
<div id="directions_panel" style="margin:20px;background-color:#FFEE77;"></div>
</body>
</html>
来源:https://stackoverflow.com/questions/3251609/how-to-get-total-driving-distance-with-google-maps-api-v3