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:After clicking on Add packages, It will open a window from which you have to select Xam.Plugin.GeoLocator package.
-
- 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.
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:
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.
Create an object of GeoCoder in your cs file:
using Xamarin.Forms.Maps;
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:
On iOS:
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:
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.