Bewerken

Delen via


Geocoding

Browse sample. Browse the sample

This article describes how you can use the .NET Multi-platform App UI (.NET MAUI) IGeocoding interface. This interfaces provides APIs to geocode a placemark to a positional coordinates and reverse geocode coordinates to a placemark.

The default implementation of the IGeocoding interface is available through the Geocoding.Default property. Both the IGeocoding interface and Geocoding class are contained in the Microsoft.Maui.Devices.Sensors namespace.

Get started

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

No setup is required.

Use geocoding

The following example demonstrates how to get the location coordinates for an address:

string address = "Microsoft Building 25 Redmond WA USA";
IEnumerable<Location> locations = await Geocoding.Default.GetLocationsAsync(address);

Location location = locations?.FirstOrDefault();

if (location != null)
    Console.WriteLine($"Latitude: {location.Latitude}, Longitude: {location.Longitude}, Altitude: {location.Altitude}");

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

Reverse geocoding

Reverse geocoding is the process of getting placemarks for an existing set of coordinates. The following example demonstrates getting placemarks:

private async Task<string> GetGeocodeReverseData(double latitude = 47.673988, double longitude = -122.121513)
{
    IEnumerable<Placemark> placemarks = await Geocoding.Default.GetPlacemarksAsync(latitude, longitude);

    Placemark placemark = placemarks?.FirstOrDefault();

    if (placemark != null)
    {
        return
            $"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";

    }

    return "";
}

Get the distance between two locations

The Location and LocationExtensions classes define methods to calculate the distance between two locations. For an example of getting the distance between two locations, see Distance between two locations.