【发布时间】:2017-03-08 11:09:24
【问题描述】:
这是我的 javascript 代码:
function getLocation() {
//navigator.geolocation.getCurrentPosition(getCoor, errorCoor, {maximumAge:60000, timeout:30000, enableHighAccuracy:true});
var mobile =jQuery.browser.mobile;
var deviceAgent = navigator.userAgent.toLowerCase();
var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);
if(mobile){
watchLocation(function(coords) {
var latlon = coords.latitude + ',' + coords.longitude;
//some stuff
}, function() {
alert("error");
});
} else {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
alert("error");
}
}
}
function watchLocation(successCallback, errorCallback) {
successCallback = successCallback || function(){};
errorCallback = errorCallback || function(){};
// Try HTML5-spec geolocation.
var geolocation = navigator.geolocation;
if (geolocation) {
// We have a real geolocation service.
try {
function handleSuccess(position) {
alert("position:"+position.coords);
successCallback(position.coords);
}
geolocation.watchPosition(handleSuccess, errorCallback, {
enableHighAccuracy: true,
maximumAge: 5000 // 5 sec.
});
} catch (err) {
errorCallback();
}
} else {
errorCallback();
}
}
getCurrentPosition 和 watchPosition 我都试过了。
当控制到达geolocation.watchPosition 行时,它到达errorCalback() 方法。
我正在使用Android 6 和Google chrome browser 和opera mini 在Motorola G 2nd Gen 中进行测试。
更新 1:当我将警报放入错误回调函数时,我得到了error:1; message:Only Secure origins are allowed(see:link)。
navigator.geolocation.getCurrentPosition(showPosition, function(e)
{ alert(e); //alerts error:1; message:Only Secure origins are allowed(see: )
console.error(e);
})
更新 2: 在 g4s8 的帮助下,我能够发现错误是由于 URL 不安全造成的。即仅使用http 而不是https 访问。但是我也通过单击高级按钮在浏览器中绕过了它。但它会提示我不想要的Do you want to allow location。有什么方法可以在不提示的情况下访问位置?
【问题讨论】:
-
您是否尝试将第二个参数(错误回调)添加到
getCurrentPosition方法?navigator.geolocation.getCurrentPosition(showPosition, function(e) {console.error(e);}) -
是的...你可以看到被注释的第二行...
errorCoor是那个回调函数... -
您能否将错误打印到控制台并在此问题中添加错误消息?它可能包含有用的信息。例如
PositionError {code: 1, message: "User denied Geolocation"} -
您可以从谷歌浏览器连接到安卓设备。看到这个链接developers.google.com/web/tools/chrome-devtools/…
-
在这种情况下,您可以在警报中显示错误代码和消息:
function (err) {alert("error: " + err.code + "; message: " + err.message);}
标签: javascript android html geolocation