android - 科尔多瓦项目中 navigator.geolocation 失败的问题
问题描述
我正在开发我的第一个科尔多瓦项目,并且正在模拟器上进行测试。
我需要使用 navigator.geolocation 来获取坐标。
我已经安装了科尔多瓦地理定位插件,它也在 config.xml 文件中提到。我已经在模拟器设置中授予对应用程序的位置访问权限,并且我还单击了模拟器扩展设置中的“发送”按钮。
尽管如此,地理定位仍然失败,我不知道为什么。
这是js代码:
//第一次初始化入口页面并处理入口页面输入验证
$(document).delegate("#entry_page","pageinit",function()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(onSuccess, onError, {timeout: 30000});
}
//rest of code
if(latitude == null || longitude == null)
{
alert("Location not given. Please allow location access and refresh the application");
error_free = 0;
}
if(dateTime == null)
{
alert("Date & Time not acquired");
error_free = 0;
}
// remaining code
});
});
//Get location and time values on successful location access
function onSuccess(position)
{
latitude = position.coords.latitude;
longitude = position.coords.longitude;
today = new Date();
date = today.getDate()+'/'+(today.getMonth()+1)+'/'+today.getFullYear();
time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
dateTime = date+' '+time;
}
//Throw error if location access is not possible
function onError(error) {
var txt;
switch(error.code)
{
case error.PERMISSION_DENIED:
txt = 'Location permission denied';
break;
case error.POSITION_UNAVAILABLE:
txt = 'Location position unavailable';
break;
case error.TIMEOUT:
txt = 'Location position lookup timed out';
break;
default:
txt = 'Unknown position.'
}
alert(txt)
}
//Reinitialise entry_page when it is revisted again
$(document).on("pageshow", "#entry_page", function()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(onSuccess, onError, {timeout: 30000});
}
changeHeaderName("#chickenNameHeader");
clearFields();
});
PS 我正在使用 Nginx 和 Nodejs。我的 Nginx 配置为 https。
解决方案
如果您的 android 版本 >= Android M,您需要先向用户询问运行时位置权限。
使用此 cordova 插件请求位置权限。
var permissions = cordova.plugins.permissions;
permissions.hasPermission(permissions.ACCESS_COARSE_LOCATION, function(status){
if (!status.hasPermission) {
//Does not have the required permission, request for the same
permissions.requestPermission(permissions.ACCESS_COARSE_LOCATION,
function(status) {
if(status.hasPermission) {
//Has permission already, fetch the location
}
}, function () {
});
}
else {
//Has permission already, fetch the location
}
});
推荐阅读
- .net - 构建 .NET Framework 4.7.2 项目时的 MSB4019 Microsoft.WebApplication.targets
- html - HTML 滚动布局
- powershell - 如何从 Powershell Invoke-WebRequest 调用中获取 HTTP 状态代码?
- botframework - 访客无法在 Microsoft Teams 上提交答案自适应卡
- php - 那是恶意软件吗?
- postgresql - PostGIS ST_Contains 在可扩展性方面与点分块
- algorithm - 将元素分配到有条件的 bin 中
- jersey - 通过 localhost 作为资源获取时未使用 CSS 文件
- java - 如何在 Spring Boot 中为 Swagger UI 指定请求正文?
- angular - typescript 将 json 数据从 url 加载到数组中