Warning: DOMDocument::loadHTML(): Tag template invalid in Entity, line: 12 in /home/customer/www/salferrarello.com/public_html/wp-content/plugins/gistpress/includes/class-gistpress.php on line 466
Warning: DOMDocument::loadHTML(): Tag svg invalid in Entity, line: 14 in /home/customer/www/salferrarello.com/public_html/wp-content/plugins/gistpress/includes/class-gistpress.php on line 466
Warning: DOMDocument::loadHTML(): Tag path invalid in Entity, line: 15 in /home/customer/www/salferrarello.com/public_html/wp-content/plugins/gistpress/includes/class-gistpress.php on line 466
Warning: DOMDocument::loadHTML(): Tag template invalid in Entity, line: 27 in /home/customer/www/salferrarello.com/public_html/wp-content/plugins/gistpress/includes/class-gistpress.php on line 466
Warning: DOMDocument::loadHTML(): Tag svg invalid in Entity, line: 29 in /home/customer/www/salferrarello.com/public_html/wp-content/plugins/gistpress/includes/class-gistpress.php on line 466
Warning: DOMDocument::loadHTML(): Tag path invalid in Entity, line: 30 in /home/customer/www/salferrarello.com/public_html/wp-content/plugins/gistpress/includes/class-gistpress.php on line 466
When working with locations in JavaScript, you often have two sets of latitude/longitude coordinates and you need the distance between theme. The following function will give you an approximate distance between theme (in miles by default).
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
/** | |
* Calculate approximate distance between two coordinates on Earth. | |
* | |
* @see https://salferrarello.com/javascript-distance-between-locations | |
* | |
* Example: | |
* | |
* LatLngDist( 40.3215666, -75.9828464, 33.5417647, -112.169801 ) | |
* | |
* Result: | |
* 2036 miles (or 3277 km) | |
* @see https://stackoverflow.com/questions/21279559/geolocation-closest-locationlat-long-from-my-position. | |
*/ | |
function LatLngDist( lat1, lng1, lat2, lng2 ) { | |
// Convert Degress to Radians | |
function Deg2Rad(deg) { | |
return deg * Math.PI / 180; | |
} | |
function PythagorasEquirectangular(lat1, lon1, lat2, lon2) { | |
lat1 = Deg2Rad(lat1); | |
lat2 = Deg2Rad(lat2); | |
lon1 = Deg2Rad(lon1); | |
lon2 = Deg2Rad(lon2); | |
// var R = 6371; // km | |
var R = 3959; // miles | |
var x = (lon2 - lon1) * Math.cos((lat1 + lat2) / 2); | |
var y = (lat2 - lat1); | |
var d = Math.sqrt(x * x + y * y) * R; | |
return d; | |
} | |
return PythagorasEquirectangular( lat1, lng1, lat2, lng2 ); | |
} |
Leave a Reply