这个函数是异步的,这是我在这种情况下遇到的大部分问题。
我想获取我所在位置的当前经度和纬度,以便可以在 distanceFromCurrent
函数中使用它们来计算我当前位置与给定 georss
之间的距离> 点。
一切工作正常,除了我无法在其异步函数之外使用 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
}
那么,有没有人有想法/解决方案,可以以不同的方式获得纬度/经度,或者我的做法完全错误?
最佳答案
如果以下调用没有阻塞,那么这根本不起作用。
navigator.geolocation.getCurrentPosition(getCoords, getError);
您调用此方法的方式意味着 getCurrentPosition() 的结果在到达 distanceFromCurrent() 方法的末尾之前不会完成。
相反,您可以执行以下操作并调用 update() 而不是 distanceFromCurrent()。这最终将使用当前的纬度/经度值调用 distanceFromCurrent() 方法。
注意:以下是伪代码,我怀疑它能否正确传递您的 georss 值。
update()
{
getCurrentPosition();
}
function getCurrentPosition(){
navigator.geolocation.getCurrentPosition(getCoords, getError);
}
function getCoords(position){
var currLat = position.coords.latitude;
var currLon = position.coords.longitude;
distanceFromCurrent(georss, lat, lng);
}
function distanceFromCurrent(georss, lat, lng)
{
// Remove -> getCurrentPosition();
var currLat = lat;
var currLon = lng;
georss = jQuery.trim(georss);
...
}
关于javascript - 地理定位并计算从当前纬度/经度到另一个纬度/经度的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12201826/