Last active
October 22, 2019 08:33
-
-
Save monkeymonk/390061dd3281dac4971fc41336d61ceb to your computer and use it in GitHub Desktop.
JavaScript Distance Between Coordinates #javascript #map
This file contains 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
/** | |
* Returns the distance bewteen 2 coordinates. | |
* @param {Object} from - Object with lat and lng | |
* @param {Object} to - Object with lat and lng | |
* @return {float} | |
*/ | |
function distance(from, to) { | |
const {atan2, cos, sqrt, sin} = Math; | |
// @note - radius of the planet earth in meters | |
const R = 6378137; | |
const toRad = Math.PI / 180; | |
const dLat = (to.lat - from.lat) * toRad; | |
const dLng = (to.lng - from.lng) * toRad; | |
const a = sin(dLat / 2) * sin(dLat / 2) + cos(from.lat * toRad) * cos(from.lat * toRad) * sin(dLng / 2) * sin(dLng / 2); | |
const c = 2 * atan2(sqrt(a), sqrt(1 - a)); | |
return R * c; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment