Using Geocoding Services with Android

The Android SDK includes the Geocoder (android.location.Geocoder) class to facilitate interaction with the handset's geocoding and reverse-geocoding services, if they are present. Instantiating a Geocoder is simple: Geocoder coder = new Geocoder(getApplicationContext());

When you have a valid Geocoder, you can begin to use any geocoding or reverse-geocoding services available on the device.

Geocoding: Translating Addresses into Coordinates

You can use the Geocoder class getFromLocationName()method to resolve a location into coordinates. This method takes two parameters: the string containing the location information and the number of results you want returned. For example, the following code looks up Springfield and limits the number of results to three:

String strLocation = "Springfield"; List<Address> geocodeResults =

coder.getFromLocationName(strLocation, 1);

You can iterate through the Geocoder results by using an iterator:

Iterator<Address> locations = geocodeResults.iterator(); while (locations.hasNext()) {

Address loc = locations.next();

double lat = loc.getLatitude();

double lon = loc.getLongitude();

// TODO: Do something with these coordinates

Each Address object returned contains information about the location. You can use the getLatitude() and getLongitude() methods of the Address class to access the location's coordinates.

You can also use the getFromLocationName() method to limit the returned address results to a certain range.

Reverse-Geocoding: Translating Coordinates into Addresses

You can use the Geocoder class's getFromLocation() method to translate raw latitude and longitude coordinates into address information. Again, you pass in the coordinates and the number of results to be returned.

0 0

Post a comment