Skip to content

Instantly share code, notes, and snippets.

@GabrielDelepine
Last active September 14, 2023 08:16
Show Gist options
  • Save GabrielDelepine/9260340 to your computer and use it in GitHub Desktop.
Save GabrielDelepine/9260340 to your computer and use it in GitHub Desktop.
Returns the distance in meter between 2 GPS coordinates
/**
* Returns the distance in meter between 2 GPS coordinates
* @param {number} lat1 - Latitude of the first coordinate
* @param {number} lon1 - Longitude of the first coordinate
* @param {number} lat2 - Latitude of the second coordinate
* @param {number} lon2 - Longitude of the second coordinate
* @returns {number} The distance in meter (float)
*/
function getDistanceFromGPS(lat1, lon1, lat2, lon2) {
if (
parseFloat(lat1) !== lat1 ||
parseFloat(lon1) !== lon1 ||
parseFloat(lat2) !== lat2 ||
parseFloat(lon1) !== lon1
) {
throw "Error params. Only float value accepted."
}
if (lat1 < 0 || lat1 > 90 || lat2 < 0 || lat2 > 90) {
throw `Out of range value. lat1 and lat2 must be 0< ? <90. Given values are lat1=${lat1} and lat2=${lat2}`
}
if (lon1 < -180 || lon1 > 180 || lon2 < -180 || lon2 > 180) {
throw `Out of range value. lon1 and lon2 must be -180< ? <180. Given values are lon1=${lon1} and lon2=${lon2}`
}
function degreesToRadians(deg) {
return deg * (Math.PI / 180)
}
const t1 = Math.sin(degreesToRadians(lat1)) * Math.sin(degreesToRadians(lat2))
const t2 = Math.cos(degreesToRadians(lat1)) * Math.cos(degreesToRadians(lat2))
const t3 = Math.cos(degreesToRadians(lon1) - degreesToRadians(lon2))
const t4 = t2 * t3
const t5 = t1 + t4
const rad_dist = Math.atan(-t5 / Math.sqrt(-t5 * t5 + 1)) + 2 * Math.atan(1)
return rad_dist * 3437.74677 * 1.1508 * 1.6093470878864446 * 1000
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment