Android Google 映射如何检查用户是否在标记矩形区域中

Android Google Map how to check if user is in marker rectangle region

我正在使用 Google 地图,并希望能够使用用户的当前位置检测用户是否在标记(放置在地图上)的矩形内。我有用户的当前位置坐标(经纬度)和标记的坐标,但不知道如何计算用户是否在该区域。

如果它们在框中,经度和纬度将在边界框的点之间。检查此站点以了解经度和纬度的精确工作方式。 https://gsp.humboldt.edu/olm/Lessons/GIS/01%20SphericalCoordinates/Latitude_and_Longitude.html

简短的回答是 PolyUtil.containsLocation 使用矩形角点(以标记为中心)和用户位置:

boolean isWithin = PolyUtil.containsLocation(userPt, rectanglePts, true);

这是 map utils. And the PolyUtil java docs

上的文档

这里是一段代码演示。请注意,矩形旋转由实用程序处理,因此不需要与坐标系对齐。事实上,它甚至不需要是一个矩形。

(我选择使用圆圈进行显示,但可以用标记代替。):

在此示例中,标记被绘制为绿色圆圈,包含矩形和两个任意点(可能的用户位置)以显示计算结果(红色=输入,蓝色=输出)。

// Create rectangle coordinates 
LatLng upperLeft = new LatLng(39.274659,-77.639552);
LatLng upperRight = SphericalUtil.computeOffset(upperLeft, 12000, 120);
LatLng lowerRight = SphericalUtil.computeOffset(upperRight, 5000, 210);
LatLng lowerLeft = SphericalUtil.computeOffset(lowerRight, 12000, 300);

// Make a list for the polygon
List<LatLng> polygonPts = new ArrayList<>();
    polygonPts.add(upperLeft);
    polygonPts.add(upperRight);
    polygonPts.add(lowerRight);
    polygonPts.add(lowerLeft);

// Draw rectangle
mMap.addPolygon(new PolygonOptions().addAll(polygonPts).geodesic(true).strokeColor(Color.BLACK));

// Draw marker (center of rectangle)
LatLng mPos = SphericalUtil.computeOffset(SphericalUtil.computeOffset(upperLeft,6000,120),2500, 210);

// Now add a circle to represent the marker - circles display nicer
mMap.addCircle(new CircleOptions().center(mPos).fillColor(Color.GREEN).radius(300).strokeWidth(1));


// Add two points and compute whether they are inside or outside rectangle and
// set color based on that (RED=inside BLUE=outside)
LatLng circleInside = SphericalUtil.computeOffset(mPos,1000, 320);
LatLng circleOutside = SphericalUtil.computeOffset(mPos,4000, 45);

// Determine if point is inside rectangle and set color accordingly.
int insideCircleColor = (PolyUtil.containsLocation(circleInside, polygonPts, true) ? Color.RED : Color.BLUE);
int outsideCircleColor = (PolyUtil.containsLocation(circleOutside, polygonPts, true) ? Color.RED : Color.BLUE);

// Add to map
mMap.addCircle(new CircleOptions().center(SphericalUtil.computeOffset(circleInside,1000, 320)).fillColor(insideCircleColor).radius(200).strokeWidth(1));
mMap.addCircle(new CircleOptions().center(SphericalUtil.computeOffset(circleOutside,1000, 320)).fillColor(outsideCircleColor).radius(200).strokeWidth(1));

// and zoom to center
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mPos, 12.0f));

并显示: