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

问题描述

我正在使用 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 的文档。和 PolyUtil java docs

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

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

在此示例中,标记绘制为绿色圆圈、包含矩形和两个任意点(可能的用户位置)以显示计算结果(RED=in,BLUE=out)。

// 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,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,true) ? Color.RED : Color.BLUE);

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

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

并显示:

enter image description here