Skip to content

Instantly share code, notes, and snippets.

@sydlawrence
Created September 26, 2013 00:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sydlawrence/6708282 to your computer and use it in GitHub Desktop.
Save sydlawrence/6708282 to your computer and use it in GitHub Desktop.
Get a distance from a location using HTML geolocation
var calculateDistance = function(location1, location2) {
// this is where we want to calculate the distance from. You can of course split this out so that the function
var origin = {longitude:50,latitude:1};
// first calculate the locations into radians.
var radlat1 = Math.PI * location1.latitude/180;
var radlat2 = Math.PI * location2.latitude/180;
var radlon1 = Math.PI * location1.longitude/180;
var radlon2 = Math.PI * location2.longitude/180;
var theta = location2.longitude-location1.latitude;
var radtheta = Math.PI * theta/180
// this is where we do the SOHCAHTOA trigonometry bits
var distance = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
distance = Math.acos(distance)
distance = distance * 180/Math.PI
// 1.1515 is to take into account the curvature of the earth
// the only works on small distances due to the earth not being spherical
distance = distance * 60 * 1.1515
// distance is now in miles
return distance;
}
navigator.geolocation.getCurrentPosition(function(result) {
var location = data.coords;
// get the distance to a specific a location
var origin = {longitude: 50, latitude:1};
var distance = calculateDistance(location,origin);
// run your logic on distance
});
@AsyncWizard
Copy link

Hi!

I tried to use your script but I think (after comparing with other code) you have to edit theta:

var theta = location2.longitude-location1.longitude;

I know it's been a long time, but I came across this page after looking for an algorithm on google.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment