Android开发:如何基于坐标与areaDifference调整Google Map矩形面积?
如何根据面积缩放Google Map上的矩形/多边形?
嘿,这个需求其实挺常见的,核心思路就是围绕矩形的中心点按比例缩放每个顶点——毕竟要保持矩形形状不变的话,等比例缩放是最合理的方式。我给你拆解一下具体步骤,再附上代码示例,应该就能搞定了:
步骤1:计算矩形的中心点
矩形的中心点是两条对角线的交点,所以我们只需要取任意一组对角顶点的坐标,计算纬度和经度的平均值就行。比如取左上角(topLeft)和右下角(bottomRight):
// 假设你已经有四个顶点的LatLng对象:topLeft, topRight, bottomRight, bottomLeft LatLng center = new LatLng( (topLeft.latitude + bottomRight.latitude) / 2, (topLeft.longitude + bottomRight.longitude) / 2 );
步骤2:计算线性缩放比例
因为面积的缩放比例是areaDifference(比如设为2就是面积扩大2倍),而面积是线性尺寸的平方关系,所以线性缩放比例是面积比例的平方根。比如面积要扩大2倍,每个方向的长度就要乘以√2:
double scaleFactor = Math.sqrt(areaDifference);
如果是缩小面积,比如areaDifference=0.5,那scaleFactor就是√0.5≈0.707,也就是缩小到原来的70.7%左右,面积就变成一半了。
步骤3:计算每个顶点的新坐标
对每个顶点,我们先算出它相对于中心点的偏移量,然后乘以缩放比例,最后加上中心点的坐标,就能得到缩放后的新坐标:
// 工具方法:根据中心点和缩放比例计算新的LatLng private LatLng scaleLatLng(LatLng original, LatLng center, double scaleFactor) { double newLat = center.latitude + (original.latitude - center.latitude) * scaleFactor; double newLng = center.longitude + (original.longitude - center.longitude) * scaleFactor; return new LatLng(newLat, newLng); } // 生成四个新顶点 LatLng newTopLeft = scaleLatLng(topLeft, center, scaleFactor); LatLng newTopRight = scaleLatLng(topRight, center, scaleFactor); LatLng newBottomRight = scaleLatLng(bottomRight, center, scaleFactor); LatLng newBottomLeft = scaleLatLng(bottomLeft, center, scaleFactor);
步骤4:更新Google Map上的多边形
把原来的多边形移除(如果已经添加到地图上),然后用新的顶点集合创建新的多边形并添加到地图:
// 假设你有原来的Polygon对象:originalPolygon if (originalPolygon != null) { originalPolygon.remove(); } // 创建新的多边形 PolygonOptions polygonOptions = new PolygonOptions() .add(newTopLeft, newTopRight, newBottomRight, newBottomLeft) .strokeColor(Color.RED) .fillColor(Color.argb(50, 255, 0, 0)); Polygon newPolygon = mMap.addPolygon(polygonOptions);
注意事项
- 如果你的“矩形”其实是任意四边形(不是轴对齐的),这个方法依然有效,因为是围绕中心点等比例缩放所有顶点,形状会保持不变,只是面积按比例变化。
- 要注意经纬度的单位是度,缩放后的坐标依然符合地理坐标规则,不会出现异常值(只要scaleFactor是合理的正数)。
内容的提问来源于stack exchange,提问作者Jaspreet Singh
相关产品推荐
相关产品推荐

