第一次执行 navigator.geolocation.getCurrentPosition(success, error, options);
时,我能够获取用户的位置。然而从第二次执行开始,该函数返回错误:
The current position could not be determined.
我遵循了 this question's answers 中给出的建议没有成功,我怎样才能让它工作?
在这里你可以找到一个 working fiddle快速查看错误。
//Pass this options to the getCurrentPosition
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
//function to execute if the current position was succesfully retrieved
function success(pos) {
console.log(pos);
var crd = {lat: pos.coords.latitude, lng : pos.coords.longitude };
var myPre = document.querySelector('pre');
myPre.textContent = JSON.stringify(crd);
myPre.style.color = someColor(); // use a diferent color just to see it's a new execution of the code
};
//execute this on error
function error(err) {
var myPre = document.querySelector('pre');
myPre.textContent = err;
myPre.style.color = someColor(); // use a diferent color
};
//attach function to button
var myButton = document.querySelector('button');
myButton.addEventListener('click', function(){
navigator.geolocation.getCurrentPosition(success, error, options);
});
最佳答案
我的想法是:
IE 用户只允许网站(脚本)(默认设置)运行一次getCurrentLocation
。用户必须授予异常才能多次运行。
However I don't know (and can't really find any documentation) if this behaviour is by design or a bug. The solution below is a work-around.
使用watchposition
相反,在最初的成功之后绕过这个bug。查看更新的 fiddle :https://jsfiddle.net/b2rnr7tw/6/
在这个 fiddle 中,我设置了一个 watchPosition
,它一更新就会显示新位置。之后它被取消(否则它会不断更新)。
//Pass this options to the getCurrentPosition
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
var watch = null;
var watchId = null;
//function to execute if the current position was succesfully retrieved
function success(pos) {
var crd = {lat: pos.coords.latitude, lng : pos.coords.longitude };
var myPre = document.querySelector('pre');
myPre.textContent = JSON.stringify(crd);
myPre.style.color = someColor(); // use a diferent color
watch.clearWatch(watchId); //after success clear the watchId.
};
//execute this on error
function error(err) {
var myPre = document.querySelector('pre');
myPre.textContent = err;
myPre.style.color = someColor(); // use a diferent color
//keep running the watchPosition if on error, however you can use a counter to only try it a few times (recommended)
};
//attach function to button
var myButton = document.querySelector('button');
myButton.addEventListener('click', function(){
if (!watch)
{
watch = navigator.geolocation;
watch.getCurrentPosition(success, error, options);
}
else
{
watchId = watch.watchPosition(success, error, options);
}
});
关于javascript - navigator.geolocation 从第二次执行返回错误 - IE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45870918/