專案中用到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) 第三個引數做手腳即可
如果是參照點為矩形的一個頂點,參照上面方法更簡單,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/126522.html
標籤:AI
上一篇:求助程式再生偽碼的仿真
下一篇:axios跨域問題 No ‘Access-Control-Allow-Origin‘ header is present on the requested resource.
