エラー コールバックを渡して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;
}
}
ただし、許可を保存して確認することはできます。彼らが許可を取り消した場合、それに応じてアクションを実行できるエラーコールバックが発生します。