最近遇到一个需求,就是在高德地图的 Polygon
内绘制一个更小的Polygon
区域,在其中心显示一个Marker
,
给高德地图提了个工单,但是并没有很好的解决这个问题,所以自己写一个计算中心经纬度的方法,在这里记录下
const lonlat = [
[116.427929, 39.904887],
[116.427935, 39.904811],
[116.427863, 39.904774],
[116.42781, 39.90475],
[116.427739, 39.904725],
[116.42768, 39.904722],
[116.427627, 39.904718],
[116.427543, 39.904721],
[116.427541, 39.90476],
[116.427539, 39.904799],
[116.427537, 39.904852],
[116.427545, 39.904891],
[116.427604, 39.904887],
[116.427659, 39.904888],
[116.427757, 39.904887],
[116.427845, 39.904888],
]
//经纬度测算中心位置
function getCenter(arr) {
let centerLonLat = []
if (arr.length) {
const lon = []
const lat = []
const poly = [];
for (let i = 0, len = arr.length; i < len; i++) {
lon.push(arr[i][0])
lat.push(arr[i][1])
}
for (let i = 0, len = lon.length; i < len; i++) {
poly.push({
x: parseFloat(lon[i]),
y: parseFloat(lat[i]),
z: 0
});
}
const sortedLongitudeArray = poly.map(item => item.x).sort();
const sortedLatitudeArray = poly.map(item => item.y).sort();
const centerLongitude = ((parseFloat(sortedLongitudeArray[0]) + parseFloat(sortedLongitudeArray[sortedLongitudeArray.length - 1])) / 2).toFixed(14);
const centerLatitude = ((parseFloat(sortedLatitudeArray[0]) + parseFloat(sortedLatitudeArray[sortedLatitudeArray.length - 1])) / 2).toFixed(14);
console.log(centerLongitude, centerLatitude);
centerLonLat = [Number(centerLongitude), Number(centerLatitude)]
}
return centerLonLat;
}
getCenter(lonlat)