android 高德地图画多边形,已知中心点 宽高画矩形 ,实际距离 千米转地图坐标距离

项目中用到mapabc 绘制矩形区域。客户只能手动选择中心点,并填写区域的宽和高,切单位为km。要求实时显示规划区域。

记录笔记。

第一步找到地图绘制多边形api

polygon = map.addPolygon(new PolygonOptions()
        .addAll(createRectangle(marker.getPosition(), 1, 1))//绘制多边形顶点坐标
        .fillColor(0x1A1677FF)//填充颜色
        .strokeColor(0xDE1677FF)//边界颜色
        .strokeWidth(5));//边界宽度

我们已知顶点坐标和客户输入的宽高km  需要计算多边形的顶点坐标(矩形):

 /**
     * 生成一个长方形的四个坐标点
     */
    private List<LatLng> createRectangle(LatLng center, double halfWidth,
                                         double halfHeight) {

        float distance = (float) Math.sqrt(halfWidth * halfWidth + halfHeight * halfHeight);//计算直角三角形斜边 。
        float degree= getDegree(0.0,0.0,-halfWidth,0.0,-halfWidth,halfHeight);//计算三角形锐角角度
        //生成四边形四个点坐标
        return Arrays.asList(
                getLatlng(distance, center,90-degree),
                getLatlng(distance, center, 90+degree),
                getLatlng(distance, center, 270-degree),
                getLatlng(distance, center, 270+degree)
        );
    }

步骤1,通过宽高算矩形顶点到中心点的距离

float distance = (float) Math.sqrt(halfWidth * halfWidth + halfHeight * halfHeight);

步骤2,通过虚拟坐标轴定位计算y轴和矩形对角线的夹角

float degree= getDegree(0.0,0.0,-halfWidth,0.0,-halfWidth,halfHeight);

            以虚拟坐标系的方式运用数学知识计算夹角

/**
 * 在坐标系中计算两条相交线夹角
 * @param vertexPointX 交点坐标
 * @param vertexPointY
 * @param point0X A点坐标
 * @param point0Y
 * @param point1X  b点坐标
 * @param point1Y
 * @return
 */
private int getDegree(Double vertexPointX, Double vertexPointY, Double point0X, Double point0Y, Double point1X, Double point1Y) {
    //向量的点乘
    Double vector = (point0X - vertexPointX) * (point1X - vertexPointX) + (point0Y - vertexPointY) * (point1Y - vertexPointY);
    //向量的模乘
    double sqrt = Math.sqrt(
            (Math.abs((point0X - vertexPointX) * (point0X - vertexPointX)) + Math.abs((point0Y - vertexPointY) * (point0Y - vertexPointY)))
                    * (Math.abs((point1X - vertexPointX) * (point1X - vertexPointX)) + Math.abs((point1Y - vertexPointY) * (point1Y - vertexPointY)))
    );
    //反余弦计算弧度
    double radian = Math.acos(vector / sqrt);
    //弧度转角度制
    return (int) (180 * radian / Math.PI);
}

步骤3,通过地图中心点,实际距离(矩形顶点到中心点距离),及夹角计算出顶点在地图上的坐标。

getLatlng(distance, center,90-degree)

/**
 *
 * @param distance 距离
 * @param latlngA 中心点坐标
 * @param angle 夹角
 * @return
 */
public static LatLng getLatlng(float distance, LatLng latlngA, double angle) {
    return new LatLng(latlngA.latitude + (distance * Math.cos(angle * Math.PI / 180)) / 111,
            latlngA.longitude + (distance * Math.sin(angle * Math.PI / 180)) / (111 * Math.cos(latlngA.latitude * Math.PI / 180))
    );
}

我默认画的图为正方向显示。如果需要倾斜。在getLatlng(distance, center,90-degree) 第三个参数做手脚即可

如果是参照点为矩形的一个顶点,参照上面方法更简单。

猜你喜欢

转载自blog.csdn.net/qq_36355271/article/details/108781514