Last active
August 29, 2015 14:11
-
-
Save dNitza/5fd71ef77c4e2b948ed2 to your computer and use it in GitHub Desktop.
Calculate distance from user given a lattitde and longitude
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
/* global App:false */ | |
'use strict'; | |
var Lib = Lib || {}; | |
Lib.DistanceView = Backbone.View.extend({ | |
latitude: 0, | |
longitude: 0, | |
initialize: function(){ | |
this.latitude = this.$el.data('lat'); | |
this.longitude = this.$el.data('long'); | |
_.bindAll(this, 'render', 'gotCoordinates'); | |
if(navigator.geolocation){ | |
navigator.geolocation.getCurrentPosition(this.gotCoordinates, this.failedToGetCoordinates); | |
} | |
}, | |
gotCoordinates: function(position){ | |
this.updateDistance(this.calculateDistance(this.latitude, this.longitude, position.coords.latitude, position.coords.longitude, 'K')); | |
}, | |
calculateDistance: function(lat1, lon1, lat2, lon2, unit){ | |
var theta = lon1 - lon2; | |
var dist = Math.sin(this.deg2rad(lat1)) * Math.sin(this.deg2rad(lat2)) + Math.cos(this.deg2rad(lat1)) * Math.cos(this.deg2rad(lat2)) * Math.cos(this.deg2rad(theta)); | |
dist = Math.acos(dist); | |
dist = this.rad2deg(dist); | |
var miles = dist * 60 * 1.1515; | |
unit = unit.toUpperCase(); | |
if (unit === 'K') { | |
return Math.round((miles * 1.609344) * 100) / 100; | |
} else if (unit === 'N') { | |
return (miles * 0.8684); | |
} else { | |
return miles; | |
} | |
}, | |
updateDistance: function(distance){ | |
this.$el.find('.distance-in-km').html(distance); | |
}, | |
failedToGetCoordinates: function(error){ | |
if(error.code === 1){ | |
console.log('Geolocation Access Denied'); | |
} | |
}, | |
deg2rad: function(deg){ | |
return deg * (Math.PI / 180); | |
}, | |
rad2deg: function(rad){ | |
return rad * (180 / Math.PI); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment