package com.samples.location.geocoderwithmap;

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

import android.app.ListActivity;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class GeocoderActivity extends ListActivity {

	private Geocoder geocoder;
	private EditText editSearch;
    private Button bSearch;
    private List<Address> locations;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        editSearch = (EditText) findViewById(R.id.editSearch);
        bSearch = (Button) findViewById(R.id.bSearch);
        geocoder = new Geocoder(getApplicationContext());
        
        bSearch.setOnClickListener(bSearch_onClick);
    }

    public OnClickListener bSearch_onClick = new OnClickListener() {
    	@Override
        public void onClick(View v) {
            String placeName = editSearch.getText().toString();
            
            try {
                locations = geocoder.getFromLocationName(placeName, 10);
            	
                int size = locations.size();
            	
            	if (size == 0) {
            		editSearch.setText("");
            		editSearch.setHint("No results. Enter new place");
            	}
            	
                String[] list = new String[size];
                
                for (int i = 0; i < size; i++) {
                	Address loc = locations.get(i);
                	list[i] = "Latitude: " + loc.getLatitude() +
                		"\nLongitude" + loc.getLongitude();
                }
                
        		setListAdapter(new ArrayAdapter<String>(getApplicationContext(),
        				android.R.layout.simple_list_item_1, list));
            } 
            catch (IOException e) {
            	Toast.makeText(getApplicationContext(), 
            			e.toString(), Toast.LENGTH_LONG).show();
            }
        }
    };
    
    public void onListItemClick(
    		ListView parent, View v, int position, long id) {
  
    	Address loc = locations.get(position);
    	Uri uri = Uri.parse(String.format("geo:%f,%f", 
    			loc.getLatitude(), loc.getLongitude()));
        Intent geoMap = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(geoMap);
    }    
}
