Use PhoneGap to Check if GPS is enabled

前端 未结 6 1745
后悔当初
后悔当初 2020-12-03 10:41

I am building an app using PhoneGap. While using the Geolocation API of phonegap I realized that the APIs time out for two reasons and the same error is thrown: 1. If GPS is

相关标签:
6条回答
  • 2020-12-03 11:11

    Just for new users redirected here there is a plugin (which started about the middle of 2014) which is called Cordova diagnostic plugin:

    This Cordova/Phonegap plugin for iOS, Android and Windows 10 Mobile is used to manage device settings such as Location, Bluetooth and WiFi. It enables management of run-time permissions, device hardware and core OS features. ref

    0 讨论(0)
  • 2020-12-03 11:26

    I tried DaveAlden's solution above but it didn't work, partially because the first function he calls cordova.plugins.diagnostic.isGpsLocationAvailable() is Android-only per the plugin docs.

    As he says, first add the two plugins:

    cordova plugin add cordova.plugins.diagnostic --save
    cordova plugin cordova-plugin-request-location-accuracy --save
    

    Then add the following functions:

    // Checks to see if GPS is enabled AND if the app is authorized
    checkEnabled(){
        cordova.plugins.diagnostic.isLocationAvailable(
          (available) => { onSuccess(available); },
          (error) => { goToSettings(error); }
        );
    }
    
    onSuccess(available) {
      if(available) { // do something };
      else goToSettings(available);
    }
    
    // Output error to console
    // Prompt user to enable GPS, on OK switch to phone settings
    goToSettings(error) {
      console.log("error: ", error);
      if(window.confirm("You need to enable location settings to use the geolocation feature.")) {
        cordova.plugins.diagnostic.switchToSettings();
      }
    }
    
    checkEnabled(); // Run check
    

    Hope this helps someone else who comes along this answer.

    0 讨论(0)
  • 2020-12-03 11:29

    Using apache cordova 3 android platform

    In the GeoBroker.java file on the exectute method add the following action after the locationManager has been instantiated.

    if(action.equals("isGPSEnabled")){
                PluginResult result;
                if ( locationManager.isProviderEnabled( LocationManager.GPS_PROVIDER )){
                    result = new PluginResult(PluginResult.Status.OK);
                }else{
                    result = new PluginResult(PluginResult.Status.ERROR);
                }
                callbackContext.sendPluginResult(result);
            }
    

    Then in the geolocation.js file in the plugins folder of your assets add the expose the new functionality

     /**
         * Asynchronously checks if gps is enabled.
         *
         * @param {Function} successCallback    The function to call when gps is enabled.
         * @param {Function} errorCallback      The function to call when gps is not enabled. (OPTIONAL)
         */
        isGPSEnabled:function(successCallback, errorCallback){
            exec(successCallback, errorCallback, "Geolocation", "isGPSEnabled", []);
        }
    

    Hope it helps

    0 讨论(0)
  • 2020-12-03 11:33

    You could check the error code in PositionError parameter of geolocationError in your call to getCurrentPosition. I am guessing that it will be PositionError.PERMISSION_DENIED when gps is not enabled, and PositionError.POSITION_UNAVAILABLE or PositionError.TIMEOUT when gps is enabled but there are other issues.

    Note that this is platform dependent. You would probably have to write a contrived error message that says "Could not get the current position. Either GPS signals are weak or GPS has been switched off".

    One thing you can try is to call getCurrentPosition with an incredibly small timeout, say 1 ms. If it says permission denied, you can conclude that gps is disabled and if it times out, you can assume that gps is enabled. I do not have time to test this, you could probably edit this answer with result of your tests.

    Another thing you can try is to use the diagnostic phonegap plugin for android. You will have to make sure you use the plugins for the other platforms also, but they are all also mostly there.

    0 讨论(0)
  • 2020-12-03 11:34

    To handle this case most gracefully, you can use cordova.plugins.diagnostic to check if GPS setting is enabled and (on Android 6+) check if app has run-time authorization, and (if it's not enabled), use cordova-plugin-request-location-accuracy to automatically switch on GPS via a native dialog without requiring users to manually switch it on via the settings page. However, since the latter relies on an up-to-date Google Play Services library on the device, it is good practice to fallback to the manual switching if the automatic switching fails.

    First add the required plugins to your project:

    cordova plugin add cordova.plugins.diagnostic --save
    cordova plugin cordova-plugin-request-location-accuracy --save
    

    Then you'd do it something like this:

    function checkAvailability(){
        cordova.plugins.diagnostic.isGpsLocationAvailable(function(available){
            console.log("GPS location is " + (available ? "available" : "not available"));
            if(!available){
               checkAuthorization();
            }else{
                console.log("GPS location is ready to use");
            }
        }, function(error){
            console.error("The following error occurred: "+error);
        });
    }
    
    function checkAuthorization(){
        cordova.plugins.diagnostic.isLocationAuthorized(function(authorized){
            console.log("Location is " + (authorized ? "authorized" : "unauthorized"));
            if(authorized){
                checkDeviceSetting();
            }else{
                cordova.plugins.diagnostic.requestLocationAuthorization(function(status){
                    switch(status){
                        case cordova.plugins.diagnostic.permissionStatus.GRANTED:
                            console.log("Permission granted");
                            checkDeviceSetting();
                            break;
                        case cordova.plugins.diagnostic.permissionStatus.DENIED:
                            console.log("Permission denied");
                            // User denied permission
                            break;
                        case cordova.plugins.diagnostic.permissionStatus.DENIED_ALWAYS:
                            console.log("Permission permanently denied");
                            // User denied permission permanently
                            break;
                    }
                }, function(error){
                    console.error(error);
                });
            }
        }, function(error){
            console.error("The following error occurred: "+error);
        });
    }
    
    function checkDeviceSetting(){
        cordova.plugins.diagnostic.isGpsLocationEnabled(function(enabled){
            console.log("GPS location setting is " + (enabled ? "enabled" : "disabled"));
            if(!enabled){
                cordova.plugins.locationAccuracy.request(function (success){
                    console.log("Successfully requested high accuracy location mode: "+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(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_PRIORITY_HIGH_ACCURACY);
            }
        }, function(error){
            console.error("The following error occurred: "+error);
        });
    }
    
    checkAvailability(); // start the check
    
    0 讨论(0)
  • 2020-12-03 11:34

    I had a similar issue with some devices. Managed to resolve it with the code below:

    var options = {maximumAge: 0, timeout: 10000, enableHighAccuracy:true};
    navigator.geolocation.getCurrentPosition(onSuccess, onError, options);
    
    0 讨论(0)
提交回复
热议问题