Monday 1 July 2013

Get Lat and Long through either GPS or Network

latitude and longitude android app





You can Find location either GPS_PROVIDER or NETWORK_PROVIDER 


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







package com.itdeveloper.khurram;

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_UPDATES, this);
                                  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_UPDATES, this);
                                         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 = new AlertDialog.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;
       }

}




and here is Your Favorite MainActivity :)


package com.itdeveloper.khurram;

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();
                           }

                     }
              });

       }
}




and your 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>


then you must have to add 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>


You can download complete example From Here 


Download 


I hope its usefull you, Happy Coddddding :)





No comments:

Post a Comment