Xamarin.Essentials:地理编码
Geocoding 类提供了 API,既可以将地标地理编码为位置坐标,又可以将坐标反向地理编码为地标。
入门
若要开始使用此 API,请阅读 Xamarin.Essentials 的入门指南,确保在项目中正确安装和设置库。
若要访问 Geocoding 功能,需要以下特定于平台的设置。
使用 Geocoding
在类中添加对 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
}
两个位置之间的距离
Location
和 LocationExtensions
类定义了可用于计算两个位置之间的距离的方法。 有关示例,请参阅文章Xamarin.Essentials:地理位置。