Dela via


Xamarin.Essentials: Geocoding

The Geocoding class provides APIs to geocode a placemark to a positional coordinates and reverse geocode coordinates to a placemark.

Get started

To start using this API, read the getting started guide for Xamarin.Essentials to ensure the library is properly installed and set up in your projects.

To access the Geocoding functionality the following platform specific setup is required.

No additional setup required.

Using Geocoding

Add a reference to Xamarin.Essentials in your class:

using Xamarin.Essentials;

Getting location coordinates for an address:

try
{
    var address =  "Microsoft Building 25 Redmond WA USA";
    var locations = await Geocoding.GetLocationsAsync(address);

    var location = locations?.FirstOrDefault();
    if (location != null)
    {
        Console.WriteLine($"Latitude: {location.Latitude}, Longitude: {location.Longitude}, Altitude: {location.Altitude}");
    }
}
catch (FeatureNotSupportedException fnsEx)
{
    // Feature not supported on device
}
catch (Exception ex)
{
    // Handle exception that may have occurred in geocoding
}

The altitude isn't always available. If it is not available, the Altitude property might be null or the value might be zero. If the altitude is available, the value is in meters above sea level.

Using Reverse Geocoding

Reverse geocoding is the process of getting placemarks for an existing set of coordinates:

try
{
    var lat = 47.673988;
    var lon = -122.121513;

    var placemarks = await Geocoding.GetPlacemarksAsync(lat, lon);

    var placemark = placemarks?.FirstOrDefault();
    if (placemark != null)
    {
        var geocodeAddress =
            $"AdminArea:       {placemark.AdminArea}\n" +
            $"CountryCode:     {placemark.CountryCode}\n" +
            $"CountryName:     {placemark.CountryName}\n" +
            $"FeatureName:     {placemark.FeatureName}\n" +
            $"Locality:        {placemark.Locality}\n" +
            $"PostalCode:      {placemark.PostalCode}\n" +
            $"SubAdminArea:    {placemark.SubAdminArea}\n" +
            $"SubLocality:     {placemark.SubLocality}\n" +
            $"SubThoroughfare: {placemark.SubThoroughfare}\n" +
            $"Thoroughfare:    {placemark.Thoroughfare}\n";

        Console.WriteLine(geocodeAddress);
    }
}
catch (FeatureNotSupportedException fnsEx)
{
    // Feature not supported on device
}
catch (Exception ex)
{
    // Handle exception that may have occurred in geocoding
}

Distance between Two Locations

The Location and LocationExtensions classes define methods to calculate the distance between two locations. See the article Xamarin.Essentials: Geolocation for an example.

API

Find more Xamarin videos on Channel 9 and YouTube.