our

Latest Blogs

How to retrieve coordinates on android and iOS with Xamarin.forms and Xamarin essentials?

iFour Team -July 05, 2021

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

  •  
  •  
  •  
How to retrieve coordinates on android and iOS with Xamarin.forms and Xamarin essentials?

In this article, we will be going to have a very interesting topic on how to retrieve coordinate in Xamarin.forms. In this project, we will find the location with the help of Xamarin.Essentials.

In Xamarin.forms, Geolocation class is available at Xamarin.Essentials API for getting the current location on different platforms like Android, and iOS. Using Xamarin.Essentials we can use a single API that will be work at all the cross-platform on Xamarin.forms.

Now, let’s see how to retrieve your coordinates on both the application android and iOS with the use of Xamarin.forms and Xamarin essentials.

Step: 1

Firstly, create Xamarin.Forms as a blank project and set the platform like android and iOS.

Step: 2

Now, add the reference Xamarin.Essentials, for adding reference Go to Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution.

After that select Browse and type Xamarin.Essentials, and install it.

Add Xamarin.Essentials package

Image: Add Xamarin.Essentials package

Step: 3

After the creation of your project, open App.Xaml file and add the below code. This is a general graphic aspect to express your application.

You just delete auto-generated data and add the below code else just replace the new data with auto-generated data.




    
   
					

Here we can set the style for labels and buttons, we can add style in App.Xaml because if once we create a style for any control in App.Xaml then no need to set the style for particular control we can use this style in the over-all application.

Step: 4

Now, open MainPage.Xaml file and add the below code for getting the location.

Just delete auto-generated data and add the below code else just replace the new data with auto-generated data.




     
     
     
     
     
     
     

            



Here, we can add some buttons and labels, buttons are used to get the location, and labels are used to get the latitude and longitude.

Latitude and longitude are used to describe the location on the Earth. They can describe the direction latitude and can describe east-west direction and longitude can describe north-south direction across the Earth.

Step: 5

Now, we can set the behavior of the application in code-behind. So, open MainPage.Xaml.CS file and just delete auto-generated data and add below code else just replace the new data with auto-generated data.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Essentials;
using Xamarin.Forms;

namespace XamarinCoordinates
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private async void Findthelocation_Clicked(object sender, EventArgs e)
        {
            try
            {
                var FindLocation = await Geolocation.GetLocationAsync(new GeolocationRequest()
                {
                    DesiredAccuracy = GeolocationAccuracy.Medium,
                    Timeout = TimeSpan.FromSeconds(20)
                });

                if (FindLocation == null)
                    await DisplayAlert("Attention", "first enable GPS.", "Ok");
                else
                    LatitudeLocation.Text = $"{FindLocation.Latitude}";
                    LongitudeLocation.Text = $"{FindLocation.Longitude}";
            }
            catch (Exception ex)
            {
                await DisplayAlert("Ooops!", $"Something went wrong:" + ex, "Ok");
            }
        }

        private async void GoingToMap_Clicked(object sender, EventArgs e)
        {
            try
            {
                await Map.OpenAsync(double.Parse(LatitudeLocation.Text), double.Parse(LongitudeLocation.Text), new MapLaunchOptions
                {
                    Name = "Your location",
                    NavigationMode = NavigationMode.None
                });
            }
            catch (Exception ex1)
            {
                await DisplayAlert("Ooops!", $"Something went wrong..", "Ok");
            }
        }
    }
}
				
Step: 6

Now, add the background image on both the platform android and, iOS.

For android, download one image for suited the map background and copy and paste it. In android open Solution Explorer -> Android file -> Resources and paste the image in below folders drawable, mipmap-anydpi-v26, mipmap-hdpi, mipmap-mdpi, mipmap-xhdpi, mipmap-xxhdpi, mipmap-xxxhdpi.

For iOS, copy image and paste it in open Solution Explorer -> iOS file -> Resources.

Step: 7

Our design is created and we can also set the behavior of the application, now need to add permission for every mobile platform.

Open Solution Explorer -> XamarinCoordinates.Android (Android file) -> Properties -> AssemblyInfo.cs file. And note down the below code to add the permission.

[assembly: UsesFeature("android.hardware.location", Required = false)]
[assembly: UsesFeature("android.hardware.location.gps", Required = false)]
[assembly: UsesFeature("android.hardware.location.network", Required = false)]
				
AssemblyInfo.cs file example

Image: AssemblyInfo.cs file example

For iOS go to Solution Explorer -> XamarinCoordinates.iOS (iOS file) and open the info.plist file using the press f7 button and add the below code at the last block.

	
NSLocationWhenInUseUsageDescription
Permission for using GPS.
					
info.plist file example

Image: info.plist file example

Step: 8

Now, need to set platform implementation for both Android and iOS.

Open Solution Explorer -> XamarinCoordinates.Android (Android file) -> MainActivity.cs and add one-line code on the OnCreate method.

MainActivity.cs file example

Image: MainActivity.cs file example

One Stop Solution for Xamarin Mobile App Development ? Your Search ends here.

In iOS, there is no need for specific platform implementation. All setups are done, our application is ready to run. Now we have to configure the GPS for both the application Android and iOS.

For Android, Start the Emulator -> Press the menu button -> Location -> Enter the location name -> Save it -> Ok.

Finally, all steps have been completed to retrieve your coordination for both the application Android and iOS. Let's see the output. ha

Output

output1
output2
Conclusion

In this article, we have seen how to create simple Xamarin.Forms application and get the current location using a single Xamarin.Essentials API on cross-platform Android, and iOS. We can also retrieve coordinates using Xamarin.Essentials for UWP, there is some method that can change.

Work with us

Well do everything we can to make our next best project!

Our Insights

Check out our most recent blogs

An in-depth guide on Angular Dependency Providers
An in-depth guide on Angular Dependency Providers

What is Angular? Angular is a frontend development framework used for building single-page client applications using HTML and Typescript. It is written in Typescript. What...

A simple guide on AOT Compilation in Angular
A simple guide on AOT Compilation in Angular

What is a Compiler? A compiler is nothing but a part of code that converts one programming language to another. If we talk about some simple programming languages like C, C++,...

Implement Attribute, Class, and Style binding in Angular
Implement Attribute, Class, and Style binding in Angular

What is binding in Angular? Binding in angular apps is the automatic synchronization of data within the model and view components. You can use data binding to define things...

Our Partners

Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo

Work With Us

Well do everything we can to make our next best project!