这个函数是异步的,在这种情况下,这是我的大部分问题。地理位置和计算从当前经纬度到另一经度纬度的距离
我想获取我的位置的当前经度和纬度,这样我就可以在distanceFromCurrent
函数中使用它们来计算我当前位置和给定的点之间的距离。
一切工作正常,除了我不能在其异步功能外使用currLat
和currLong
。
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;
}
这是计算与一组纬度/经度从georss
和正常工作的距离当前的经纬度像它此刻的功能。
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
}
因此,没有人有一个想法/解决方案可能获得该纬度/经度不同的方式或我要对这个完全错误的?
您是否找到解决方案?把你的函数放在回调函数中,不幸的是javascript如何工作 – 2012-08-30 20:00:34