Sergio Mac-Intosh Sergio Mac-Intosh - 1 month ago 6
Javascript Question

How can i get the total distance in KM in my javascript

How can i get the total distance in KM in my javascript. It is shown already on top of the Panel, but i need this value also in my javascript. My javascript is as followed:

var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();

var map = new google.maps.Map(document.getElementById('map'), {
zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP
});

directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('panel'));


var een = '52.3641205';
var twee = '4.905697000000032';
var drie = '52.6010666';
var vier = '4.73768229999996';

var p1 = new google.maps.LatLng(een, twee);
var p2 = new google.maps.LatLng(drie, vier);

var request = {
origin: p1,
destination: p2,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};

directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {

alert('Total travel distance is:' + response);

directionsDisplay.setDirections(response);

}
});


The functionality is working but i would also like to alert the total distance. This is seen at the top of the panel. The panel will be invisible in the future so a getelementbyID function is not enough.

Can someone help me with this?

Thank You!

Sergio

Answer

In your request, set units=metric.

Then use: distance = response.routes[0].legs[0].distance.text; in your alert.