Find file History
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
..
Failed to load latest commit information.
Images
ReverseGeocode
README.md
ReverseGeocode.sln

README.md

id title brief article sdk
B7DAA598-B6AD-6FBF-8E0E-BD53E99322B3
Reverse Geocode a Location
This recipe shows how use the Geocoder to get an address from a latitude and longitude.

Recipe

Follow these steps to reverse geocode a location.

  1. In Main.axml (or whatever layout file you wish) add the following XML.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<Button
    android:id="@+id/revGeocodeButton"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/revGeocodeButtonText"
    />
 <TextView
    android:id="@+id/addressText"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
   />
</LinearLayout>
  1. Add a string resource named revGeocodeButtonText to Strings.Xml.
<string name="revGeocodeButtonText">Reverse Geocode Location</string>
  1. Add a click event handler for the button in the Activity’s OnCreate method.
var button = FindViewById<Button> (Resource.Id.revGeocodeButton);
button.Click += async (sender, e) => { … }

Notice that this is using an async lambda to perform the work when the button is clicked. This will cause the work to performed asynchronously and not block the UI thread.

  1. Next add the following code to the click event handler:
button.Click += async (sender, e) => {
	var geo = new Geocoder (this);
	var addresses = await geo.GetFromLocationAsync (42.37419, -71.120639, 1);

	var addressText = FindViewById<TextView> (Resource.Id.addressText);
	if (addresses.Any())
	{
		addresses.ToList().ForEach (addr => addressText.Append (addr + System.Environment.NewLine + System.Environment.NewLine));
	}
	else
	{
		addressText.Text= "Could not find any addresses.";
	}
};

Running the application results in the address being displayed as shown in the screenshot above.

Additional Information

This recipe creates a Geocoder instance, which is in the Android.Locations namespace. The Geocoder calls GetFromLocationAsync with the latitude and longitude to reverse geocode. This will perform the network call asynchronously so that main UI thread is not blocked. When the result is returned, the method will return a list of addresses and continue on the UI thread. In this call 1 address is returned because that is the number passed into the third argument of the GetFromLocationAsync call. The returned address contains a variety of information about the location, including the street address.