![](/img/trans.png)
[英]How to create a resizable rectangle with user touch events on google map Android?
[英]Android Google Map how to check if user is in marker rectangle region
我正在使用谷歌地圖,並希望能夠使用用戶的當前位置檢測用戶是否在標記的矩形中(放置在地圖上)。 我有用戶的當前位置坐標(緯度和經度)和標記的坐標,但不知道如何計算用戶是否在該區域內。
如果它們在框中,則經度和緯度將在邊界框的點之間。 檢查此站點以了解經度和緯度的確切工作原理。 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 文檔
這是一個演示代碼片段。 請注意,矩形旋轉由實用程序處理,因此無需與坐標系對齊。 事實上,它甚至不需要是一個矩形。
(我選擇使用圓圈進行顯示,但可以用標記替換。):
在此示例中,標記被繪制為綠色圓圈,包含矩形和兩個任意點(可能的用戶位置)以顯示計算結果(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, 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));
並顯示:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.