Discovering distance to a location using javascript
I saw @MrQwest tweet the other day that he was going to be creating something that showed the user something different if they were near a location. He asked Twitter if anyone had done something similar.
Last Christmas I was asked to make a web site for the launch of the latest Rolling Stones’ greatest hits album Grrr. For the launch, the Stones were having a pop up shop on Carnaby Street. Polydor, the label the band is signed to, wanted to be able to allow fans to listen to the album via their mobile phone if they were within a mile of the store while they were shopping. It would also allow fans to listen to the album easily and for free while in the pop up store before they decided to buy the album.
For this example I checked using the new(ish) HTML5 JavaScript geolocation API for the user’s location:
navigator.geolocation.getCurrentPosition(function(result) {
var location = data.coords;
});
The location
object has longitude
and latitude
as attributes along with various others. Once I have got their location
I then needed to discover their distance from a known location, using the longitude and latitude.
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
});
So now I know their distance, I can then show them the relative information. Now there are a few things to bear in mind, location data can be spoofed. The browser could pretend it is somewhere else. The band and label were very aware with this for the project.
There we go, simples.