Skip to content

Instantly share code, notes, and snippets.

@stopsatgreen
Last active December 9, 2015 20:58
Show Gist options
  • Save stopsatgreen/4326804 to your computer and use it in GitHub Desktop.
Save stopsatgreen/4326804 to your computer and use it in GitHub Desktop.
Find the distance between two points, taking into account the curvature of the Earth.
function findDistance() {
'use strict';
var hasGeoLocation = navigator.geolocation ? true : false;
if (hasGeoLocation) {
var toLat, toLon, fromLat, fromLon, dLat, dLon, R, a, c, d, distance;
navigator.geolocation.getCurrentPosition(function(position) {
// Define the toRad function for later calculation
if (typeof(Number.prototype.toRad) === 'undefined') {
Number.prototype.toRad = function() {
return this * Math.PI / 180;
};
}
// Destination co-ordinates
toLat = 51.524284;
toLon = -0.076237;
// User co-ordinates
fromLat = position.coords.latitude;
fromLon = position.coords.longitude;
// Average Radius of the Earth (km)
R = 6371;
// Perform the distance calculations using the Haversine formula to account for the Earth's curvature.
// This code is from http://www.movable-type.co.uk/scripts/latlong.html
dLat = (toLat-fromLat).toRad();
dLon = (toLon-fromLon).toRad();
a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(toLat.toRad()) * Math.cos(fromLat.toRad()) * Math.sin(dLon/2) * Math.sin(dLon/2);
c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
d = R * c;
// Round to one decimal place
distance = Math.round(d*10)/10;
// Return the result
document.getElementById('hello').innerHTML = 'You are ' + distance + 'km from the destination';
});
} else {
window.alert('Your browser does not support GeoLocation');
}
}
document.addEventListener('DOMContentLoaded', findDistance, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment