Search code examples
androidcordovaionic-frameworkphonegap-plugins

how to detect GPS is on or off using cordova


I am creating mobile app which uses geolocation plugin and I want show popup to enable GPS when GPS is turned off. How to detect whether GPS is on or off and how to show location setting to on GPS?


Solution

  • It can be done using the following Cordova Plugin: https://github.com/dpa99c/cordova-diagnostic-plugin

    Add the plugin:

    ionic plugin add cordova.plugins.diagnostic
    

    Check for GPS whether it is enabled or not as below,

    cordova.plugins.diagnostic.isLocationEnabled(successCallback, errorCallback);
    

    If GPS is not enabled, Open Location settings as below,

    cordova.plugins.diagnostic.switchToLocationSettings();
    

    Complete code:

    cordova.plugins.diagnostic.isLocationEnabled(successCallback, errorCallback);
    function successCallback(res){
      console.log("Location is " + (res ? "Enabled" : "not Enabled"));
      !res ? cordova.plugins.diagnostic.switchToLocationSettings() : '';
    }
    function errorCallback(err){
      console.log("Error: "+JSON.stringify(err));
    }