Posted By

chrisaiv on 09/24/11


Tagged

googlemaps android


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

bobgott
icecreamboyy


Android: Google Maps Marker


 / 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.

  1. /**********************************
  2. * Fired every time a user touches the map
  3. * MotionEvent.getAction() lets you determine
  4. * whether a user has lifted their finger
  5. **********************************/
  6. @Override
  7. public boolean onTouchEvent(MotionEvent e, MapView mapView) {
  8. if( e.getAction() == 1 ){
  9. //getProjection() returns screen-pixel coords to lat/lng coordinates
  10. //fromPixels converts the screen coordinates into a GeoPoint
  11. GeoPoint geoPoint = mapView.getProjection().fromPixels(
  12. (int) e.getX(),
  13. (int) e.getY() );
  14.  
  15. /*
  16. Toast.makeText( getActivity(),
  17. "Location: " + geoPoint.getLatitudeE6() / 1E6 + ", " +
  18. geoPoint.getLongitudeE6() / 1E6,
  19. Toast.LENGTH_SHORT).show();
  20. */
  21.  
  22. //Geocoder converts lat/lng into an address
  23. Geocoder geocoder = new Geocoder( getActivity(), Locale.getDefault() );
  24.  
  25. try{
  26. //getFromLocation() does the reverse Geo Location
  27. List<Address> addresses = geocoder.getFromLocation(
  28. geoPoint.getLatitudeE6() / 1E6,
  29. geoPoint.getLongitudeE6() / 1E6,
  30. 1 );
  31. //Capture the address in a String
  32. String addy = "";
  33. if( addresses.size() > 0 ){
  34. for (int i = 0; i < addresses.get(0).getMaxAddressLineIndex(); i++ ){
  35. addy += addresses.get(0).getAddressLine(i) + "\n";
  36. }
  37. }
  38. //Present the address using Toast
  39. Toast.makeText( getActivity(), addy, Toast.LENGTH_SHORT).show();
  40. }
  41. catch( IOException evt ){
  42. evt.printStackTrace();
  43. }
  44.  
  45. /**********************************
  46. * Find the Geo Coordinates based on the Name
  47. **********************************/
  48. try{
  49. List<Address> addresses = geocoder.getFromLocationName("kusc", 5);
  50. String addy = "";
  51. if( addresses.size() > 0 ){
  52. geoPoint = new GeoPoint(
  53. (int) (addresses.get(0).getLatitude() * 1E6),
  54. (int) (addresses.get(0).getLongitude() * 1E6));
  55. mapController.animateTo(geoPoint);
  56. mapView.invalidate();
  57. }
  58. //Present the address using Toast
  59. Toast.makeText( getActivity(), addy, Toast.LENGTH_SHORT).show();
  60. }catch( IOException evt){
  61. evt.printStackTrace();
  62. }
  63. }
  64. //onTouchEvent requires a boolean
  65. return false;
  66. }
  67. }

Report this snippet  

You need to login to post a comment.