Check if a latitude and longitude is within a circ

2019-01-16 13:03发布

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

4条回答
成全新的幸福
2楼-- · 2019-01-16 13:39

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.

查看更多
ゆ 、 Hurt°
3楼-- · 2019-01-16 13:53

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);
查看更多
戒情不戒烟
4楼-- · 2019-01-16 13:53

If you mean by "How to create an area", that you want to draw the area on the map, you will find an example right in the map V2 reference doc for the class Circle.

For checking whether the distance between the center of the circle and your point is greater than 10 km I would suggest to use the static method Location.distanceBetween(...) as it avoids unnecessary object creations.

See also here (at the very end of the answer) for a code example in case the area is a polygon rather than a circle.

查看更多
我命由我不由天
5楼-- · 2019-01-16 14:01

What you basically need, is the distance between to 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 that API: https://developer.android.com/reference/android/location/Location.html

查看更多
登录 后发表回答