Check if a latitude and longitude is within a circle

46,241

Solution 1

What you basically need, is the distance between two points on the map:

float[] results = new float[1];
Location.distanceBetween(centerLatitude, centerLongitude, testLatitude, testLongitude, results);
float distanceInMeters = results[0];
boolean isWithin10km = distanceInMeters < 10000;

If you have already Location objects:

Location center;
Location test;
float distanceInMeters = center.distanceTo(test);
boolean isWithin10km = distanceInMeters < 10000;

Here is the interesting part of the API used: https://developer.android.com/reference/android/location/Location.html

Solution 2

Check this:

 private boolean isMarkerOutsideCircle(LatLng centerLatLng, LatLng draggedLatLng, double radius) {
    float[] distances = new float[1];
    Location.distanceBetween(centerLatLng.latitude,
            centerLatLng.longitude,
            draggedLatLng.latitude,
            draggedLatLng.longitude, distances);
    return radius < distances[0];
}

Solution 3

Have you gone through the new GeoFencing API. It should help you. Normal implementation takes a lot of time. This should help you implementing it easily.

Solution 4

see https://developer.android.com/reference/android/location/Location.html

Location areaOfIinterest = new Location;
Location currentPosition = new Location;

areaOfIinterest.setLatitude(aoiLat);
areaOfIinterest.setLongitude(aoiLong);

currentPosition.setLatitude(myLat);
currentPosition.setLongitude(myLong);

float dist = areaOfIinterest.distanceTo(currentPosition);

return (dist < 10000);

Solution 5

Just in case if anyone is using GoogleMap and tried to apply location range by long&lat. You may try google.maps.Circle()

i.e. (mkr is your marker)

  let yourcircle = new google.maps.Circle({
    strokeColor: "#0079C3",
    strokeOpacity: .8,
    strokeWeight: 2,
    fillColor: "#0079C3",
    fillOpacity: 0.2,
    map: this.map,
    center:  {'lat':your latitude, 'lng':your longitude},
    radius: Math.sqrt(your distance range) * 1000,
  });
Share:
46,241
Peter Warbo
Author by

Peter Warbo

I work as IT consultant in Gothenburg, Sweden, doing mobile development mostly for iOS.

Updated on February 14, 2021

Comments

  • Peter Warbo
    Peter Warbo about 3 years

    See this illustration:

    enter image description here

    What I would like to know is:

    1. How to create an area (circle) when given a latitude and longitude and the distance (10 kilometers)
    2. How to check (calculate) if a latitude and longitude is either inside or outside the area

    I would prefer if you can give me code example in Java or specifically for Android with Google Maps API V2