この関数は非同期であり、この場合の私の問題のほとんどです。
現在地の現在の経度と緯度を取得したいので、これらを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
}
それで、誰かがおそらくそのlat / lngを別の方法で取得するためのアイデア/解決策を持っていますか、それとも私はこれについて完全に間違っていますか?