ThatGuyYouSaw
ThatGuyYouSaw

Reputation: 36

Set a random Geofence location 2km away based off a users current location

I'm using using Google-Play-Services-Location to track the location of the user.

When the user clicks a button it will start a challenge and the user would need to go to a random location within 2km of their current longitude and latitude (computed randomly by the application logic).

Geofencing that location to determine if they arrived.

Is it possible to set a geofence in this way, and how would I go about attempting it?

Upvotes: 0

Views: 516

Answers (2)

Hayden Passmore
Hayden Passmore

Reputation: 1155

First

1 degree of longitude = 111km

1 degree of latitude = 111km

So 2km for both longitude and latitude are equal to .018 degrees

Second

You could get the users location longitude and latitude then add a random longitude and latitude that equal to .018.

For example: add longitude of .007 and a latitude of .011 (which equals .018) to the users location. This will give you a location 2km away from your user.

If you want the closest part of the fence to be 2km away just double the degree total to .036 and make your fence radius 2km.

Lastly

To get a geofence you could do something similar to the above 4 times that will give you a square fence. Or once to give you a radius. This distance is upto how big you want your fence to be

Upvotes: 1

FnR
FnR

Reputation: 75

I am not sure if this is what exactly looking for or not. I used this code for creating randomly marker at a given radius of given position.

private void getLocation() {


    double x0 = 38.423734;
    double y0 = 27.142826000000014;
    int radius = 50000;

    for (int i = 0; i < 50; i++) {
        Random random = new Random();

        // Convert radius from meters to degrees
        double radiusInDegrees = radius / 111000f;

        double u = random.nextDouble();
        double v = random.nextDouble();
        double w = radiusInDegrees * Math.sqrt(u);
        double t = 2 * Math.PI * v;
        double x = w * Math.cos(t);
        double y = w * Math.sin(t);

        // Adjust the x-coordinate for the shrinking of the east-west distances
        double new_x = x / Math.cos(Math.toRadians(y0));

        double foundLongitude = new_x + x0;
        double foundLatitude = y + y0;
        LatLng position = new LatLng(foundLongitude, foundLatitude);


        MarkerOptions mo = new MarkerOptions()
                .position(position)
                .title(i + "").alpha(0.87f)
                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));

        Marker marker = mMap.addMarker(mo);


    }




}

50000 means 50km radius and x0 and y0 are center of radius

Upvotes: 1

Related Questions