Skip to content

Instantly share code, notes, and snippets.

@clauswitt
Created January 13, 2012 07:11
Show Gist options
  • Select an option

  • Save clauswitt/1604972 to your computer and use it in GitHub Desktop.

Select an option

Save clauswitt/1604972 to your computer and use it in GitHub Desktop.

Revisions

  1. clauswitt revised this gist Jan 13, 2012. 1 changed file with 15 additions and 7 deletions.
    22 changes: 15 additions & 7 deletions distance.js
    Original file line number Diff line number Diff line change
    @@ -1,10 +1,18 @@
    /**
    * Simple node js module to get distance between two coordinates.
    *
    * Heavily inspired by http://www.movable-type.co.uk/scripts/latlong.html
    *
    *
    */
    /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
    /* */
    /* Simple node js module to get distance between two coordinates. */
    /* */
    /* Code transformed from Chris Veness example code - please refer to his website for licensing */
    /* questions. */
    /* */
    /* */
    /* Latitude/longitude spherical geodesy formulae & scripts (c) Chris Veness 2002-2011 */
    /* - www.movable-type.co.uk/scripts/latlong.html */
    /* */
    /* */
    /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */



    /** Converts numeric degrees to radians */
    if(typeof(Number.prototype.toRad) === "undefined") {
  2. clauswitt created this gist Jan 13, 2012.
    37 changes: 37 additions & 0 deletions distance.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    /**
    * Simple node js module to get distance between two coordinates.
    *
    * Heavily inspired by http://www.movable-type.co.uk/scripts/latlong.html
    *
    *
    */

    /** Converts numeric degrees to radians */
    if(typeof(Number.prototype.toRad) === "undefined") {
    Number.prototype.toRad = function () {
    return this * Math.PI / 180;
    }
    }

    // start and end are objects with latitude and longitude
    //decimals (default 2) is number of decimals in the output
    //return is distance in kilometers.
    exports.getDistance = function(start, end, decimals) {
    decimals = decimals || 2;
    var earthRadius = 6371; // km
    lat1 = parseFloat(start.latitude);
    lat2 = parseFloat(end.latitude);
    lon1 = parseFloat(start.longitude);
    lon2 = parseFloat(end.longitude);

    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 = earthRadius * c;
    return Math.round(d * Math.pow(10, decimals)) / Math.pow(10, decimals);
    };