這個函數是異步的,在這種情況下,這是我的大部分問題。地理位置和計算從當前經緯度到另一經度緯度的距離
我想獲取我的位置的當前經度和緯度,這樣我就可以在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