How To Retrieve Your Coordinates On Android And iOS With Xamarin.forms And Xamarin Essentials

Introduction

 
In this article I'll show you how to create a simple Xamarin.Forms application that gets your coordinates and retrieves them on your default map application.
 
This will be possible using the Xamarin Essentials API for Geolocation and Maps.
 
If you want, you can download the solution from my GitHub Repository. 
 
Of course this is a very basic solution and, If you want, I invite you to improve it.
 
Prerequisites
 
IDE: Visual Studio 2019 (All Versions).
 
The steps given below will lead you to the goal.
 
Step 1
 
Create a new blank Xamarin.Forms project for Android and iOS.
 
 
Step 2
 
Write the code for the App.xaml file.
 
With this step, we'll define the general graphic aspect of the application controllers.
 
Go to Solution Explorer -> Double Click on App.xaml, delete the auto-generated code and write the following,
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <Application xmlns="http://xamarin.com/schemas/2014/forms"  
  3.                      xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"  
  4.                      xmlns:d="http://xamarin.com/schemas/2014/forms/design"  
  5.                      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
  6.                      mc:Ignorable="d"  
  7.                      x:Class="GeoMap_Test.App">  
  8.       <Application.Resources>  
  9.             <Style x:Key="CustomLabel" TargetType="Label">  
  10.                   <Setter Property="FontSize" Value="Large"/>  
  11.                   <Setter Property="FontAttributes" Value="Bold"/>  
  12.                   <Setter Property="BackgroundColor" Value="Ivory"/>  
  13.                   <Setter Property="WidthRequest" Value="150"/>  
  14.                   <Setter Property="HeightRequest" Value="80"/>  
  15.                   <Setter Property="HorizontalTextAlignment" Value="Center"/>  
  16.                   <Setter Property="VerticalTextAlignment" Value="Center"/>  
  17.             </Style>  
  18.             <Style x:Key="CustomButton" TargetType="Button">  
  19.                   <Setter Property="BackgroundColor" Value="LightGray"/>  
  20.                   <Setter Property="WidthRequest" Value="180"/>  
  21.                   <Setter Property="HeightRequest" Value="60"/>  
  22.                   <Setter Property="CornerRadius" Value="15"/>  
  23.             </Style>  
  24.       </Application.Resources>  
  25. </Application>   
Step 3
 
Write the code for the MainPage.xaml file.
 
This step allows us to define the aspect of the MainPage.
 
Tip:
 
Please, note that I used the <StackLayout> tag. If you want, you can create a <Grid>.
 
Go to Solution Explorer -> Double Click on MainPage.xaml, delete the auto-generated code and write the following,
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"  
  3.                         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"  
  4.                         xmlns:d="http://xamarin.com/schemas/2014/forms/design"  
  5.                         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
  6.                         mc:Ignorable="d"  
  7.                         x:Class="GeoMap_Test.MainPage"  
  8.                         Title="Geo Map Application"  
  9.                         BackgroundImageSource="dreamstime_xxl_88693404.jpg">  
  10.   
  11.    <ContentPage.Content>  
  12.          <StackLayout Spacing="100" VerticalOptions="CenterAndExpand">  
  13.                <StackLayout Padding="10">  
  14.                      <Label Text="Welcome to the GeoMapUnion test."  
  15.                                  HorizontalOptions="Center" FontSize="Large" TextColor="Brown"/>  
  16.                </StackLayout>  
  17.                <StackLayout HorizontalOptions="Center">  
  18.                      <Button Text="Get your location" Clicked="GetYourLocation_Clicked"  
  19.                                    Style="{StaticResource CustomButton}"/>  
  20.                </StackLayout>  
  21.                <StackLayout Orientation="Horizontal" HorizontalOptions="Center" Spacing="60">  
  22.                      <Label Text="Latitude" x:Name="YourLocationLatitude" Style="{StaticResource CustomLabel}"/>  
  23.                      <Label Text="Longitude" x:Name="YourLocationLongitude" Style="{StaticResource CustomLabel}"/>  
  24.                </StackLayout>  
  25.                <StackLayout HorizontalOptions="Center">  
  26.                      <Button Text="Go To Map" Clicked="GoToMap_Clicked" Style="{StaticResource CustomButton}"/>  
  27.                </StackLayout>  
  28.          </StackLayout>  
  29.    </ContentPage.Content>  
  30. </ContentPage>   
Step 4
 
Write the code-behind for the MainPage.xaml.cs file.
 
Now, we have to define the behavior, the engine, of the application.
 
