diff --git a/CHANGELOG.md b/CHANGELOG.md index a7e0bafe..b3a7b90e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,6 +41,7 @@ Leaflet Changelog * Added `ImageOverlay` `load` event. [#213](https://github.com/CloudMade/Leaflet/issues/213) * Added `minWidth` option to `Popup` (by [@marphi](https://github.com/marphi)). [#214](https://github.com/CloudMade/Leaflet/pull/214) * Improved `LatLng` constructor to be more tolerant (and throw descriptive error if latitude or longitude can't be interpreted as a number). [#136](https://github.com/CloudMade/Leaflet/issues/136) + * Added `LatLng` `distanceTo` method (great circle distance) (by [@mortenbekditlevsen](https://github.com/mortenbekditlevsen)). [#462](https://github.com/CloudMade/Leaflet/pull/462) * Added `LatLngBounds` `toBBoxString` method for convenience (by [@JasonSanford](https://github.com/JasonSanford)). [#263](https://github.com/CloudMade/Leaflet/pull/263) * Added `LatLngBounds` `intersects(otherBounds)` method (thanks to [@pagameba](https://github.com/pagameba)). [#350](https://github.com/CloudMade/Leaflet/pull/350) * Added `L.Util.template` method for simple string template evaluation. diff --git a/src/geo/LatLng.js b/src/geo/LatLng.js index 254685f2..03897ac6 100644 --- a/src/geo/LatLng.js +++ b/src/geo/LatLng.js @@ -43,16 +43,18 @@ L.LatLng.prototype = { }, // 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; + distanceTo: function (/*LatLng*/ other)/*->Double*/ { + var R = 6378137, // earth radius in meters + d2r = L.LatLng.DEG_TO_RAD, + dLat = (other.lat - this.lat) * d2r, + dLon = (other.lng - this.lng) * d2r, + lat1 = this.lat * d2r, + lat2 = other.lat * d2r, + sin1 = Math.sin(dLat / 2), + sin2 = Math.sin(dLon / 2); + + var a = sin1 * sin1 + sin2 * sin2 * Math.cos(lat1) * Math.cos(lat2); + + return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); } };