地理編碼

Browse sample. 流覽範例

本文說明如何使用 .NET 多平臺應用程式 UI (.NET MAUI) IGeocoding 介面。 此介面提供 API,將地標記地理編碼為位置座標,並將地理編碼座標反向編碼為地標記。

介面的預設實作 IGeocoding 可透過 Geocoding.Default 屬性取得。 IGeocoding介面和Geocoding類別都包含在 命名空間中Microsoft.Maui.Devices.Sensors

開始使用

若要存取 地理編碼 功能,需要下列平臺特定設定。

不需要任何設定。

使用地理編碼

下列範例示範如何取得位址的位置座標:

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

高度不一定可用。 如果無法使用, Altitude 則屬性可能是 null,或值可能是 0。 如可使用高度,此值 (公尺) 會高於海平面。

反向地理編碼

反向地理編碼是取得現有座標集的尺規程式。 下列範例示範取得印記:

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 "";
}

取得兩個位置之間的距離

LocationLocationExtensions 類別會定義方法,以計算兩個位置之間的距離。 如需取得兩個位置之間距離的範例,請參閱 兩個位置之間的距離。