To implement such a geocoding example, we use the Maps module of Xamarin.Forms. It is initialized at the very same place where Forms.Init is called, namely in OnCreate for Android
FormsMaps.Init(this, savedInstanceState);
and in FinishedLaunching for iOS:
FormsMaps.Init();
In the shared code, we define a searchBar. It is similar to an Entry element, but comes with buttons and events more dedicated to searching something. When pressing the “Search” button, we call an asynchronous method SearchAddress passing the search string and await the resulting coordinate representation. The latter are displayed as an alert dialog.
var searchBar = new SearchBar {
Placeholder = "Enter an address",
VerticalOptions = LayoutOptions.Start,
};
searchBar.SearchButtonPressed += async (sender, e) => {
var coordinates = await SearchAddress(searchBar.Text);
MainPage.DisplayAlert("Location", coordinates, "Ok");
};
Before implementing the SearchAddress method, we add the searchBar to the MainPage and make sure to have sufficient padding on the top edge of the iOS screen.
MainPage = new ContentPage {
Padding = new Thickness(0, Device.OnPlatform(20, 0, 0), 0, 0),
Content = searchBar,
};
The SearchAddress method is the place where the magic happens. We create a new Geocoder object and call an asynchronous method GetPositionsForAddressAsync. After awaiting a result of type IEnumerable, we convert it to a List and check whether it contains any element. If so, we return a string containing latitude and longitude of the first item. Otherwise, we return an error message.
static async Task<string> SearchAddress(string address)
{
var geocoder = new Geocoder();
var positions = (await geocoder.GetPositionsForAddressAsync(address)).ToList();
if (positions.Any())
return string.Format("Latitude: {0}\nLongitude: {1}",
positions.First().Latitude,
positions.First().Longitude);
else
return "No position found";
}