From f0c31c169125d5c47c7d27439dfb78e23263f39d Mon Sep 17 00:00:00 2001 From: Jussi Mattas Date: Tue, 5 Dec 2017 10:11:23 +0200 Subject: [PATCH] Use more stable form of Haversine formula. (#5935) * Use more stable form of Haversine formula. The new form does not give a non-zero distance from a point to itself. * Pre-compute sines which are used twice. --- src/geo/crs/CRS.Earth.js | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) mode change 100644 => 100755 src/geo/crs/CRS.Earth.js diff --git a/src/geo/crs/CRS.Earth.js b/src/geo/crs/CRS.Earth.js old mode 100644 new mode 100755 index 0ded3129..6ecff658 --- a/src/geo/crs/CRS.Earth.js +++ b/src/geo/crs/CRS.Earth.js @@ -24,9 +24,10 @@ export var Earth = Util.extend({}, CRS, { var rad = Math.PI / 180, lat1 = latlng1.lat * rad, lat2 = latlng2.lat * rad, - a = Math.sin(lat1) * Math.sin(lat2) + - Math.cos(lat1) * Math.cos(lat2) * Math.cos((latlng2.lng - latlng1.lng) * rad); - - return this.R * Math.acos(Math.min(a, 1)); + sinDLat = Math.sin((latlng2.lat - latlng1.lat) * rad / 2), + sinDLon = Math.sin((latlng2.lng - latlng1.lng) * rad / 2), + a = sinDLat * sinDLat + Math.cos(lat1) * Math.cos(lat2) * sinDLon * sinDLon, + c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); + return this.R * c; } });