Tag Archives: geolocation

Capture Current Location inside of a Backbone Model

Here is how I take the lat and lng from the browser and turn it into a Backbone Model with a function to figure out haversine

var CurrentLocationModel = Backbone.Model.extend({
   initialize: function(){
    this.getLocation();
  },
  getLocation: function(){
        var that = this;
		if (navigator.geolocation){	
			navigator.geolocation.getCurrentPosition(function(position){
				that.set("lat",position.coords.latitude);
				that.set("lng",position.coords.longitude);
			});
		}else{
		    that.set("lat",0);
			that.set("lng",0);
		}
   },
   getDistance: function(lat,lng){
        //see http://stackoverflow.com/questions/14560999/using-the-haversine-formula-in-javascript
		var that = this;
		var R = 6371; // km 
		console.log(that.get("lat"));
		//has a problem with the .toRad() method below.
		var x1 = that.get("lat")-lat;
		var dLat = x1.toRad();  
		var x2 = that.get("lng")-lng;
		var dLon = x2.toRad();  
		var a = Math.sin(dLat/2) * Math.sin(dLat/2) + 
					Math.cos(lat.toRad()) * Math.cos(that.get("lat").toRad()) * 
					Math.sin(dLon/2) * Math.sin(dLon/2);  
		var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
		var dist = R * c;
        return(dist);		
   }
  
});
Tagged , ,