package com.samples.location.reversegeocoding; 

import java.io.IOException;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class GeocoderActivity extends Activity {

	private LocationManager manager;
	private TextView text;
	private Geocoder geocoder;
	
	private LocationListener listener = new LocationListener() {
	
		public void onLocationChanged(Location argLocation) {
			printLocation(argLocation);
		}
	
		@Override
		public void onProviderDisabled(String arg0) {
			printLocation(null);
		}
	
		@Override
		public void onProviderEnabled(String arg0) {}
	
		@Override
		public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}
	};
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		text = (TextView)findViewById(R.id.text);	
		
		manager = (LocationManager)getSystemService(
				  Context.LOCATION_SERVICE);		
		manager.requestLocationUpdates(
				LocationManager.GPS_PROVIDER, 0, 0, listener);	
		Location loc = manager.getLastKnownLocation(
				LocationManager.GPS_PROVIDER);
		geocoder = new Geocoder(getApplicationContext());
		
		printLocation(loc);
		
	}
	
	private void printLocation(Location loc) {
		if (loc != null) {
			text.setText("Longitude:\t" + loc.getLongitude() + 	    
                "\nLatitude:\t" + loc.getLatitude());
	
		    try {
		    	List<Address> list = geocoder.getFromLocation(
		    			loc.getLatitude(), loc.getLongitude(), 20);
		    	for (int i = 0; i < list.size(); i++) {
		    		Address address = list.get(i);
		    	    text.append("\nAddress# " + i + 
		                    "\n\tLocality: " + address.getLocality() + 
		                    "\n\tCountryName: " + address.getCountryName() + 
		                    "-" + address.getCountryCode() + 
		                    "\n\tFeatureName: " + address.getFeatureName() + 
		                    "\n\tPostalCode: " + address.getPostalCode()
		                    );
		    	}
		    }
	        catch (IOException e) {
	        	Toast.makeText(getApplicationContext(), 
	        			e.toString(), Toast.LENGTH_LONG).show();
	        }
		}
		else {
			text.setText("Location unavailable");
		}
	    
	}
}