How To Draggable Change Location and Search Location

How to Implement draggable map like Ola android, Update with change location..

Xml Files:-
activity_main1.xml

<?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" >

    <fragment
        android:id="@+id/map"
        android:name="com.parthivdraggingogmap.in.CustomMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <include
        android:id="@+id/marker_view_incl"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        layout="@layout/marker_view1" />

    <include
        android:id="@+id/location_display_incl"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_margin="2dp"
        layout="@layout/location_display_view1" />


</RelativeLayout>

splashsreeen.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#fff"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:background="#fff"
        android:gravity="center"
        android:orientation="vertical" >

        <ImageView
            android:id="@+id/image"
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:background="@drawable/location" />

        <TextView
            android:id="@+id/loc"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="LOCATION"
            android:textColor="#000"
            android:textSize="16dp"
            android:textStyle="bold" />
    </LinearLayout>


</LinearLayout>

marker_view1.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <ImageView
        android:id="@+id/marker_icon_view"
        android:layout_width="60dp"
        android:layout_height="40dp"
        android:layout_centerInParent="true"
        android:layout_marginTop="162dp"
        android:src="@drawable/piniconnew" />


</RelativeLayout>

location_display_view1.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="125dp"
    android:background="@drawable/searchlay"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="55dp"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="5dp"
        android:gravity="center_horizontal"
        android:orientation="vertical"
        android:paddingLeft="10dp"
        android:paddingRight="10dp" >

        <TextView
            android:id="@+id/text_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:gravity="center"
            android:text="Set Location"
            android:textSize="12sp"
            android:visibility="gone" />

        <TextView
            android:id="@+id/location_text_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/text_view"
            android:layout_centerHorizontal="true"
            android:text="Set Location"
            android:textColor="#fff"
            android:textSize="14sp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_gravity="center"
        android:gravity="center"
        android:orientation="horizontal" >

        <EditText
            android:id="@+id/et_location"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:layout_marginLeft="15dp"
            android:layout_weight="1"
            android:background="@drawable/edittextstrokeorange"
            android:hint="Search Address.."
            android:inputType="text"
            android:paddingLeft="5dp"
            android:textColor="#000"
            android:textColorHint="#000"
            android:textSize="12dp" />

        <LinearLayout
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_gravity="center"
            android:layout_marginRight="20dp"
            android:background="#d35400"
            android:gravity="center"
            android:orientation="horizontal" >

            <Button
                android:id="@+id/btn_find"
                android:layout_width="35dp"
                android:layout_height="35dp"
                android:background="@drawable/searchicon"
                android:textColor="#fff" />
        </LinearLayout>
    </LinearLayout>


</LinearLayout>

Java Files:-

SplashScreen.java

package com.parthivdraggingogmap.in;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
public class SplashScreen extends Activity {

    Handler handler;
    private GpsTracker gps;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);
overridePendingTransition(R.anim.move_left_in_activity, R.anim.move_left_out_activity);
        setContentView(R.layout.splashsreeen);
     
        ImageView image = (ImageView) findViewById(R.id.image);
        RotateAnimation anim = new RotateAnimation(0.0f, 180.0f, Animation.RESTART, 0.5f, Animation.RESTART, 0.5f);
        anim.setInterpolator(new LinearInterpolator());
        anim.setRepeatCount(Animation.RESTART);
        anim.setDuration(700);
        image.startAnimation(anim);

        handler=new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
           
            gps = new GpsTracker(SplashScreen.this);
                 gps.canGetLocation();
           
            if(gps.canGetLocation()) {

            Intent intent=new Intent(SplashScreen.this,MainActivity.class);
                     startActivity(intent);
                     finish();
                 
                 
                 }else {
               
                     gps.showSettingsAlert();
                 
                 }
             
            }
        },2000);

    }

}

MainActivity.java

package com.parthivdraggingogmap.in;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.Typeface;
import android.location.Address;
import android.location.Geocoder;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.Projection;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.parthivdraggingogmap.in.MapWrapperLayout.OnDragListener;

