我需要將用戶的當前位置打包到對象中並將其發送給PHP腳本。所以我現在有以下幾點。腳本不允許geolocation.getCurrentPosition完成其回調函數
位置對象
function position(lat, lon) {
this.latitude = lat;
this.longitude = lon;
this.setlat = function(lat) {
this.latitude = lat;
};
this.setlon = function(lon) {
this.longitude = lon;
};
this.print = function() {
alert(this.longitude + ", " + this.latitude);
};
}
控制流
var origin = new position(0, 0);
$(document).ready(function() {
getLocation();
origin.print();
});
功能
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(setLocation, showError, {timeout:60000});
} else {
alert("GeoLocation is not supported on this browser or device.");
return null;
}
}
function setLocation(position) {
alert('callback success!');
origin.setlat(position.coords.latitude);
origin.setlon(position.coords.longitude);
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
console.log("User denied the request for Geolocation.");
break;
case error.POSITION_UNAVAILABLE:
console.log("Location information is unavailable.");
break;
case error.TIMEOUT:
console.log("The request to get user location timed out.");
break;
case error.UNKNOWN_ERROR:
console.log("An unknown error occurred.");
break;
}
}
問題我在調用setLocation
回調之前,主控制流程會繼續,並忽略我要求它爲我獲得某些東西的事實。我調用getLocation並獲得「0,0」的警報,因爲這是原始設置的原因。所以出於某種原因,我的setLocation
回調只是不會被調用,直到程序中的其他內容完成。
我已經在文檔中四處看了一遍,但它很直接,並且沒有很多事情發生,所以很難確定發生這種情況的原因。
我知道很多人都在爲此苦苦掙扎,似乎有很多'看這個主題',但所有這些話題都指向與我自己相同的代碼,但格式化爲有點不同。
重要的是要注意,我真的需要封裝在全局變量中的位置數據,因爲我將在頁面加載時將我的位置與幾十個其他位置進行比較。
嘗試的解決方案
我已經試過限制離開基於回調函數完成我navigator.geolocation.getCurrentPosition()
while循環,但結果總是在無休止的循環。
-I've試圖以允許功能有一定的時間來完成與在PositionOptions
的maximumAge
和timeout
值打,但同樣這只是導致setLocation
整理其它所有的計劃函數調用完成後。
- 我嘗試過使用兩個單獨的$(document).ready(function(){});
以分割getLocation()
和origin.print()
函數。
-I've嘗試使用watchPosition
代替getCurrentPosition.
最後,我真的只需要對爲什麼在getCurrentPosition
回調函數沒有完成,直到一切做一些澄清。
你應該在回調函數setLocation中移動警報,在該函數內部你可以發送對象到PHP,記得javascript是Async –
不幸的是我有點受限於有一個全局變量,因爲我比較我的位置幾十個其他地點。所以這樣做並不合情理。真的不應該很難實現我所描述的功能。 – Csteele5