Tuesday, April 19, 2016

Location Based Services Part-III (Get Updated Address also with Latitude & Longitude)

" Jai Saraswati Maa"

Please refer Part - II  of LBS


In this example you will also get Address of your new updated location.
In previous example i have added only one Button & one Text View in Layout.
One method which is on onClick of Button.
Changed from previous example are in Bold Italic. 
A. Changed Layout file is activity_main.xml file is as
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout 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: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="com.exam.ravi.locationbsex1.MainActivity">

    <TextView        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Ltitude and  Longitude... "

        android:id="@+id/textLocation"

        android:textSize="20dp"/>
    <Button        android:layout_width="wrap_content"

        android:layout_height="wrap_content"        android:text="GetAddress"

        android:onClick="findAddress"

        android:id="@+id/butAdd"

        android:layout_below="@+id/textLocation"

        android:layout_marginTop="10dp"/>

    <TextView        android:layout_width="wrap_content"

        android:layout_height="match_parent"

        android:id="@+id/textAdd"

        android:textSize="15sp"

        android:layout_below="@+id/butAdd"

        android:layout_marginTop="10dp"/>
</RelativeLayout>

B. Java code is as   MainActivity.java  

package com.exam.ravi.locationbsex1;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

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

public class MainActivity extends AppCompatActivity
         implements GoogleApiClient.OnConnectionFailedListener ,
                GoogleApiClient.ConnectionCallbacks ,LocationListener
{
    TextView dis,add;
    GoogleApiClient googleApiClient;
    int SERVICE_CODE = 99;
    Double lat,lng;
    LocationRequest locationRequest;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        add= (TextView) findViewById(R.id.textAdd);
        dis = (TextView) findViewById(R.id.textLocation);
        if(checkServices())
        {
            clientInitialization();
        }
    }
    private void clientInitialization() {
        googleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addOnConnectionFailedListener(this)
                .addConnectionCallbacks(this)
                .build();
    }
    @Override    protected void onStart() {
        super.onStart();
        googleApiClient.connect();
    }
@Overrideprotected void onStop() {
    super.onStop();
    if(googleApiClient.isConnected())
        googleApiClient.disconnect();
}

private boolean checkServices()
{
    int result= GooglePlayServicesUtil.isGooglePlayServicesAvailable
                                                      (getApplicationContext());
    if(result!= ConnectionResult.SUCCESS)
    {
        if(GooglePlayServicesUtil.isUserRecoverableError(result))
        {
            GooglePlayServicesUtil.getErrorDialog(result,this,SERVICE_CODE).show();
        }
        return false;
    }
    return true;
}

@Overridepublic void onConnected(Bundle bundle) {
locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(36000000);
        LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient,
                               locationRequest,this);

    }

    @Override    public void onConnectionSuspended(int i) {
     Toast.makeText(this, "Connection Susspended", Toast.LENGTH_SHORT).show();
    }

    @Override    public void onConnectionFailed(ConnectionResult connectionResult) {
        Toast.makeText(this, "Connection Failed", Toast.LENGTH_SHORT).show();

    }

    @Override    public void onLocationChanged(Location location) {
        lat = location.getLatitude();
        lng = location.getLongitude();
        if(location!=null)
            dis.setText("Latitude = " + lat + "\n Longitude = " + lng);
        else            dis.setText("Location Not Found");

    }
   public void findAddress(View view) {
       Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
       try {
           List<Address> addressList = geocoder.getFromLocation(lat,lng, 1);
           if (addressList != null && addressList.size() > 0) {
             String message ="";
               for(int i = 0 ; i<addressList.get(0).getMaxAddressLineIndex();i++)
               {
                   message = message + addressList.get(0).getAddressLine(i)+"\n";
               }
            
               add.setText("Address is \n"+ message);
           }
       } catch (IOException e) {
           e.printStackTrace();
       }
   }
}
  

No comments:

Post a Comment