phonegap: how to check if gps is enabled

泄露秘密 提交于 2019-12-03 04:16:41
DaveAlden

Assuming we're talking just about Android platform only, as @Joerg rightly says, you can use cordova.plugins.diagnostic to check if GPS is enabled using isGpsLocationEnabled():

cordova.plugins.diagnostic.isGpsLocationEnabled(function(enabled){
    console.log("GPS location is " + (enabled ? "enabled" : "disabled"));
}, function(error){
    console.error("The following error occurred: "+error);
});    

If the result is that GPS is switched off, you can either switch the user to the location settings page to manually enable GPS:

cordova.plugins.diagnostic.switchToLocationSettings();

Or, in addition, you could use cordova-plugin-request-location-accuracy to request high accuracy location mode (i.e. GPS) directly from within the app. This will show a native confirm dialog and if user agrees, GPS will be enabled automatically:

function onRequestSuccess(success){
    console.log("Successfully requested accuracy: "+success.message);
}

function onRequestFailure(error){
    console.error("Accuracy request failed: error code="+error.code+"; error message="+error.message);
    if(error.code !== cordova.plugins.locationAccuracy.ERROR_USER_DISAGREED){
        if(window.confirm("Failed to automatically set Location Mode to 'High Accuracy'. Would you like to switch to the Location Settings page and do this manually?")){
            cordova.plugins.diagnostic.switchToLocationSettings();
        }
    }
}

cordova.plugins.locationAccuracy.request(onRequestSuccess, onRequestFailure, cordova.plugins.locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY);

The answer to your question is below.

You cannot check *if gps is enabled*

You can set a timeout and get the timeout. You can do this by setting the timeout parameter in the geolocationoptions parameter. (which you did not use)

From the documentation

  • timeout: The maximum length of time (milliseconds) that is allowed to pass from the call to navigator.geolocation.getCurrentPosition or geolocation.watchPosition until the corresponding geolocationSuccess callback executes. If the geolocationSuccess callback is not invoked within this time, the geolocationError callback is passed a PositionError.TIMEOUT error code. (Note that when used in conjunction with geolocation.watchPosition, the geolocationError callback could be called on an interval every timeout milliseconds!) (Number)

WAIT I WAS WRONG

There is now a plugin that checks to see if the GPS is turned on.

In fact, more than one.

The best way to check if GPS, Wifi, … is enabled, is to use this plugin:

https://www.npmjs.com/package/cordova.plugins.diagnostic

Using this plugin you can check a lot of features and you can switch the user to the settings.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!