Search code examples
androidgpsappcelerator

How to check if the location service is enabled or not in Appcelerator


Can you please help me to check if the location service is enabled or not in Appcelerator. I am working with Titanium SDk 6.1.2 and Samsung S5 with Marshmellow OS. Even though the GPS is enabled/not in device, But every time it results in false. Thanks in Advance.


Solution

  • First of all you need to check for Location Permissions for app in Android & then you need to check if location service is enabled in device or not.

    Both are different statements.

    First one checks for app permission to access location & 2nd is about checking location service is on or off.

    Without checking Location Permissions first on Android, you cannot check for location on/off state, else it will always lead to false status.

    First of all add this in tiapp.xml in ios -> plist -> dict

    <key>NSLocationAlwaysUsageDescription</key>
    <string>Determine Current Location</string>
    

    Now here's the cross-compatible code for Android/iOS.

    function checkLocationEnabledOrNot(_callback, _args) {
        if (Titanium.Geolocation.locationServicesEnabled) {
            _callback(_args);
    
        } else {
            alert("Turn on location on your device.");
        }
    }
    
    
    // pass _callback method you want to call after successful access to location
    // you can also pass arguments as 2nd parameter to the function you want to call
    
    function startLocationProcess(_callback, _args) {
        Ti.Geolocation.accuracy = Ti.Geolocation.ACCURACY_HIGH;
    
        if (OS_IOS) {
            checkLocationEnabledOrNot(_callback, _args);
    
        } else if (OS_ANDROID) {
            if (Ti.Geolocation.hasLocationPermissions()) {
                checkLocationEnabledOrNot(_callback, _args);
    
            } else {
                Ti.Geolocation.requestLocationPermissions(Ti.Geolocation.AUTHORIZATION_ALWAYS, function (locationEvent) {
                    if (locationEvent.success) {
                        checkLocationEnabledOrNot(_callback, _args);
    
                    } else {
                        alert("Location permissions are required to access locations.");
                    }
                });
            }
        }
    }
    

    Now, on a button click whatever you want to do after location check, you can simply do it like this:

    function anotherFunction(name) {
        alert(name);
    }
    
    
    $.someButton.addEventListener('click', function (e) {
        startLocationProcess(anotherFunction, "Hello D.Ish");
    });