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.
carto
Jussi Mattas 7 years ago committed by Iván Sánchez Ortega
parent 45b3e041d2
commit f0c31c1691

@ -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;
}
});

Loading…
Cancel
Save