public class MainActivity extends Activity implements OnDragListener {

 
    private GoogleMap googleMap;
    private CustomMapFragment mCustomMapFragment;
    private View mMarkerParentView;
    private ImageView mMarkerImageView;
    private int imageParentWidth = -1;
    private int imageParentHeight = -1;
    private int imageHeight = -1;
    private int centerX = -1;
    private int centerY = -1;
    CameraUpdate cameraUpdate = null;
    private TextView mLocationTextView;
    double latitude;
    double longitude;
    private GpsTracker gps;
    private LatLng curentpoint;
    LatLng centerLatLng;
    String  address;
    Boolean isInternetPresent = true;
    Typeface tf;
String fontPath = "fonts/Smoolthan Bold.otf";
boolean isNetworkEnabled = false;
MarkerOptions markerOptions;
LatLng slatLng;
ConnectivityManager conMgr;
NetworkInfo netInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);
overridePendingTransition(R.anim.move_left_in_activity, R.anim.move_left_out_activity);
        setContentView(R.layout.activity_main1);
        tf= Typeface.createFromAsset(getAssets(),
fontPath);
        //Internet ConnectivityManager
        conMgr =  (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        netInfo = conMgr.getActiveNetworkInfo();

        // InitializeUI
        initializeUI();
     
        //current location click
        FloatingActionButton fabButton = new FloatingActionButton.Builder(MainActivity.this)
            .withDrawable(getResources().getDrawable(R.drawable.userlocation))
            .withButtonColor(Color.parseColor("#8a699c"))
            .withGravity(Gravity.BOTTOM | Gravity.RIGHT)
            .withMargins(0, 0, 14, 14).create();
          fabButton.setOnClickListener(new OnClickListener() {

           @Override
           public void onClick(View v) {
         
           if(netInfo == null){
                 
                Context context=getApplicationContext();
        LayoutInflater inflater=getLayoutInflater();
        View customToastroot =inflater.inflate(R.layout.fillallfield, null);
            TextView validate=(TextView)customToastroot.findViewById(R.id.textView1);    
        validate.setText("PLEASE SWITCH ON INTERNET...");
        validate.setTypeface(tf);
        validate.setTextColor(Color.WHITE);
        Toast customtoast=new Toast(context);
        customtoast.setView(customToastroot);
        customtoast.setGravity(Gravity.BOTTOM | Gravity.BOTTOM,0, 0);
        customtoast.setDuration(1000);
        customtoast.show();
       
                }else{
               
                gps = new GpsTracker(MainActivity.this);
                      gps.canGetLocation();
                      latitude = gps.getLatitude();
                  longitude = gps.getLongitude();
                  curentpoint = new LatLng(latitude, longitude);

                      CameraPosition camPos = new CameraPosition.Builder()
                      .target(new LatLng(latitude, longitude)) 
                      .zoom(18)     
                      .build();
                      CameraUpdate camUpd3 = CameraUpdateFactory.newCameraPosition(camPos);
                      googleMap.animateCamera(camUpd3);
                      googleMap.clear();
                      mLocationTextView.setText(address);
                }
           }
          });
     
        //searchbtn
        Button btn_find = (Button) findViewById(R.id.btn_find);
        OnClickListener findClickListener = new OnClickListener() {
            @Override
            public void onClick(View v) {
           
            EditText etLocation = (EditText) findViewById(R.id.et_location);
            etLocation.setTypeface(tf);
                 String location = etLocation.getText().toString();

            if(location.equals("")||location.equals(" ")){
           
            Context context=getApplicationContext();
        LayoutInflater inflater=getLayoutInflater();
        View customToastroot =inflater.inflate(R.layout.fillallfield, null);
            TextView validate=(TextView)customToastroot.findViewById(R.id.textView1);    
        validate.setText("TYPE SEARCHING ADDRESS...");
        validate.setTypeface(tf);
        validate.setTextColor(Color.WHITE);
        Toast customtoast=new Toast(context);
        customtoast.setView(customToastroot);
        customtoast.setGravity(Gravity.BOTTOM | Gravity.BOTTOM,0, 0);
        customtoast.setDuration(1000);
        customtoast.show();
           
            }else{
           
               if(location!=null && !location.equals("")){
                           new GeocoderTask().execute(location);
                           etLocation.setText("");
                           InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
                           imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
                       
                       }
            }
         
            }
        };
   btn_find.setOnClickListener(findClickListener);

    }

    private void initializeUI() {

        try {
            // Loading map
            initilizeMap();

        } catch (Exception e) {
            e.printStackTrace();
        }
        mLocationTextView = (TextView) findViewById(R.id.location_text_view);
        mLocationTextView.setTypeface(tf);
        mMarkerParentView = findViewById(R.id.marker_view_incl);
        mMarkerImageView = (ImageView) findViewById(R.id.marker_icon_view);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        DisplayMetrics displaymetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);

        imageParentWidth = mMarkerParentView.getWidth();
        imageParentHeight = mMarkerParentView.getHeight();
        imageHeight = mMarkerImageView.getHeight();

        centerX = imageParentWidth / 2;
        centerY = (imageParentHeight / 2) + (imageHeight / 2);
    }

    private void initilizeMap() {
        if (googleMap == null) {
            mCustomMapFragment = ((CustomMapFragment) getFragmentManager()
                    .findFragmentById(R.id.map));
            mCustomMapFragment.setOnDragListener(MainActivity.this);
            googleMap = mCustomMapFragment.getMap();
            // check if map is created successfully or not
            if (googleMap == null) {
                Toast.makeText(getApplicationContext(),
                        "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                        .show();
            }
        }
     
     
        gps = new GpsTracker(MainActivity.this);
        gps.canGetLocation();
        latitude = gps.getLatitude();
    longitude = gps.getLongitude();
    curentpoint = new LatLng(latitude, longitude);

        CameraPosition camPos = new CameraPosition.Builder()
        .target(new LatLng(latitude, longitude)) 
        .zoom(18)     
         .build();
        CameraUpdate camUpd3 = CameraUpdateFactory.newCameraPosition(camPos);
        googleMap.animateCamera(camUpd3);
        googleMap.clear();
   
      Geocoder geocoder;
      List<Address> addresses = null;
      geocoder = new Geocoder(MainActivity.this, Locale.getDefault());

      try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
   
      if (addresses != null && addresses.size() > 0) {


         address = addresses.get(0).getAddressLine(0);

          }

    }

    @Override
    protected void onResume() {
        super.onResume();
     
        mLocationTextView.setText(address);
   
        if(gps.canGetLocation()) {

     
         }else {
       
            gps.showSettingsAlert();
         
        }
     
        if(netInfo == null){
         
        Context context=getApplicationContext();
LayoutInflater inflater=getLayoutInflater();
View customToastroot =inflater.inflate(R.layout.fillallfield, null);
    TextView validate=(TextView)customToastroot.findViewById(R.id.textView1);    
validate.setText("PLEASE SWITCH ON INTERNET...");
validate.setTypeface(tf);
validate.setTextColor(Color.WHITE);
Toast customtoast=new Toast(context);
customtoast.setView(customToastroot);
customtoast.setGravity(Gravity.BOTTOM | Gravity.BOTTOM,0, 0);
customtoast.setDuration(1000);
customtoast.show();

        }else{
       
       
        }
   
    }
 
 
    //dragging location
       public void onDrag(MotionEvent motionEvent) {
        if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
            Projection projection = (googleMap != null && googleMap
                    .getProjection() != null) ? googleMap.getProjection()
                    : null;
            //
            if (projection != null) {
                centerLatLng = projection.fromScreenLocation(new Point(
                        centerX, centerY));
             
                updateLocation(centerLatLng);
            }
        }
    }

    private void updateLocation(LatLng centerLatLng) {
        if (centerLatLng != null) {
            Geocoder geocoder = new Geocoder(MainActivity.this,
                    Locale.getDefault());

            List<Address> addresses = new ArrayList<Address>();
            try {
                addresses = geocoder.getFromLocation(centerLatLng.latitude,
                        centerLatLng.longitude, 1);
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (addresses != null && addresses.size() > 0) {

                String addressIndex0 = (addresses.get(0).getAddressLine(0) != null) ? addresses
                        .get(0).getAddressLine(0) : null;
                String addressIndex1 = (addresses.get(0).getAddressLine(1) != null) ? addresses
                        .get(0).getAddressLine(1) : null;
                String addressIndex2 = (addresses.get(0).getAddressLine(2) != null) ? addresses
                        .get(0).getAddressLine(2) : null;
                String addressIndex3 = (addresses.get(0).getAddressLine(3) != null) ? addresses
                        .get(0).getAddressLine(3) : null;

                String completeAddress = addressIndex0;

                if (addressIndex2 != null) {
                    completeAddress += "," + addressIndex2;
                }
                if (addressIndex3 != null) {
                    completeAddress += "," + addressIndex3;
                }
                if (completeAddress != null) {
                    mLocationTextView.setText(completeAddress);
                }
            }
         
         
        }
    }
 
    //typing address get location
    private class GeocoderTask extends AsyncTask<String, Void, List<Address>>{

        @Override
        protected List<Address> doInBackground(String... locationName) {
            // Creating an instance of Geocoder class
            Geocoder geocoder = new Geocoder(getBaseContext());
            List<Address> addresses = null;

            try {
                // Getting a maximum of 3 Address that matches the input text
                addresses = geocoder.getFromLocationName(locationName[0], 3);
             
             
           
            } catch (IOException e) {
                e.printStackTrace();
            }
            return addresses;
        }

        @Override
        protected void onPostExecute(List<Address> addresses) {

            if(addresses==null || addresses.size()==0){
             
                Context context=getApplicationContext();
    LayoutInflater inflater=getLayoutInflater();
    View customToastroot =inflater.inflate(R.layout.fillallfield, null);
        TextView validate=(TextView)customToastroot.findViewById(R.id.textView1);    
    validate.setText("No Location found...");
    validate.setTypeface(tf);
    validate.setTextColor(Color.WHITE);
    Toast customtoast=new Toast(context);
    customtoast.setView(customToastroot);
    customtoast.setGravity(Gravity.BOTTOM | Gravity.BOTTOM,0, 0);
    customtoast.setDuration(1000);
    customtoast.show();
                googleMap.clear();
             
            }else{

            googleMap.clear();
         

            // Adding Markers on Google Map for each matching address
            for(int i=0;i<addresses.size();i++){

                Address saddress = (Address) addresses.get(i);

                // Creating an instance of GeoPoint, to display in Google Map
                slatLng = new LatLng(saddress.getLatitude(), saddress.getLongitude());

                        String addressText = String.format("%s, %s",
                saddress.getMaxAddressLineIndex() > 0 ? saddress.getAddressLine(0) : "",
                saddress.getCountryName());

                markerOptions = new MarkerOptions();
                markerOptions.position(slatLng);
                markerOptions.title(addressText);
           
                // Locate the first location
                if(i==0)
               
                googleMap.moveCamera(CameraUpdateFactory.newLatLng(slatLng));
                    googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
                 
                    mLocationTextView.setText("");
                    Geocoder geocoder;
                    List<Address> saddresses = null;
                    geocoder = new Geocoder(MainActivity.this, Locale.getDefault());

                    try {
              saddresses = geocoder.getFromLocation(saddress.getLatitude(), saddress.getLongitude(), 1);
              } catch (IOException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
              }
                 
                    if (saddresses != null && saddresses.size() > 0) {


                   String searchaddress = saddresses.get(0).getAddressLine(0);
                 
                   mLocationTextView.setText(searchaddress);
             
                     
                                                   
                    }
            }
            }
        }
    }

}

