Use PhoneGap to Check if GPS is enabled

前端 未结 6 1766
后悔当初
后悔当初 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: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.

提交回复
热议问题