Xamarin.Forms 地理编码

命名空间 Xamarin.Forms.Maps 提供一个 Geocoder 类,该类在字符串地址与存储在 Position 对象中的纬度和经度坐标之间进行转换。 有关 Position 结构的详细信息,请参阅地图位置和距离

注意

Xamarin.Essentials 中提供了备用地理编码 API。 Xamarin.EssentialsGeocoding API 在对地址进行地理编码时提供结构化地址数据,而不是此 API 返回的字符串。 有关详细信息,请参阅 Xamarin.Essentials:地理编码

对地址进行地理编码

可以通过创建 Geocoder 实例并在 Geocoder 实例上调用 GetPositionsForAddressAsync 方法,将街道地址地理编码为纬度和经度坐标:

using Xamarin.Forms.Maps;
// ...
Geocoder geoCoder = new Geocoder();

IEnumerable<Position> approximateLocations = await geoCoder.GetPositionsForAddressAsync("Pacific Ave, San Francisco, California");
Position position = approximateLocations.FirstOrDefault();
string coordinates = $"{position.Latitude}, {position.Longitude}";

GetPositionsForAddressAsync 方法采用表示地址的 string 参数,并异步返回可以表示地址的 Position 对象的集合。

对地址进行反向地理编码

可以通过创建 Geocoder 实例并在 Geocoder 实例上调用 GetAddressesForPositionAsync 方法,将纬度和经度坐标反向编码为街道地址:

using Xamarin.Forms.Maps;
// ...
Geocoder geoCoder = new Geocoder();

Position position = new Position(37.8044866, -122.4324132);
IEnumerable<string> possibleAddresses = await geoCoder.GetAddressesForPositionAsync(position);
string address = possibleAddresses.FirstOrDefault();

GetAddressesForPositionAsync 方法采用由纬度和经度坐标组成的 Position 参数,并异步返回表示位置附近地址的字符串集合。