xamarinbg 1

How to use GeoLocator in Xamarin.Forms?

Abstract

These days every application wants to access your location. It is a very basic requirement but the question is how to achieve this. Sometimes, we use GeoLocation but get stuck in issues regarding permissions. Accessing Location is not a difficult task but we need to be very careful in giving permissions. This article contains everything by which you can get the latitude and longitude of the location by providing desired permissions. By using latitude/longitude, we can also obtain an address.

Introduction

Xamarin.Forms provide the readymade plugin for accessing the location of your device from both platforms(Android and iOS). We need to add that plugin and write a single function for using it. This article will also demonstrate how to add permissions for Android and iOS. I have added the screenshots using MacBook but you will find everything same on Windows.

Steps for using GeoLocator:

    • 1) Create a new cross-platform app in Visual Studio.
    • 2) For using GeoLocator, you need to add the package Xam.Plugin.GeoLocator in your project as shown below:GeoLocator in Xamarin StapeAfter clicking on Add packages, It will open a window from which you have to select Xam.Plugin.GeoLocator package.

GeoLocator in Xamarin Stape2

    • 3) Before accessing the GPS in Android or iOS, we need to add Location permission.

Android:

For Adding the Location permission in Android right click on your project and then go to the options(or properties). In Required permissions check AccessFineLocation and AccessCoarseLocation.

GeoLocator in Xamarin Stape3

Now you need to add some code in MainActivity as given below.


public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Android.Content.PM.Permission[] grantResults)
{
Plugin.Permissions.PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}

Add this function in your MainActivity file and then in OnCreate method write the lines mentioned below.


global::Xamarin.FormsMaps.Init(this, bundle);
Plugin.CurrentActivity.CrossCurrentActivity.Current.Init(this, bundle);

iOS:

We need to give permission in info.plist:

GeoLocator in Xamarin Stape4

Adding Privacy-Location Usage Description and Location When In Use Usage Description in the source of info.plist. Add one line code in FinishedLaunching of AppDelegate. This will be used for initializing the map.

global::Xamarin.FormsMaps.Init();

  • 4) Now we need to add a XAML and write the code for displaying the location. We are adding a button and label. After clicking that button, the label will display your location.
    <ContentPage.Content>
    <StackLayout Padding="0,20,0,0" VerticalOptions="Center" HorizontalOptions="Center">
    <Label Text="Click Below To Get Location" TextColor="Blue" HorizontalOptions="Center"/>
    <Button Text="Find Location" Clicked="OnButtonClicked" BackgroundColor="Azure"
    HorizontalOptions="CenterAndExpand"/>
    <Label x:Name="addressLabel" TextColor="Navy" Margin="20,20,0,0" />
    </StackLayout>
    </ContentPage.Content>
  • 5) Now In the corresponding cs file, we need to write the button click event. Firstly, you need to add namespace.

    using Xamarin.Forms.Maps;
    Create an object of GeoCoder in your cs file:

    Geocoder geoCoder = new Geocoder();
    async void OnButtonClicked(object sender, EventArgs e)
    {
    try
    {
    var locator = CrossGeolocator.Current;
    locator.DesiredAccuracy = 50;
    var position = await locator.GetPositionAsync(TimeSpan.FromSeconds(2));
    double? latitude = Convert.ToDouble(position.Latitude);
    double? longitude = Convert.ToDouble(position.Longitude);
    if (latitude != null && longitude != null)
    {
    var revposition = new Position(latitude.Value, longitude.Value);
    var possibleAddresses = await geoCoder.GetAddressesForPositionAsync(revposition);
    foreach (var address in possibleAddresses)
    addressLabel.Text += address + "\n";
    }
    else addressLabel.Text += "error";
    }
    catch (Exception ex)
    {
    await DisplayAlert("Notification", "Unable to get GPS Location " + ex, "Ok");
    }
    }
  • 6) Now run the code on both the platforms and you’ll get the output as shown below:

On Android:

GeoLocator in Xamarin Stape5

On iOS:

GeoLocator in Xamarin Stape6

Conclusion:

This will completely help you in showing the current device location. If you don’t want to use this plugin then you need to make a dependency service for xamarin app development

About Author:
Author Rashi saini is working in QSS Technosoft as a Xamarin Developer. She has a good experience in Xamarin.Forms(PCL and Shared both) and Xamarin native. She likes to be aware with new trends in technology.

About QSS:
QSS Technosoft is leading Xamarin App Development Company developing a cross-platform mobile applications for its esteemed customers. The company has a core competency in developing and delivering Enterprise level Xamarin applications both in Native and Hybrid platforms. The Xamarin competency has experienced and dedicated team of Xamarin developers.

Tags: , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

Hire certified

Developers

  • Avg. 6+ Years of Experience.
  • Dedicated Resource on Demand.
  • NDA Protected Terms.
  • Start/Interview within 24 Hours.
  • Flexible Engagement Models.
  • Best code practices.
Start Now!
E-Book

eBook

6 Most Important Factors for a Successful Mobile App!

Every precaution that you take in the development process will help you to be effective in building products that will help you grow and reach your goals. Consider these 6 factors before heading for mobile app development.

Subscribe to our newsletter and stay updated

Loading