## Posts Tagged ‘latitude’

### The haversine formula

I had to do a little research into calculating distances between 2 points on the Earth, as I wanted the latest version of the dotspott webOS app to calculate the distance from your current position to your spotts.

The page at Movable Type on the subject proved to be an amazing resource.

I ended up doing an straightforward implementation of the haversine formula:

```R = mean radius of earth = 6,371km Δlat = lat2 - lat1 Δlong = long2 - long1 a = sin²(Δlat/2) + cos(lat1) · cos(lat2) · sin²(Δlong/2) c = 2 · atan2( sqrt(a), sqrt(1-a) ) d = R · c```

The Javascript code (HSD.CurrentGlobalPosition.LatLong is a string with the device’s current position as a latitude,longitude pair):

`HSD.Math.toRad = function(deg){    return deg * (Math.PI/180);}HSD.CurrentGlobalPosition.calcDistance = function(_targetLat, _targetLon){    var latlongParts = HSD.CurrentGlobalPosition.LatLong.split(',');        var lat1 = parseFloat(latlongParts[0]);    var lon1 = parseFloat(latlongParts[1]);    var lat2 = parseFloat(_targetLat);    var lon2 = parseFloat(_targetLon);        var R = 6371; // km    var dLat = HSD.Math.toRad(lat2-lat1);    var dLon = HSD.Math.toRad(lon2-lon1);     var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(HSD.Math.toRad(lat1)) * Math.cos(HSD.Math.toRad(lat2)) * Math.sin(dLon/2) * Math.sin(dLon/2);     var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));     var d = R * c;        return d;}`

The result is the distance to the target in kilometers.