This function is asynchronous which is most of my problem in this case.
I want to get the current longitude and latitude of my location so I can then use these in the distanceFromCurrent
function to calculate the distance between my current location and a given georss
point.
Everything works fine except for the fact I can't use the currLat
and currLong
outside of its asynchronous function.
function getCurrentPosition(){
navigator.geolocation.getCurrentPosition(getCoords, getError);
}
function getCoords(position){
var currLat = position.coords.latitude;
var currLon = position.coords.longitude;
}
function getError(error) {
alert("Error");
}
// convert degrees to radians
Number.prototype.toRad = function()
{
return this * Math.PI / 180;
}
This is the function that calculates the distance from the georss
and the current latitude and longitude it works fine with a set lat/lng like it has at the moment.
function distanceFromCurrent(georss)
{
getCurrentPosition();
var currLat = 3.0;
var currLon = 4.0;
georss = jQuery.trim(georss);
var pointLatLon = georss.split(" ");
var pointLat = parseFloat(pointLatLon[0]);
var pointLon = parseFloat(pointLatLon[1]);
var R = 6371; //Radius of the earth in Km
var dLat = (pointLat - currLat).toRad(); //delta (difference between) latitude in radians
var dLon = (pointLon - currLon).toRad(); //delta (difference between) longitude in radians
currLat = currLat.toRad(); //conversion to radians
pointLat = pointLat.toRad();
var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(currLat) * Math.cos(pointLat);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); //must use atan2 as simple arctan cannot differentiate 1/1 and -1/-1
var distance = R * c; //sets the distance
distance = Math.round(distance*10)/10; //rounds number to closest 0.1 km
return distance; //returns the distance
}
So, does anyone have an ideas/solution to maybe getting that lat/lng a different way or am I going about this completely wrong?