Pages

Thursday, August 22, 2013

Nautical Distance Between Two Points( latitude/longitude)

Earth as a Sphere:

We always see maps 2D and assume the distance between two place is easy to calculate, However it is slightly complicated. Earth is some what spherical in shape, hills mountains adds more complication which makes almost impossible to calculate accurate distance between two places. Basically we will be calculating approximate distance between two points assuming earth as a sphere ignoring ellipsoidal effects.


Concept of Spherical Geometry  talks about this concept in detail.

Rather than going to detail we will focus on implementation.

There are few options:
1. Haversine formula[Detail]
Haversine formula: a = sin²(Δφ/2) + cos(φ1).cos(φ2).sin²(Δλ/2)
                                 c = 2.atan2(√a, √(1−a))
                                 d = R.c
where φ is latitude, λ is longitude, R is earth’s radius (mean radius = 6,371km)
  note that angles need to be in radians to pass to trig functions!

JavaScript:
var R = 6371; // km
var dLat = (lat2-lat1).toRad();
var dLon = (lon2-lon1).toRad();
var lat1 = lat1.toRad();
var lat2 = lat2.toRad();

var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2); 
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
var d = R * c;
d is the distance between two point in KM.

[note: toRad() should convert decimal to radient so simply add this function following the function which calculate distance 
  /** Converts numeric degrees to radians */
    if (typeof (Number.prototype.toRad) === "undefined") {
        Number.prototype.toRad = function () {
            return this * Math.PI / 180;
        }
    }]
2. Spherical Law of Cosines: [Detail]

Spherical law of cosines: d = acos( sin(φ1).sin(φ2) + cos(φ1).cos(φ2).cos(Δλ) ).R
JavaScript:
var R = 6371; // km
var d = Math.acos(Math.sin(lat1)*Math.sin(lat2) + 
                  Math.cos(lat1)*Math.cos(lat2) *
                  Math.cos(lon2-lon1)) * R;
Excel: =ACOS(SIN(lat1)*SIN(lat2)+COS(lat1)*COS(lat2)*COS(lon2-lon1))*6371
(Note that here and in all subsequent code fragments, for simplicity I do not show conversions from degrees to radians; see code below for complete versions).

3. Google Spherical  computeDistanceBetween():[Detail]

Google Map API provides static method to get distance between two point.

<script src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false&libraries=geometry">
     function calculatedis(){
        var d = google.maps.geometry.spherical.computeDistanceBetween(new google.maps.LatLng(lat1, lon1), new google.maps.LatLng(lat2, lon2));
    
        return d;
}
</script>
[note: Donot forget to add libraries=geometry ]

Hope this will help you Cheers!!!

No comments:

Post a Comment