您可以將錯誤回調移交給getCurrentPosition()
以確定用戶是否拒絕跟蹤/位置無法確定(spec)。
此外,我會設置一個TimeOut,它會在一段時間後提示您的消息,因爲在這種情況下用戶很可能忽略了瀏覽器對話框。
示例代碼:
function getLocation(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition,showError);
// set a Timeout, after which the user gets prompted
// ugly global var but you could prevent this e.g. with a closure
t = window.setTimeout(
function(){alert("Please allow us to locate you;) !")},3000
);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position){
alert("Latitude: " + position.coords.latitude + " - Longitude: " + position.coords.longitude);
// position could be determined, clear the timeout
window.clearTimeout(t);
}
function showError(error){
// an error occured, clear the timeout as well
window.clearTimeout(t);
switch(error.code) {
case error.PERMISSION_DENIED:
alert("User denied the request.");
// Do stuff here, etc. ask the user to please allow the request
break;
case error.POSITION_UNAVAILABLE:
alert("No Location information available.");
break;
case error.TIMEOUT:
// user probably didn't recognize the browser dialog
alert("The request timed out.");
break;
case error.UNKNOWN_ERROR:
alert("An unknown error occurred.");
break;
}
}
但是,你仍然可以存儲權限,並檢查它。如果他們撤銷權限,您將進入錯誤回調,您可以在其中採取相應措施。
+1我也想知道。 – Mark
您是否嘗試過執行'getCurrentPostion()'調用,然後檢查是否出現'PERMISSION_DENIED'錯誤? –