Geocode an Address

PDF for offline use
Sample Code:
Related Articles:
Related SDKs:

Let us know how you feel about this

Translation Quality


0/250

This recipe shows how use the Geocoder to get a latitude and longitude for an address.

Recipe

Follow these steps to geocode an address.

  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/geocodeButton"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/geocodeButtonText"
    />
 <TextView
    android:id="@+id/addressText"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
   />
</LinearLayout>
  1. Add a string resource named geocodeButtonText to Strings.Xml.
<string name="geocodeButtonText">Geocode Address</string>
  1. Add a click event handler for the button in the Activity’s OnCreate method.
var button = FindViewById<Button> (Resource.Id.geocodeButton);
button.Click += (sender, e) => { … }
  1. Add the following code to the click event handler to call the Geocoder on a separate thread.
button.Click += (sender, e) => {
       new Thread (new ThreadStart (() => {
              var geo = new Geocoder (this);

              var addresses = geo.GetFromLocationName (
                      "50 Church St, Cambridge, MA", 1);

              RunOnUiThread (() => {
                      var addressText = FindViewById<TextView>
                             (Resource.Id.addressText);

                      addresses.ToList ().ForEach ((addr) => {
                             addressText.Append (addr.ToString () +
                                    "\r\n\r\n");
                      } );
              } );
       } )).Start ();
} ;
  1. Running the application results in the address being displayed with location information as shown in the screenshot above.

Additional Information

This creates a Geocoder instance, which is in the Andorid.Locations namespace. The Geocoder calls GetFromLocationName with the address to geocode. When the result is returned, the code adds it to the UI inside a call to RunOnUiThread. The result of the Geocoder is an address list. In this call 1 address is returned because that is the number passed into the second argument of the GetFromLocationName call. The returned address contains a variety of information about the location, including the latitude and longitude.

Xamarin Workbook

If it's not already installed, install the Xamarin Workbooks app first. The workbook file should download automatically, but if it doesn't, just click to start the workbook download manually.