Skip to content

Instantly share code, notes, and snippets.

@darkterminal
Created April 20, 2023 03:24
Show Gist options
  • Select an option

  • Save darkterminal/5f57c0ef16d6095c7c4e60497c7408c5 to your computer and use it in GitHub Desktop.

Select an option

Save darkterminal/5f57c0ef16d6095c7c4e60497c7408c5 to your computer and use it in GitHub Desktop.

Revisions

  1. darkterminal created this gist Apr 20, 2023.
    28 changes: 28 additions & 0 deletions harvesine.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,28 @@
    function harvesine(pta, ptb) {

    const [lat1, lon1] = pta.split(',')
    const [lat2, lon2] = ptb.split(',')

    // convert to radians
    const rad1 = (lat1 * Math.PI) / 180;
    const rad2 = (lat2 * Math.PI) / 180;
    const dLat = ((lat2 - lat1) * Math.PI) / 180;
    const dLon = ((lon2 - lon1) * Math.PI) / 180;

    // Haversine formula
    const a =
    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(rad1) * Math.cos(rad2) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    const R = 6371; // Earth's radius in kilometers

    // return distance in kilometers
    return Math.round(R * c) + ' Km';

    }

    // Usage:
    // var p1 = '52.518611,13.408056'
    // var p2 = '51.507222,-0.1275'

    // console.log(harvesine(p1, p2))