# 移动地图时地图自动获取当前地图中心地区

## 代码实现

let extent = map.getExtent()

[{
"name": "密云县",
"cp": [117.0923, 40.5121],
"id": 110228,
"extent": [116.6776, 40.223, 117.507, 40.8012]
}, {
"name": "怀柔区",
"cp": [116.6377, 40.6219],
"id": 110116,
"extent": [116.2875, 40.2292, 116.8863, 41.0607]
}, {
"name": "房山区",
"cp": [115.8453, 39.7163],
"id": 110111,
"extent": [115.4361, 39.5082, 116.2546, 39.925]
}...]

/
* 获取两个矩形交叉的矩形交叉矩形
* @param {any} rectA [startX, startY, endX, endY]
* @param {any} rectB [startX, startY, endX, endY]
* @returns
/
function getCrossRect(rectA, rectB) {
if (rectB[0] > rectA[2] || rectB[2] < rectA[0] || rectB[1] > rectA[3] || rectB[3] < rectA[1]) return [0, 0, 0, 0]
let startX = rectA[0] > rectB[0] ? rectA[0] : rectB[0],
startY = rectA[1] > rectB[1] ? rectA[1] : rectB[1],
endX = rectA[2] < rectB[2] ? rectA[2] : rectB[2],
endY = rectA[3] < rectB[3] ? rectA[3] : rectB[3]
return [startX, startY, endX, endY]
}

/
* 矩形面积
* @param {any} rect [startX, startY, endX, endY]
* @returns
/
function square(rect) {
return (rect[2] - rect[0])  (rect[3] - rect[1])
}

/
* 获取矩形中心
* @param {any} rect [startX, startY, endX, endY]
* @returns
*/
function getCenter(rect) {
return [(rect[0] + rect[2]) / 2, (rect[1] + rect[3]) / 2]
}

/
* 获得两个点距离的平方
* @param {any} pA
* @param {any} pB
* @returns
/
function lineLength(pA, pB) {
return (pA[0] - pB[0])  2 + (pA[1] - pB[1])  2
}

export default {
getCrossRect,
square,
getCenter,
lineLength
}

const centerOffset = 0.25,    //中心区域便宜
minRatio = 0.7            //最小占比
map.on('viewchange', function (evt) {
let extent = map.getExtent(),
xOffset = (extent.xmax - extent.xmin)  centerOffset,
yOffset = (extent.ymax - extent.ymin)  centerOffset,
// 地图中央50%区域
mainExtent = [extent.xmin + xOffset, extent.ymin + yOffset, extent.xmax - xOffset, extent.ymax - yOffset],
mainCenter = square.getCenter(mainExtent),
candidate = areaExtent.filter(i => {
let crossRect = square.getCrossRect(i.extent, mainExtent)
return square.square(crossRect) / square.square(mainExtent) > minRatio
})
let curArea = candidate.sort((a, b) => {
return square.lineLength(a.cp, mainCenter) - square.lineLength(b.cp, mainCenter)
})[0]
})

curArea即为地图当前显示地区。

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120