androidgoogle-api-clientlocationlistenerandroid-geofence

Check if geo location(lat,lon) inside a circular geo fence


I have a saved geo location(latitude,longitude).when a user presses a action button in app, the current location is recorded.

I want to check if the current latitude,longitude(which I have) falls in a circular geofence (who's center geo point I have ).

I don't want to create a geofence on Google map. I just want to check if a geolocation falls in a geofence.

The code I use to get current geolocation when the accuracy is less than 20 :

public class CreatePlaceActivity extends Fragment implements
        OnClickListener,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener, LocationListener {
    private Button cancelBtn, submitBtn;

    public boolean geoLocationCheck = false;
    private String TAG = "CreatePlaceActivity";

    public CreatePlaceActivity() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.create_place_screen,
                container, false);
        submitBtn = (Button) rootView.findViewById(R.id.submit_btn_id);
        submitBtn.setTypeface(typeface);
        submitBtn.setOnClickListener(this);
        cancelBtn = (Button) rootView.findViewById(R.id.cancel_btn_id);
        cancelBtn.setOnClickListener(this);

        setlocationClient();
        return rootView;
    }

    private void setlocationClient() {
        int resp = GooglePlayServicesUtil
                .isGooglePlayServicesAvailable(getActivity());
        if (resp == ConnectionResult.SUCCESS) {

            locationclient = new GoogleApiClient.Builder(getActivity())
                    .addApi(LocationServices.API).addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .build();
            locationclient.connect();
        } else {
            GooglePalyErrorDialogIsShowing = true;

            Toast.makeText(getActivity(),// CreatePlaceActivity.this,
                    "Google Play Service Error " + resp, Toast.LENGTH_LONG)
                    .show();

            if (alert == null) {
                onLocationChangedbuilder = new AlertDialog.Builder(
                        getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
            } else if (alert.isShowing()) {
                alert.dismiss();

                onLocationChangedbuilder = new AlertDialog.Builder(
                        getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);

            }
            onLocationChangedbuilder
                    .setTitle("Alert!")
                    .setMessage("Google Play Service Error " + resp)
                    .setPositiveButton("OK",
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog,
                                        int which) {

                                    locationLockDialogIsShowing = false;
                                    GooglePalyErrorDialogIsShowing = false;

                                    ((MenuActivity) getActivity())
                                            .removeFragment(CreatePlaceActivity.this);

                                }
                            });

            alert = onLocationChangedbuilder.create();
            alert.setCancelable(false);
            try {
                alert.show();
            } catch (Exception e) {

            }

        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.submit_btn_id:
            Log.i(TAG, "lat=" + currentGeoLocation.getLatitude() + "lon="
                    + currentGeoLocation.getLongitude() + "acc="
                    + currentGeoLocation.getAccuracy() + "alt="
                    + currentGeoLocation.getAltitude());
            validatePlace();

            break;
        case R.id.cancel_btn_id:
            // finish();
            ((MenuActivity) getActivity())
                    .removeFragment(CreatePlaceActivity.this);

            break;

        default:
            break;
        }
    }


    @Override
    public void onLocationChanged(Location location) {

        float accuracy = 50;

        // DateTime dt1 = new DateTime();
        // DateTimeFormatter fmt1 = ISODateTimeFormat.dateTime();

        Time time = new Time();
        time.setToNow();
        String strdt = String.valueOf(time.toMillis(false));

        if (location != null) {

            accuracy = location.getAccuracy();

            locationLockDialogIsShowing = true;

            if (globalAccuracy - location.getAccuracy() >= 20
                    || globalAccuracy - location.getAccuracy() >= -20) {

                globalAccuracy = location.getAccuracy();
            }
        }



        if (alert == null) {
            onLocationChangedbuilder = new AlertDialog.Builder(getActivity(),
                    AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
        } else if (alert.isShowing()) {
            alert.dismiss();

            onLocationChangedbuilder = new AlertDialog.Builder(getActivity(),
                    AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);

        }
        final float accr = accuracy;
        onLocationChangedbuilder
                .setTitle("Alert!")
                .setMessage(
                        "Getting the best possible location..Please wait.\nCurrent Accuracy is "
                                + accuracy)
                .setPositiveButton("Cancel",
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                // TODO Auto-generated method stub

                                locationLockDialogIsShowing = false;

                                if (locationclient != null) {

                                    locationclient.disconnect();
                                }

                                Time time = new Time();
                                time.setToNow();
                                String strdt = String.valueOf(time
                                        .toMillis(false));



                                if (alert == null) {

                                } else if (alert.isShowing()) {
                                    alert.dismiss();
                                }
                                if (locationLockAlert == null) {

                                } else if (locationLockAlert.isShowing()) {
                                    locationLockAlert.dismiss();
                                }
                                // setResult(RESULT_OK);
                                // finish();
                                ((MenuActivity) getActivity())
                                        .removeFragment(CreatePlaceActivity.this);
                            }
                        });

        alert = onLocationChangedbuilder.create();
        alert.setCancelable(false);
        try {
            alert.show();
        } catch (Exception e) {

        }
        if (location.getAccuracy() <= 16) {

            DateTime dt = new DateTime();
            DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
            String str1 = fmt.print(dt);

            locationLockDialogIsShowing = false;

            Time timeNow = new Time();
            timeNow.setToNow();

            String str = String.valueOf(timeNow.toMillis(false));

            // locationLockTimestamp = str1;
            // TODO
            currentGeoLocation = location;

            if (locationclient != null) {
                if (locationclient.isConnected()) {

                    LocationServices.FusedLocationApi.removeLocationUpdates(
                            locationclient, this);
                    locationclient.disconnect();
                }
            }

            if (alert.isShowing()) {
                alert.dismiss();
            }
            if (locationLockAlert != null) {

                if (locationLockAlert.isShowing()) {
                    locationLockAlert.dismiss();
                }
            }
            showDialog("Alert!",
                    "GPS Location locked.. You can now continue to create place");

        }


    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onConnected(Bundle connectionHint) {
        // TODO Auto-generated method stub

        final float accuracy = 250;

        if (locationclient != null && locationclient.isConnected()) {

            if (geoLocationCheck == false) {

                locationrequest = LocationRequest.create();
                locationrequest
                        .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

                locationrequest.setInterval(100);
                // locationclient.requestLocationUpdates(locationrequest, this);
                LocationServices.FusedLocationApi.requestLocationUpdates(
                        locationclient, locationrequest, this); 

                locationLockDialogIsShowing = true;

                if (alert == null) {
                    onLocationChangedbuilder = new AlertDialog.Builder(
                            getActivity(),
                            AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
                } else if (alert.isShowing()) {
                    alert.dismiss();

                    onLocationChangedbuilder = new AlertDialog.Builder(
                            getActivity(),
                            AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);

                }
                onLocationChangedbuilder
                        .setTitle("Alert!")
                        .setMessage(
                                "Getting the best possible location..Please wait.\nCurrent Accuracy is "
                                        + accuracy)
                        .setPositiveButton("Cancel",
                                new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog,
                                            int which) {
                                        // TODO Auto-generated method stub

                                        locationLockDialogIsShowing = false;

                                        if (locationclient != null) {
                                            locationclient.disconnect();
                                        }

                                        Time time = new Time();
                                        time.setToNow();
                                        String strdt = String.valueOf(time
                                                .toMillis(false));


                                        if (alert == null) {
                                        } else if (alert.isShowing()) {
                                            alert.dismiss();
                                        }
                                        if (locationLockAlert == null) {

                                        } else if (locationLockAlert
                                                .isShowing()) {
                                            locationLockAlert.dismiss();
                                        }
                                        // setResult(RESULT_OK);
                                        // finish();
                                        ((MenuActivity) getActivity())
                                                .removeFragment(CreatePlaceActivity.this);
                                    }
                                });

                alert = onLocationChangedbuilder.create();
                alert.setCancelable(false);
                try {
                    alert.show();
                } catch (Exception e) {

                }

            }
        }

    }


    @Override
    public void onConnectionSuspended(int arg0) {
        Log.i("fused", "loc client onConnectionSuspended");
    }

    public Dialog showDialog(String title, String msg) {

        locationLockAlert = new AlertDialog.Builder(getActivity(),
                AlertDialog.THEME_DEVICE_DEFAULT_LIGHT).create();
        locationLockAlert.setTitle(title);
        locationLockAlert.setMessage(msg);
        locationLockAlert.setButton("OK",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        locationLockAlert.dismiss();

                    }
                });
        try {
            locationLockAlert.show();
        } catch (Exception e) {

        }
        return locationLockAlert;

    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        // TODO Auto-generated method stub

    }
}

Link I have referred is Android Geofencing (Polygon)

Thanks!


Solution

  • If you know the radius of the circle and its center point, you know if any other point is inside the circle by using the following formula:

    enter image description here which is the distance formula.

    Also, if both points are Location objects. you can use Location.distanceTo