MapWrapperLayout.java

package com.parthivdraggingogmap.in;

import android.content.Context;
import android.view.MotionEvent;
import android.widget.FrameLayout;

public class MapWrapperLayout extends FrameLayout {

    public interface OnDragListener {
        public void onDrag(MotionEvent motionEvent);
    }

    private OnDragListener mOnDragListener;

    public MapWrapperLayout(Context context) {
        super(context);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (mOnDragListener != null) {
            mOnDragListener.onDrag(ev);
        }
        return super.dispatchTouchEvent(ev);
    }

    public void setOnDragListener(OnDragListener mOnDragListener) {
        this.mOnDragListener = mOnDragListener;
    }

}

CustomMapFragment.java

package com.parthivdraggingogmap.in;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.android.gms.maps.MapFragment;

public class CustomMapFragment extends MapFragment {

    private View mOriginalView;
    private MapWrapperLayout mMapWrapperLayout;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mOriginalView = super.onCreateView(inflater, container, savedInstanceState);

        mMapWrapperLayout = new MapWrapperLayout(getActivity());
        mMapWrapperLayout.addView(mOriginalView);

        return mMapWrapperLayout;
}

    @Override
    public View getView() {
        return mOriginalView;
    }

    public void setOnDragListener(MapWrapperLayout.OnDragListener onDragListener) {
        mMapWrapperLayout.setOnDragListener(onDragListener);
    }

}

GpsTracker.java

package com.parthivdraggingogmap.in;

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 GpsTracker 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 canGetLocation = 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 GpsTracker(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.canGetLocation = 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 latitude/longitude 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(GpsTracker.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/Wi-Fi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }


    /**
     * Function to show settings alert dialog.
     * On pressing the Settings button it will launch 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 the 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 the 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;
    }

 }

Screenshots:-

                                                          Draggable Location



Search Location








No comments:

Post a Comment

back to top