Last active
February 27, 2023 19:07
-
-
Save Phoenix2k/43cbcf6de6cd6410f25dcbdc895acb67 to your computer and use it in GitHub Desktop.
JavaScript: Distance between two 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
/** | |
* Distance between two coordinates | |
* | |
* @author Salvador Dali | |
* | |
* @param { number } lat_1 - Latitude of first point | |
* @param { number } lon_1 - Longitude of first point | |
* @param { number } lat_2 - Latitude of second point | |
* @param { number } lon_2 - Longitude of second point | |
* | |
* @see http://stackoverflow.com/a/21623256 | |
* @see https://en.wikipedia.org/wiki/Haversine_formula | |
* | |
* @return { number } Distance in km | |
*/ | |
function distance_between( lat_1, lon_1, lat_2, lon_2 ) { | |
var Earth = 6371; // Radius of the Earth in km | |
var x = ( lat_2 - lat_1 ) * Math.PI / 180; | |
var y = ( lon_2 - lon_1 ) * Math.PI / 180; | |
var distance = 0.5 - Math.cos( x ) / 2 + | |
Math.cos( lat_1 * Math.PI / 180 ) * | |
Math.cos( lat_2 * Math.PI / 180 ) * | |
( 1 - Math.cos( y ) ) / 2; | |
return Earth * 2 * Math.asin( Math.sqrt( distance ) ); | |
} |
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
/** | |
* Distance between two coordinates (lite) | |
* | |
* @author Salvador Dali | |
* @author AnttiK / OiOi | |
* | |
* @param { number } lat_1 - Latitude of first point | |
* @param { number } lon_1 - Longitude of first point | |
* @param { number } lat_2 - Latitude of second point | |
* @param { number } lon_2 - Longitude of second point | |
* | |
* @see http://stackoverflow.com/a/21623256 | |
* @see https://en.wikipedia.org/wiki/Haversine_formula | |
* | |
* @return { number } Distance in km | |
*/ | |
function distance_between( lat_1, lon_1, lat_2, lon_2 ) { | |
var Earth = 6371; // Radius of the Earth in km | |
var x = ( lon_2 - lon_1 ) * Math.PI / 180 * Math.cos( ( ( lat_1 + lat_2 ) / 2 ) * Math.PI / 180 ); | |
var y = ( lat_2 - lat_1 ) * Math.PI / 180; | |
return Earth * Math.sqrt( x * x + y * y ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment