/ Published in: Java
This is part of a much larger class but I wanted to give enough context to explain the value of GeoCoder. GeoCoder has two methods called getFromLocation() and getFromLocationName() that allow you to capture an address or coordinates.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
/********************************** * Fired every time a user touches the map * MotionEvent.getAction() lets you determine * whether a user has lifted their finger **********************************/ @Override public boolean onTouchEvent(MotionEvent e, MapView mapView) { if( e.getAction() == 1 ){ //getProjection() returns screen-pixel coords to lat/lng coordinates //fromPixels converts the screen coordinates into a GeoPoint GeoPoint geoPoint = mapView.getProjection().fromPixels( (int) e.getX(), (int) e.getY() ); /* Toast.makeText( getActivity(), "Location: " + geoPoint.getLatitudeE6() / 1E6 + ", " + geoPoint.getLongitudeE6() / 1E6, Toast.LENGTH_SHORT).show(); */ //Geocoder converts lat/lng into an address try{ //getFromLocation() does the reverse Geo Location List<Address> addresses = geocoder.getFromLocation( geoPoint.getLatitudeE6() / 1E6, geoPoint.getLongitudeE6() / 1E6, 1 ); //Capture the address in a String if( addresses.size() > 0 ){ for (int i = 0; i < addresses.get(0).getMaxAddressLineIndex(); i++ ){ addy += addresses.get(0).getAddressLine(i) + "\n"; } } //Present the address using Toast Toast.makeText( getActivity(), addy, Toast.LENGTH_SHORT).show(); } evt.printStackTrace(); } /********************************** * Find the Geo Coordinates based on the Name **********************************/ try{ List<Address> addresses = geocoder.getFromLocationName("kusc", 5); if( addresses.size() > 0 ){ geoPoint = new GeoPoint( (int) (addresses.get(0).getLatitude() * 1E6), (int) (addresses.get(0).getLongitude() * 1E6)); mapController.animateTo(geoPoint); mapView.invalidate(); } //Present the address using Toast Toast.makeText( getActivity(), addy, Toast.LENGTH_SHORT).show(); evt.printStackTrace(); } } //onTouchEvent requires a boolean return false; } }