嘗試捕捉錯誤,要知道爲什麼它不工作
document.querySelector("#posBtn").addEventListener("click",function(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(PositionFunction, showError);
} else {
console.log("Geolocation is not supported by this browser.");
}
});
function PositionFunction(p) {
console.log(p.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;
}
}
查看實例:https://jsfiddle.net/ozmsq23w/6/
添加一個錯誤回調函數來調試它。請參閱https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition – sking