Return to Snippet

Revision: 51436
at September 24, 2011 03:18 by chrisaiv


Initial Code
/**********************************
		 * 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
				Geocoder geocoder = new Geocoder( getActivity(), Locale.getDefault() );
				
				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
					String addy = "";
					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();
				}
				catch( IOException evt ){
					evt.printStackTrace();
				}
				
				/**********************************
				 * Find the Geo Coordinates based on the Name
				**********************************/
				try{
					List<Address> addresses = geocoder.getFromLocationName("kusc", 5);
					String addy = "";
					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();
				}catch( IOException evt){
					evt.printStackTrace();
				}
			}
			//onTouchEvent requires a boolean
			return false;
		}		
	}

Initial URL

                                

Initial Description
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.

Initial Title
Android: Google Maps Marker

Initial Tags
android

Initial Language
Java