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.
This commit is contained in:
Jussi Mattas 2017-12-05 10:11:23 +02:00 committed by Iván Sánchez Ortega
parent 45b3e041d2
commit f0c31c1691

9
src/geo/crs/CRS.Earth.js Normal file → Executable file
View File

@ -24,9 +24,10 @@ export var Earth = Util.extend({}, CRS, {
var rad = Math.PI / 180, var rad = Math.PI / 180,
lat1 = latlng1.lat * rad, lat1 = latlng1.lat * rad,
lat2 = latlng2.lat * rad, lat2 = latlng2.lat * rad,
a = Math.sin(lat1) * Math.sin(lat2) + sinDLat = Math.sin((latlng2.lat - latlng1.lat) * rad / 2),
Math.cos(lat1) * Math.cos(lat2) * Math.cos((latlng2.lng - latlng1.lng) * rad); sinDLon = Math.sin((latlng2.lng - latlng1.lng) * rad / 2),
a = sinDLat * sinDLat + Math.cos(lat1) * Math.cos(lat2) * sinDLon * sinDLon,
return this.R * Math.acos(Math.min(a, 1)); c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return this.R * c;
} }
}); });