From 86badfcefaa52325901198358759bace9c2f06cf Mon Sep 17 00:00:00 2001 From: Morten Ditlevsen Date: Thu, 2 Feb 2012 09:39:20 +0100 Subject: [PATCH] Haversine distance formula for getting distance (in meters) between two LatLngs --- src/geo/LatLng.js | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/geo/LatLng.js b/src/geo/LatLng.js index fae7cec4..254685f2 100644 --- a/src/geo/LatLng.js +++ b/src/geo/LatLng.js @@ -40,5 +40,19 @@ L.LatLng.prototype = { return 'LatLng(' + L.Util.formatNum(this.lat) + ', ' + L.Util.formatNum(this.lng) + ')'; + }, + + // Haversine distance formula, see http://en.wikipedia.org/wiki/Haversine_formula + distanceTo: function (/*LatLng*/ that)/*->Double*/ { + var R = 6378137; // earth radius in meters + var dLat = (that.lat - this.lat) * L.LatLng.DEG_TO_RAD; + var dLon = (that.lng - this.lng) * L.LatLng.DEG_TO_RAD; + var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + + Math.sin(dLon / 2) * Math.sin(dLon / 2) * + Math.cos(this.lat * L.LatLng.DEG_TO_RAD) * + Math.cos(that.lat * L.LatLng.DEG_TO_RAD); + var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); + var d = R * c; + return d; } };