Wednesday, September 15, 2010

Google Maps API V3 - distanceFrom method

I recently started upgrading a website, which uses Google Maps, from V2 to V3. On one page I needed to calculate the distance between two GLatLngs. This was easily done in V2 with the GLatLng.distanceFrom method. Although this method seems to have disappeared when V3 was released, so I created it:

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!