在ons.ready中获取用户位置不起作用

Posted

技术标签:

【中文标题】在ons.ready中获取用户位置不起作用【英文标题】:Get users location in ons.ready not working 【发布时间】:2016-07-21 14:30:26 【问题描述】:

我有以下代码:

ons.ready( function() 

    navigator.geolocation.getCurrentPosition(
        function( position ) 
            geo.lat = position.coords.latitude;
            geo.lon = position.coords.longitude;
        
    );
 );

有时,但不是所有时候我都会收到以下错误:

Location access is not available.
Error in Error callbackId: Geolocation54410059

我需要用户的位置来将数据加载到我的应用程序的主页中。最好的地方在哪里?

【问题讨论】:

【参考方案1】:

ons.ready 在加载 dom 时触发,您正在使用 cordova 插件来获取地理位置。所以在cordova准备好之前你不能使用它。

只要做:

document.addEventListener('deviceready', function () 
     // now cordova is ready
     navigator.geolocation.getCurrentPosition(function( position ) 
            geo.lat = position.coords.latitude;
            geo.lon = position.coords.longitude;
    );
, false);

我想会很好的。

编辑:

尝试将这些选项添加到您的函数中:

navigator.geolocation.getCurrentPosition(function( position ) 
                geo.lat = position.coords.latitude;
                geo.lon = position.coords.longitude;
        ,  maximumAge: 3000, timeout: 5000, enableHighAccuracy: true );

你可以为 'enableHighAccuracy' 和 'maximumAge' 设置任何你想要的值,但是你必须提供一个 'timeout' 选项,因为在 android 中有一些怪癖:

Android 怪癖

如果地理定位服务关闭,则调用 onError 回调 超时间隔后(如果指定)。如果超时参数不是 指定则不调用回调。

【讨论】:

以上是关于在ons.ready中获取用户位置不起作用的主要内容,如果未能解决你的问题,请参考以下文章

获取我在 OsmDroid 中的位置不起作用

Android Studio:地理定位不起作用。无法在 Webview 中获取地理位置

位置的 getSpeed() 在 WiFi 上不起作用

Cordova GeoLocation 在 android 应用程序中不起作用

后台获取 performFetchWithCompletionHandler 不起作用?

地理位置在 Cordova Android 模拟器中不起作用