How to enable Location on xamarin forms?

HarshitaHarshita ✭✭✭✭INMember ✭✭✭✭

I want to turn on the location from my app button click in xamarin forms.
Like this image:

How to do this?

Answers

  • NicolaLoroNicolaLoro ✭✭ USMember ✭✭

    The Geolocator Plugin that Vivieknegi linked to, helps you getting access to the device position, but it doesn't let you activate the device location setting, if not already activated.
    If in your app you realize that the GPS is off (and the Geolocator can tell you that), you can prompt the above message you pasted from the PCL/Shared project or .NET class library, but you should call the DependencyService for redirecting the user to the device native settings page for activating it. So, for Android it would be raising an Intent through:
    Xamarin.Forms.Forms.Context.StartActivity(new Android.Content.Intent(Android.Provider.Settings.ActionLocat‌​ionSourceSettings));

  • MakMak ✭✭ INMember ✭✭

    @Harshita how did you achieved that? Using dependency service with os specific implementations or anything better?

  • HarshitaHarshita ✭✭✭✭ INMember ✭✭✭✭
    edited June 10

    @Mak
    Here is it,call it by dependency service from android project

    public async void turnOnGps()
            {
                try
                {
                    MainActivity activity = Forms.Context as MainActivity;
    
                    GoogleApiClient googleApiClient = new GoogleApiClient.Builder(activity)
                        .AddApi(LocationServices.API).Build();
                    googleApiClient.Connect();
                    LocationRequest locationRequest = LocationRequest.Create();
                    locationRequest.SetPriority(LocationRequest.PriorityHighAccuracy);
                    locationRequest.SetInterval(10000);
                    locationRequest.SetFastestInterval(10000 / 2);
    
                    LocationSettingsRequest.Builder
                            locationSettingsRequestBuilder = new LocationSettingsRequest.Builder()
                            .AddLocationRequest(locationRequest);
                    locationSettingsRequestBuilder.SetAlwaysShow(false);
                    LocationSettingsResult locationSettingsResult = await LocationServices.SettingsApi.CheckLocationSettingsAsync(
                        googleApiClient, locationSettingsRequestBuilder.Build());
    
                    if (locationSettingsResult.Status.StatusCode == LocationSettingsStatusCodes.ResolutionRequired)
                    {
                        locationSettingsResult.Status.StartResolutionForResult(activity, 0);
                    }
                }
                catch (Exception ex)
                {
                    GlobalVariables.SendExceptionReport(ex);
                }
            }
    
Sign In or Register to comment.