Currently Browsing

Calculate the distance between two sets of coordinates using JavaScript

Here’s some code which allows you to calculate the distance in miles, kilometres or nautical miles between two sets of coordinates:

[code lang="js"]/* Function Name: distance()
Function Description: Calculates the distance between two sets of coordinates.

@Author: Adam Williams <adam.williams@awdigital.eu>
@License: Creative Commons Attribution-Share Alike 2.0 UK: England & Wales - http://creativecommons.org/licenses/by-sa/2.0/uk/
@Example: distance(53.61857936489517, -1.4501953125, 65.82078234733756, -172.265625, 'm');

*/

/* Dependant functions */

function deg2rad(angle) {
return (angle * Math.PI / 180);
}

function rad2deg (angle) {
return (angle / Math.PI) * 180;
}

/* Main function */

function distance(lat1, lon1, lat2, lon2, unit) {
var theta, dist, miles;
theta = lon1 - lon2;

dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
miles = dist * 60 * 1.1515;
unit = unit.toUpperCase();

if (unit === "K") {
return (miles * 1.609344);
} else if (unit === "N") {
return (miles * 0.8684);
} else {
return miles;
}
}[/code]

You can download the code if you don’t want to copy and paste: distance.js

Any feedback welcomed.

Cheers! :-)

Tags: , , ,

LEAVE A REPLY