Go to Solution Explorer -> Double Click on MainPage.xaml.cs, delete the auto-generated code and write the following,
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Linq;  
  5. using System.Text;  
  6. using System.Threading.Tasks;  
  7. using Xamarin.Forms;  
  8. using Xamarin.Essentials;  
  9.   
  10. namespace GeoMap_Test {  
  11.          // Learn more about making custom code visible in the Xamarin.Forms previewer  
  12.          // by visiting https://aka.ms/xamarinforms-previewer  
  13.          [DesignTimeVisible(false)]  
  14.          public partial class MainPage : ContentPage {  
  15.                public MainPage() {  
  16.                      InitializeComponent();  
  17.                }  
  18.   
  19.                /* With this section, we'll implement the 
  20.                GeoLocation API by Xamarin Essentials*/  
  21.                #region GeoLocation API  
  22.                private async void GetYourLocation_Clicked(object sender, EventArgs e) {  
  23.                      try  
  24.                      {  
  25.                            var yourLocation = await Geolocation.GetLocationAsync(new GeolocationRequest()  
  26.                            {  
  27.                                  DesiredAccuracy = GeolocationAccuracy.Medium,  
  28.                                  Timeout = TimeSpan.FromSeconds(30)  
  29.                            });  
  30.   
  31.                            if (yourLocation == null)  
  32.                               await DisplayAlert("Attention""GPS is not available""Ok");  
  33.                            else  
  34.                               YourLocationLatitude.Text = $"{yourLocation.Latitude}";  
  35.                               YourLocationLongitude.Text = $"{yourLocation.Longitude}";  
  36.                      }  
  37.                      catch (Exception ex)  
  38.                      {  
  39.                            await DisplayAlert("Ooops!", $"Something went wrong: {ex.Message}""Ok");  
  40.                      }  
  41.             }  
  42.             #endregion  
  43.   
  44.   
  45.             /* With this section we'll implement the 
  46.             Maps API by Xamarin Essentials*/  
  47.             #region Maps API  
  48.             private async void GoToMap_Clicked(object sender, EventArgs e) {  
  49.                   try  
  50.                   {  
  51.                         await Map.OpenAsync(double.Parse(YourLocationLatitude.Text), double.Parse(YourLocationLongitude.Text), new MapLaunchOptions  
  52.                         {  
  53.                               Name = "Your location",  
  54.                               NavigationMode = NavigationMode.None  
  55.                         });  
  56.                   }  
  57.                   catch (Exception ex1)  
  58.                   {  
  59.                         await DisplayAlert("Ooops!", $"Remember to search your coordinates, first.""Ok");  
  60.                   }  
  61.             }  
  62.             #endregion  
  63.       }  
  64. }   
Step 4
 
Copy the Backgroud Image.
 
Now, download the BackgroudImage.zip file (from the top of the article), unzip and copy the file "dreamstime_xxl_88693404.jpg" into the following folders:
 
Android,
  • \Resources\drawable
  • \Resources\mipmap-anydpi-v26
  • \Resources\mipmap-hdpi
  • \Resources\mipmap-mdpi
  • \Resources\mipmap-xhdpi
  • \Resources\mipmap-xxhdpi
  • \Resources\mipmap-xxxhdpi
iOS,
  • \Resources 
Step 5
 
Add the correct permissions for every mobile platform.
 
Android:
 
Go to Solution Explorer -> GeoMap_Test.Android -> Properties. Double click on AssemblyInfo.cs file and add the following code to the end of the "Add some common permissions" block,
  1. [assembly: UsesFeature("android.hardware.location", Required = false)]  
  2. [assembly: UsesFeature("android.hardware.location.gps", Required = false)]  
  3. [assembly: UsesFeature("android.hardware.location.network", Required = false)]   
 
iOS
 
Go to Solution Explorer -> GeoMap_Test.iOS. Hit F7 on the Info.plist file and add the following code to the last code block,
  1. <key>NSLocationWhenInUseUsageDescription</key>  
  2. <string>Permission for using GPS.</string>   
Step 6
 
Platform Implementation Specifics for both mobile platforms,
 
Android
 
Go to Solution Explorer -> GeoMap_Test.Android -> Double click on MainActivity.cs file and add the following code to the OnCreate Method,
  1. Xamarin.Essentials.Platform.Init(this, savedInstanceState);   
 
iOS
 
No Platform Implementation Specifics.
 
Step 7 - Configure the GPS on the emulators.
 
Now, we have to configure the GPS of both the simulators (of course this step is not necessary if you install the app into your smartphone).
 
Android
 
Launch the simulator -> Click on the three dots (menu) - > Location -> Write the Location name -> Save the point -> Ok.
 
 
 
 
iOS
 
Launch the simulator -> Click on the gear (Settings) -> On Path choose "Apple".
 
 
 
Step 8
 
Output for both the mobile platforms.
 
Well, we've finally arrived to the end. The following images show you the output of the application in both the mobile platforms.
 
Android
 
 
 
 
iOS
 
 
 
 
 
 

Conclusion

 
In this tutorial I've shown you how to create a basic Xamarin.Forms application that gets your coordinates and retrieves them on your default map app.
 
We've used the Xamarin Essentals APIs to reach this goal.
 
Of course, you can improve it and it's possible to "clean the code", but It's not the purpose of this demo.
 
The entire solution is available at this GitHub Repository 
 
Feel free to share your feedback with me.
 
Thank you so much for your attention and interest.


Similar Articles