I tried to find a better way to calculate distance between two points on google maps, but the result it wasn't what I expected.
For example, those two solutions which I found here: Calculate distance between two points in google maps V3 are similarly (it produces aprox. 249.3424456 Km - but its wrong because distance between Bacau and Bucharest - Romania - are aprox. 300 Km).
The plnkr link: http://plnkr.co/edit/cv25C6pga0lla7xyBDRO?p=preview
Or:
$( document ).ready(function() {
var myLatLng = new google.maps.LatLng({ lat: 46.5610058, lng: 26.9098054 });
var myLatLng2 = new google.maps.LatLng({ lat: 44.391403, lng: 26.1157184 });
var calc1 = google.maps.geometry.spherical.computeDistanceBetween(myLatLng, myLatLng2)/1000;
console.log('calc1 = ' + calc1);
var start = { lat: 46.5610058, lng: 26.9098054 };
var stop = { lat: 44.391403, lng: 26.1157184 };
var rad = function(x) {
return x * Math.PI / 180;
};
var getDistance = function(p1, p2) {
var R = 6378137; // Earth’s mean radius in meter
var dLat = rad(p2.lat - p1.lat);
var dLong = rad(p2.lng - p1.lng);
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(rad(p1.lat)) * Math.cos(rad(p2.lat)) *
Math.sin(dLong / 2) * Math.sin(dLong / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c;
return d; // returns the distance in meter
};
var calc2 = getDistance(start, stop)/1000;
console.log('calc2 = ' + calc2);
document.getElementById("test").innerHTML = 'calc1 = ' + calc1 + '<br/>calc2 = ' + calc2;
});
When I try to calculate these distance with google maps web api http://maps.googleapis.com/maps/api/distancematrix/json?origins=46.5610058,26.9098054&destinations=44.391403,26.1157184 it tell me that the distance is 299 Km (which is the good value - distance between Bacau and Bucharest - Romania - are aprox. 300 Km).
I prefer to calculate locally rather than to access every time a website but why when I use 'google.maps.geometry.spherical.computeDistanceBetween' function or Haversine formula it calculate a wrong value?