package com.example.Maps013;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;

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

import com.google.android.gms.identity.intents.Address;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import com.google.android.gms.vision.barcode.Barcode.GeoPoint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.content.Context;
import android.location.Geocoder;


public class Geocoder_find_address02 extends FragmentActivity 
{
	GoogleMap map;
	Button btn_find;
	
	final Double lat = 0.0; 
	final Double lng = 0.0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.geocoder02_layout);
		 		
		// Getting reference to SupportMapFragment of the activity_main
		SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
		
		// Getting Map for the SupportMapFragment
		map = fm.getMap();
		map.clear();
		
		// Enable MyLocation Button in the Map
		map.setMyLocationEnabled(true);
		map.setIndoorEnabled(true);
		map.getUiSettings().setZoomControlsEnabled(true);
		map.getUiSettings().setMyLocationButtonEnabled(true);
		map.getUiSettings().setCompassEnabled(true);
		map.getUiSettings().setAllGesturesEnabled(true);
		
		// zoom sur le centre de la France 
		map.moveCamera( CameraUpdateFactory.newLatLngZoom(new LatLng(46.4606 , 2.2557) , 5.5f) );
		
		
		btn_find = (Button) findViewById(R.id.btn_find);
	    btn_find.setOnClickListener(new View.OnClickListener() 
	    {
		            @Override
		            public void onClick(View arg0) 
		            {
		            		EditText et_place = (EditText) findViewById(R.id.et_place);
		            		String place = et_place.getText().toString();
		
		            		GeocodingLocation2 locationAddress = new GeocodingLocation2();
		            		locationAddress.getAddressFromLocation(place, getApplicationContext(), new GeocoderHandler2());
		            }
	    });
		
	}
	
	 private class GeocoderHandler2 extends Handler 
	 {
		 @Override
	        public void handleMessage(Message message) 
	        {
		            String locationAddress;
		           
		            switch (message.what)
		            {
		                case 1:
		                    Bundle bundle = message.getData();
		                    locationAddress = bundle.getString("address");
		                    break;
		                default:
		                    locationAddress = null;
		            }
		            
		            
		            
		            //latLongTV.setText(locationAddress);
		            String aaa = locationAddress;
		            
		            String error = "Unable to get Latitude and Longitude for this address location";
		            
		            boolean retval = locationAddress.contains(error);
		            
		            if(retval == false)
		            {	
		            	String[] morceaux = locationAddress.split(" ");
		            
		            	double lat = Double.parseDouble(morceaux[0]);
		            	double lng = Double.parseDouble(morceaux[1]);
		            
		            	map.moveCamera( CameraUpdateFactory.newLatLngZoom(new LatLng(lat , lng) , 10f) );
		            
		            	LatLng point = new LatLng(lat, lng);
		            
		            	map.addMarker(new MarkerOptions().position(point).title(point.toString()));
		            
		            	Toast.makeText(getBaseContext(), locationAddress , Toast.LENGTH_LONG).show();
		            } 	
		           else	
		           {
		        	   Toast.makeText(getBaseContext(), "Unable to find this address location !." , Toast.LENGTH_LONG).show();
		           }
		            
	        }
	 }
}	

class GeocodingLocation2 
{

    private static final String TAG = "GeocodingLocation";
    
	static List<android.location.Address> Totoaddress;


    public static void getAddressFromLocation(final String locationAddress, final Context context, final Handler handler) 
    {
        Thread thread = new Thread()
        {
		            @Override
		            public void run()
		            {
		            	
		            		Geocoder geocoder = new Geocoder(context, Locale.getDefault());
		            		String result = null;
			                
		            		try 
			                {
			                    
			                    Totoaddress = geocoder.getFromLocationName(locationAddress,5);
			                    
			                    if (Totoaddress != null && Totoaddress.size() > 0) 
			                    {
			                    	
			                    	android.location.Address location= Totoaddress.get(0);
			                        StringBuilder sb = new StringBuilder();
			                        //sb.append(location.getLatitude()).append("\n");
			                        //sb.append(location.getLongitude()).append("\n");
			                      sb.append(location.getLatitude());
			                      sb.append(" ");
			                      sb.append(location.getLongitude());
			                        result = sb.toString();
			                    }
			                }
			                
			                catch (IOException e) 
			                {
			                    Log.e(TAG, "Unable to connect to Geocoder", e);
			                } 
			                
			                finally 
			                {
				                    Message message = Message.obtain();
				                    message.setTarget(handler);
				                    if (result != null) 
				                    {
				                        message.what = 1;
				                        Bundle bundle = new Bundle();
				                       // result = "Address: " + locationAddress +
				                        //        "\n\nLatitude and Longitude :\n" + result;
				                        
				                        result = result;
				                        
				                        bundle.putString("address", result);
				                       message.setData(bundle);
				                    } 
				                    
				                    else 
				                    {
				                        message.what = 1;
				                        Bundle bundle = new Bundle();
				                        result = "Address: " + locationAddress +
				                                "\n Unable to get Latitude and Longitude for this address location.";
				                        bundle.putString("address", result);
				                        message.setData(bundle);
				                    }
				                    
				                    message.sendToTarget();
			                }
		            }
        };
        thread.start();
    }
}




