8 Oct 2012

Get current location | latitude and longitude in Android.

EXAMPLE : 1 


Step 1: Add below dependency into your project.
implementation 'com.google.android.gms:play-services-location:18.0.0'
Step 2: Implement coding for the runtime permission for the location.
Step 3: Add below permission in to the android manifest.
<uses-permission android:name = "android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name = "android.permission.ACCESS_NETWORK_STATE" />

 Step 4: Below is the code spinet to get current location from the mobile.

class LocationHelper
{
    private val TAG = this.javaClass.name
    private var cancellationTokenSource = CancellationTokenSource()    

    fun getLocation(activity: Activity)
    {
        val fusedLocationClient = LocationServices.getFusedLocationProviderClient(activity)
        if (ActivityCompat.checkSelfPermission(activity,
     Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(activity,
     Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
        {
            return
        }

        val currentLocationTask: Task<Location> =  fusedLocationClient.getCurrentLocation(
PRIORITY_HIGH_ACCURACY, cancellationTokenSource.token)

        currentLocationTask.addOnCompleteListener { task: Task<Location> ->
            if (task.isSuccessful && task.result != null)
            {
                val result: Location = task.result                
                Log.i(TAG,"getLocation : (success): ${result.latitude}, ${result.longitude}")
            }
            else
            {
                val exception = task.exception
                Log.i(TAG,"getLocation : "+exception?.message!!)
            }
        }
    }
}

 Step 5: Call method.

LocationHelper.getCurrentLocation(activity)

EXAMPLE : 2


Here is one example which try to find location using GPS , if your GPS not available then try to use network for find location. GPS or Network not enable then it will ask user to Enable Gps/network Setting.





MyLocation.java

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;

public class MyLocation extends Service implements LocationListener {

       private final Context mContext;

       // flag for GPS status
       boolean isGPSEnabled = false;

       // flag for network status
       boolean isNetworkEnabled = false;

       // flag for GPS status
       boolean isLocationAvailable = false;

       Location location// location
       double latitude// latitude
       double longitude// longitude

       // The minimum distance to change Updates in meters
       private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

       // The minimum time between updates in milliseconds
       private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

       // Declaring a Location Manager
       protected LocationManager locationManager;

       public MyLocation(Context context) {
              this.mContext = context;
              getLocation();
       }

       public Location getLocation() {
              try {
                     locationManager = (LocationManager) mContext
                                  .getSystemService(LOCATION_SERVICE);

                     // getting GPS status
                     isGPSEnabled = locationManager
                                 .isProviderEnabled(LocationManager.GPS_PROVIDER);

                     // getting network status
                     isNetworkEnabled = locationManager
                                 .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

                     if (!isGPSEnabled && !isNetworkEnabled) {
                           // no network provider is enabled
                     } else {
                           this.isLocationAvailable = true;
                           if (isNetworkEnabled) {
                                  locationManager.requestLocationUpdates(
                                               LocationManager.NETWORK_PROVIDER,
                                                MIN_TIME_BW_UPDATES,
                                               MIN_DISTANCE_CHANGE_FOR_UPDATESthis);
                                  Log.d("Network""Network");
                                  if (locationManager != null) {
                                         location = locationManager
                                                      .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                                         if (location != null) {
                                                latitude =location.getLatitude();
                                                longitude =location.getLongitude();
                                         }
                                  }
                           }
                           // if GPS Enabled get lat/long using GPS Services
                           if (isGPSEnabled) {
                                  if (location == null) {
                                        locationManager.requestLocationUpdates(
                                                      LocationManager.GPS_PROVIDER,
                                                       MIN_TIME_BW_UPDATES,
                                                      MIN_DISTANCE_CHANGE_FOR_UPDATESthis);
                                         Log.d("GPS Enabled""GPS Enabled");
                                         if (locationManager != null) {
                                                location = locationManager
                                                             .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                                                if (location != null) {
                                                       latitude =location.getLatitude();
                                                       longitude =location.getLongitude();
                                                }
                                         }
                                  }
                           }
                     }

              } catch (Exception e) {
                     e.printStackTrace();
              }

              return location;
       }

       /**
        * Stop using GPS listener Calling this function will stop using GPS in your
        * app
        * */
       public void stopUsingGPS() {
              if (locationManager != null) {
                     locationManager.removeUpdates(MyLocation.this);
              }
       }

       /**
        * Function to get latitude
        * */
       public double getLatitude() {
              if (location != null) {
                     latitude = location.getLatitude();
              }

              // return latitude
              return latitude;
       }

       /**
        * Function to get longitude
        * */
       public double getLongitude() {
              if (location != null) {
                     longitude = location.getLongitude();
              }

              // return longitude
              return longitude;
       }

       /**
        * Function to check GPS/wifi enabled
        *
        * @return boolean
        * */
       public boolean isLocationAvailable() {
              return this.isLocationAvailable;
       }

       /**
        * Function to show settings alert dialog On pressing Settings button will
        * lauch Settings Options
        * */
       public void showSettingsAlert() {
              AlertDialog.Builder alertDialog = newAlertDialog.Builder(mContext);

              // Setting Dialog Title
              alertDialog.setTitle("GPS is settings");

              // Setting Dialog Message
              alertDialog
                           .setMessage("GPS is not enabled. Do you want to go to settings menu?");

              // On pressing Settings button
              alertDialog.setPositiveButton("Settings",
                           new DialogInterface.OnClickListener() {
                                  public void onClick(DialogInterface dialog, int which) {
                                         Intent intent = new Intent(
                                                      Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                         mContext.startActivity(intent);
                                  }
                           });

              // on pressing cancel button
              alertDialog.setNegativeButton("Cancel",
                           new DialogInterface.OnClickListener() {
                                  public void onClick(DialogInterface dialog, int which) {
                                         dialog.cancel();
                                  }
                           });

              // Showing Alert Message
              alertDialog.show();
       }

       @Override
       public void onLocationChanged(Location location) {
       }

       @Override
       public void onProviderDisabled(String provider) {
       }

       @Override
       public void onProviderEnabled(String provider) {
       }

       @Override
       public void onStatusChanged(String provider, int status, Bundle extras) {
       }

       @Override
       public IBinder onBind(Intent arg0) {
              return null;
       }

}


MainActivity.java

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
       // MyLocation class
       MyLocation myLocation;

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

              Button mylocationBtn = (Button) findViewById(R.id.MyLatLongBtn);
              mylocationBtn.setOnClickListener(new OnClickListener() {

                     @Override
                     public void onClick(View v) {
                           // TODO Auto-generated method stub

                           TextView latitudeTv = (TextView) findViewById(R.id.latitudeTV);
                           TextView longitudeTv = (TextView) findViewById(R.id.longitudeTv);

                           // create class object
                           myLocation = new MyLocation(MainActivity.this);

                           // check if GPS enabled
                           if (myLocation.isLocationAvailable()) {

                                  Double latitude =myLocation.getLatitude();
                                  Double longitude =myLocation.getLongitude();

                                  latitudeTv.setText(latitude.toString());
                                 longitudeTv.setText(longitude.toString());
                           } else {
                                  // can't get location
                                  // GPS or Network is not enabled
                                  // Ask user to enable GPS/network in settings
                                  myLocation.showSettingsAlert();
                           }

                     }
              });

       }
}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/bgimage" >

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="21dp"
        android:text="Longitude"
        android:textColor="@android:color/white"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/latitudeTV"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textView1"
        android:layout_alignBottom="@+id/textView1"
        android:layout_alignParentRight="true"
        android:text="00"
        android:textColor="@android:color/white"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/longitudeTv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textView2"
        android:layout_alignBottom="@+id/textView2"
        android:layout_alignLeft="@+id/latitudeTV"
        android:text="00"
        android:textColor="@android:color/white"
        android:textSize="18sp" />

    <Button
        android:id="@+id/MyLatLongBtn"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:text="MyLatLong"
        android:textColor="@android:color/white" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_alignRight="@+id/textView2"
        android:layout_marginTop="50dp"
        android:text="Latitude"
        android:textColor="@android:color/white"
        android:textSize="18sp" />

</RelativeLayout>

Permition in manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.itdeveloper.khurram"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

    <uses-permission android:name="android.permission.INTERNET" />


    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.itdeveloper.khurram.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

</manifest>


I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.

Thank you :)

No comments:

Post a Comment