Tuesday 6 January 2015

Find Location (Geolocation,Address)



Requirements  :


1. import library project. 
Eg: (E:\Android Setup\sdk\extras\google\google_play_services\libproject\google-play-services_lib).
2.Add reference with main project .
3.XML file to show the result.
4.Java class to access location.


public class MainActivity extends Activity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener

{

  LocationClient mLocationClient;
  private TextView addressLabel;
  private TextView locationLabel;
  private Button getLocationBtn;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

      locationLabel = (TextView) findViewById(R.id.locationLabel);
     addressLabel = (TextView) findViewById(R.id.addressLabel);
     getLocationBtn = (Button) findViewById(R.id.getLocation);

     getLocationBtn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
           displayCurrentLocation();
        }
     });
 
     // Create the LocationRequest object
     mLocationClient = new LocationClient(this, this, this);
  }
  @Override
  protected void onStart() {
     super.onStart();
     // Connect the client.
     mLocationClient.connect();
     locationLabel.setText("Got connected....");
  }
  @Override
  protected void onStop() {
     // Disconnect the client.
     mLocationClient.disconnect();
     super.onStop();
     locationLabel.setText("Got disconnected....");
  }
  @Override
  public void onConnected(Bundle dataBundle) {
     // Display the connection status
     Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
  }
  @Override
  public void onDisconnected() {
     // Display the connection status
     Toast.makeText(this, "Disconnected. Please re-connect.",
     Toast.LENGTH_SHORT).show();
  }
  @Override
  public void onConnectionFailed(ConnectionResult connectionResult) {
     // Display the error code on failure
     Toast.makeText(this, "Connection Failure : " +
     connectionResult.getErrorCode(),
     Toast.LENGTH_SHORT).show();
  }
  public void displayCurrentLocation() {
     // Get the current location's latitude & longitude
     Location currentLocation = mLocationClient.getLastLocation();
     String msg = "Current Location: " +
     Double.toString(currentLocation.getLatitude()) + "," +
     Double.toString(currentLocation.getLongitude());
   
     // Display the current location in the UI
     locationLabel.setText(msg);
   
     // To display the current address in the UI
     (new GetAddressTask(this)).execute(currentLocation);
  }
  /*
   * Following is a subclass of AsyncTask which has been used to get
   * address corresponding to the given latitude & longitude.
   */
  private class GetAddressTask extends AsyncTask<Location, Void, String>{
     Context mContext;
     public GetAddressTask(Context context) {
        super();
        mContext = context;
     }

     /*
      * When the task finishes, onPostExecute() displays the address.
      */
     @Override
     protected void onPostExecute(String address) {
        // Display the current address in the UI
        addressLabel.setText(address);
     }
     @Override
     protected String doInBackground(Location... params) {
        Geocoder geocoder =
        new Geocoder(mContext, Locale.getDefault());
        // Get the current location from the input parameter list
        Location loc = params[0];
        // Create a list to contain the result address
        List<Address> addresses = null;
        try {
           addresses = geocoder.getFromLocation(loc.getLatitude(),
           loc.getLongitude(), 1);
        } catch (IOException e1) {
           Log.e("LocationSampleActivity",
           "IO Exception in getFromLocation()");
           e1.printStackTrace();
           return ("IO Exception trying to get address");
        } catch (IllegalArgumentException e2) {
           // Error message to post in the log
           String errorString = "Illegal arguments " +
           Double.toString(loc.getLatitude()) +
           " , " +
           Double.toString(loc.getLongitude()) +
           " passed to address service";
           Log.e("LocationSampleActivity", errorString);
           e2.printStackTrace();
           return errorString;
        }
        // If the reverse geocode returned an address
        if (addresses != null && addresses.size() > 0) {
           // Get the first address
           Address address = addresses.get(0);
           /*
           * Format the first line of address (if available),
           * city, and country name.
           */
           String addressText = String.format(
           "%s, %s, %s",
           // If there's a street address, add it
           address.getMaxAddressLineIndex() > 0 ?
           address.getAddressLine(0) : "",
           // Locality is usually a city
           address.getLocality(),
           // The country of the address
           address.getCountryName());
           // Return the text
           return addressText;
        } else {
           return "No address found";
        }
     }
  }// AsyncT

        @Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}


XML LAYOUT

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/getLocation"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/get_location" />

    <TextView
        android:id="@+id/locationLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/addressLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>






No comments:

Post a Comment

How to do text writing animation?  In Android Development we do not have the option to use any other custom font in our default Tex...