我有一个通过单击按钮触发的功能来检查地理位置。本地理位置打开时,它在手机上工作正常,当关闭时,如预期的那样显示一条消息。问题发生在首先关闭手机的定位服务,单击按钮(按预期弹出消息),然后如果用户在应用程序仍处于打开状态时重新打开定位服务,然后再次单击按钮,仍然是一样的弹出“无位置服务”消息。
有没有办法在每次点击按钮时检查手机的定位服务是打开还是关闭?在 Android 和 IOS 上获得相同的结果。
代码:
$(document).ready(function () {
$('#smallScreenGeolocate').on('click', function(){
getCurrentLocation();
});
});
function getCurrentLocation () {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(addGeolocationMarker, locationError);
return true;
}
else {
alert("Browser doesn't support Geolocation. Visit http://caniuse.com to discover browser support for the Geolocation API.");
return false;
}
}
最佳答案
从另一个 SO 帖子中检查这个答案 https://stackoverflow.com/a/14862073/6539349
您必须按照此处的建议检查错误是什么 http://www.w3schools.com/html/html5_geolocation.asp
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition,showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
The second parameter
showError
of the getCurrentPosition() method is used to handle errors. It specifies a function to run if it fails to get the user's location:
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred."
break;
}
}
关于android - 位置服务关闭和打开时地理定位不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37756484/