谷歌地图多边形各边距离显示、中心面积标注及首尾点距离修复需求
解决方案
一、修复首尾顶点间距离的显示问题
原代码循环逻辑未覆盖最后一个顶点到第一个顶点的边,导致这条边的长度缺失。调整循环逻辑,确保遍历多边形所有边:
修改polygonLabels()方法如下:
private void polygonLabels() { // 清除旧标记避免重复(按需保留,动态更新场景建议添加) for (Marker marker : polygonMarkers) { marker.remove(); } polygonMarkers.clear(); int pointCount = polygonPoints.size(); // 遍历所有边,共pointCount条(含最后一点到第一点的边) for (int i = 0; i < pointCount; i++) { LatLng startPoint = polygonPoints.get(i); // 终点:最后一个点时回到第一个点 LatLng endPoint = polygonPoints.get((i + 1) % pointCount); // 计算两点距离 double distance = SphericalUtil.computeDistanceBetween(startPoint, endPoint); int distanceInt = (int) distance; String distanceString = distanceInt + "m"; // 获取边的中点 LatLng midpoint = SphericalUtil.interpolate(startPoint, endPoint, 0.5); // 添加距离标记 Marker marker = addText(getApplicationContext(), mMap, midpoint, distanceString, 2, 18); polygonMarkers.add(marker); } // 调用面积标注方法 addAreaLabel(); }
关键修改点:
- 循环从
i=0开始遍历所有顶点,确保每条边都被处理 - 用
(i + 1) % pointCount自动处理最后一个点到第一个点的跳转 - 新增旧标记清除逻辑,避免多次调用时标记堆积
二、添加多边形中心的面积标注
新增方法计算并标注多边形面积,借助Google Maps Utils工具类实现:
private void addAreaLabel() { if (polygonPoints.size() < 3) { return; // 至少3个点才能构成多边形 } // 计算多边形面积(单位:平方米) double area = SphericalUtil.computeArea(polygonPoints); String areaString; // 根据面积大小格式化显示 if (area >= 10000) { areaString = String.format("%.2f 公顷", area / 10000); } else { areaString = String.format("%.0f ㎡", area); } // 计算多边形质心(中心位置) LatLng centroid = SphericalUtil.computeCentroid(polygonPoints); // 添加面积标记(调整参数区分距离标记) Marker areaMarker = addText(getApplicationContext(), mMap, centroid, areaString, 4, 20); // 可单独存储面积标记,方便后续更新/移除 // areaMarkers.add(areaMarker); }
说明:
SphericalUtil.computeArea():Google Maps Utils提供的高精度球面面积计算方法SphericalUtil.computeCentroid():计算多边形质心,作为面积标注的位置- 面积格式化:根据实际需求调整单位和小数位数,提升可读性
注意事项
- 确保已引入Google Maps Utils库,否则
SphericalUtil无法使用。在build.gradle中添加依赖:
implementation 'com.google.maps.android:android-maps-utils:2.2.0'
- 需在多边形绘制完成(所有顶点存入
polygonPoints)后调用polygonLabels()方法
内容的提问来源于stack exchange,提问作者Aayushi Raj Singh
相关产品推荐
相关产品推荐

