Xamarin.Essentials:地理編碼

地理編碼類別會提供 API,可以將地標進行地理編碼為位置座標,也可以將地理編碼座標反轉為地標。

開始使用

若要開始使用此 API,請閱讀 入門指南Xamarin.Essentials,以確保連結庫已正確安裝並設定在您的專案中。

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

不需要進行額外設定。

使用地理編碼

在類別中新增 的 Xamarin.Essentials 參考:

using Xamarin.Essentials;

取得地址的位置座標:

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
}

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

使用反向地理編碼

反向地理編碼是為一組現有座標集取得地標的流程:

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
}

兩個位置之間的距離

LocationLocationExtensions 類別會定義方法,以計算兩個位置之間的距離。 如需範例,請參閱文章Xamarin.Essentials:地理位置。

API

Channel 9YouTube 上尋找更多 Xamarin 影片。