`google.maps.LatLng.prototype.distanceFrom = function(p2) {`

var R = 6378137; // earth's mean radius in meters (this was a parameter in V2)

var rad = function(x) {return x*Math.PI/180;}

var dLat = rad(p2.lat() - this.lat());

var dLong = rad(p2.lng() - this.lng());

var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(rad(this.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.toFixed(3);

}

Using the Haversine formula (found here) I created a custom method within the LatLng class. I altered it a little in order to get the distance in meters instead of kilometres. Seems to work as intended!

## No comments:

## Post a Comment