Follow these simple steps to use a GeoLocator in Xamarin.Forms in Android

xamarin-mobile-11-638

As we are breathing in the age of gadgets and applications, where utmost every application likes to fetch the location of every single user and for this, they are requesting you to permit them to access your real-time location. While a lot of time it has been observed that developers prefer to use Geolocation to track the user’s location, but get stuck in so many technical issues at the time of taking users permission to access location. Well, by taking care of a few little things location tracking is not such a hassle task. For a better experience, use the below-mentioned code in your Xamarin.forms to track the actual location of a user.

Follow the steps to use GeoLocator in Xamarin.forms for Android:

  1. Create a new cross-platform app using Visual Studio.

d

      2. Now add a Xam.Plugin.GeoLocator in your project to use GeoLocator.

2

       3. When you will hit the Add Packages option over there, a new window will be open from where you will be able to select Xam.Plugin.Geolocator package. See the picture.

3
4. Now, to access the GPS in Android, at first add a location permission. For this, open your project, click the right click of your mouse and the, simply go on to the options / properties button and check AccessFineLocation and AccessCoarseLocation and then click “ok.”

      5. Now its time to add a short and simple code in your application and here is that code,

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);

 6. In the next step, add a XAML file in your project and write this code. This code will display the location whenever you will press on the added button or label.

<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>

 7. Now, open the corresponding cs file to add this button click event code:

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”);
}

 8. It’s all done now, enjoy running the code successfully.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>