Share via


Xamarin.Forms Map Geocoding

The Xamarin.Forms.Maps namespace provides a Geocoder class, which converts between string addresses and latitude and longitude coordinates that are stored in Position objects. For more information about the Position struct, see Map Position and Distance.

Note

An alternative geocoding API is available in Xamarin.Essentials. The Xamarin.Essentials Geocoding API offers structured address data when geocoding addresses, as opposed to the strings returned by this API. For more information, see Xamarin.Essentials: Geocoding.

Geocode an address

A street address can be geocoded into latitude and longitude coordinates by creating a Geocoder instance and calling the GetPositionsForAddressAsync method on the Geocoder instance:

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

The GetPositionsForAddressAsync method takes a string argument that represents the address, and asynchronously returns a collection of Position objects that could represent the address.

Reverse geocode an address

Latitude and longitude coordinates can be reverse geocoded into a street address by creating a Geocoder instance and calling the GetAddressesForPositionAsync method on the Geocoder instance:

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();

The GetAddressesForPositionAsync method takes a Position argument comprised of latitude and longitude coordinates, and asynchronously returns a collection of strings that represent the addresses near the position.