Reputation: 1204
I am trying to find the distance between the two points p1 and p2 in two different methods from google api...
Here is the code...
var directionsService = new google.maps.DirectionsService();
var p1 = new google.maps.LatLng(45.463688, 9.18814);
var p2 = new google.maps.LatLng(46.0438317, 9.75936230000002);
var request = {
origin: p1,//'Melbourne VIC', // a city, full address, landmark etc
destination: p2,// 'Sydney NSW',
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
console.log(response.routes[0].legs[0].distance.value/1000); // the distance in metres
//console.log(response.routes[0].legs[0].duration.value);
}
else {
// oops, there's no route between these two locations
// every time this happens, a kitten dies
// so please, ensure your address is formatted properly
}
console.log(calcDistance(p1, p2));
//if(!(parseFloat("hello"))) console.log(parseFloat("12.222"));
//calculates distance between two points in km's
function calcDistance(p1, p2) {
return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
}
});
I am getting the outputs as follows... 103.847 // for the first log 78.35 // for the second log
Can some one explain me why this difference is there.... Am I going wrong some where....
Upvotes: 0
Views: 552
Reputation: 1294
The first method you use is a request to googles direction service and, as you set the travel mode to DRIVING
this response is a set of directions between the two points along roads. The distance is the distance you would have to drive.
The second method is to the geometry library, and is returning the shortest path across the sphere that is the world(the great-circle distance) between the two points. So distance 2 is shorter because it is direct, while distance 1 is the actual travel distance assuming you want to use roads.
Upvotes: 2