Created
April 20, 2023 03:24
-
-
Save darkterminal/5f57c0ef16d6095c7c4e60497c7408c5 to your computer and use it in GitHub Desktop.
Calculate Distance from 2 Coordinates
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment