Listing 1111 A short Geocoder example

@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState) ; this.setContentView(R.layout.main);

this.input = (EditText) this.findViewById(; this.output = (TextView) this.findViewById(; this.button = (Button) this.findViewById( geocode_button); this.isAddress = (CheckBox) this.findViewById(;

this .button.setOnClickListener(new OnClickListener() { public void onClick(final View v) { output.setText(performGeocode(

input.getText().toString(), isAddress.isChecked()));

private String performGeocode(String in, boolean isAddr) { String result = "Unable to Geocode - " + in;

if (this.input ! = null) { O Instantiate Geocoder

Geocoder geocoder = new Geocoder (this) ; <1-' with Context if (isAddr) { try {

List<Address> addresses = © Get Address from geocoder.getFromLocationName (in, 1); <-' location name if (addresses != null) {

result = addresses.get(0).toString();

Log.e("GeocodExample", "Error", e) ;

String [] coords = in. split (",") ; if ((coords ! = null) && (coords.length == 2)) { List<Address> addresses = geocoder.getFromLocation( Double.parseDouhle (coords[0]) Double.parseDouhle(coords[1]) 1) ;

result = addresses.get(0).toString();

Log.e("GeocodExample", "Error", e) ;

Get Address from coordinates

return result;

Input (description of place/address or coordinate pair [123,45]):

In Android terms, you create a Geocoder by constructing it with the Context of your application O- You then use a Geocoder to covert either String instances that represent place names into Address objects with the get-FromLocationName method Q or latitude and longitude coordinates into Address objects with the getFromLocation method Q

Figure 11.8 is an example of our simplified GeocoderExample in use. In this case we are converting a String representing a place (Wrigley Field in Chicago) into an Address object that contains latitude and longitude coordinates.

The GeocoderExample application shows how useful the Geocoder is. For instance, if you have data that includes address string portions, or even just place descriptions, it's easy to covert that into latitude and longitude numbers for use with GeoPoint and Overlay, and so on.

Geocoding rounds out our look at the powerful location- and mapping-related components of the Android platform.

Input (description of place/address or coordinate pair [123,45]):

Wrigley Field, Chicagcj

Input is an Address or Pia« Description?


Field".! : "Chicago, IL*,2:"USA")rfeature=wrlgley

Fleldnddmln^lLfSub-admln^nulljlocallly^Chlcago, thoroughfare=null,postalCode=nu]l,counti7Code

=US.courit ryMame=U SA rhasLal ltude=tr ue/atl t Lid e=41.9482,hasLonj>ltude=true,longltijde=-87.65

57, phone-null.url-null.extf as-null]

Figure 11.8 A Geocoder usage example that demonstrates turning an Address String into an Address object that provides latitude and longitude coordinates

0 0

Post a comment