phonegap: how to check if gps is enabled

前端 未结 3 1198
耶瑟儿~
耶瑟儿~ 2021-02-06 09:01

I want to show an alert saying that \"Please turn on your GPS\".

How can I get GPS status using phonegap?

I have used following code but I don\'t get any alert m

3条回答
  •  醉酒成梦
    2021-02-06 09:27

    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);
    

提交回复
热议问题