如果可以实现记得点赞分享,谢谢老铁~
在开始之前,我们先看下效果图,如下:
第一步,写一个initDrawLayer 绘画图层的方法,这里面主要处理图层的闭合,生成,颜色,透明度等样式。这里主要用到了遍历,才可以生成多个图层。代码如下:
// 初始化加载图层
// ps: 这里的data 就是传入的经纬度的集合
const initDrawLayer = (data: any) => {
let allList: any = [];
data?.forEach((item: any) => {
if (item && item.coordinates && item.coordinates.length > 0) {
// Add a data source containing GeoJSON data.
const source = map.current.getSource('maine');
const JsonObj: any = {
'type': 'geojson',
"data": {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"properties": { "name": "Null Island" },
"geometry": {
"type": "Polygon",
"coordinates": [item.coordinates]
}
}]
}
}
let jsonObjList = JsonObj.data.features[0].geometry.coordinates[0]
// 这个地方主要判断经纬度结合中的首尾要闭合,要一样。
if (
jsonObjList[0][0] !== jsonObjList[jsonObjList.length - 1][0] &&
jsonObjList[0][1] !== jsonObjList[jsonObjList.length - 1][1]
) {
jsonObjList.push(item.coordinates[0])
}
if (source) {
const featuresList = source._data.features;
featuresList.push(JsonObj.data.features[0])
source.setData({
"type": "FeatureCollection",
"features": featuresList
})
} else {
map?.current?.addSource(`maine`, JsonObj);
}
}
});
// Add a new layer to visualize the polygon.
map?.current?.addLayer({
'id': `maine`,
'type': 'fill',
'source': 'maine', // reference the data source
'layout': {},
'paint': {
'fill-color': '#0080ff', // blue color fill
'fill-opacity': 0
}
});
// Add a black outline around the polygon.
map?.current?.addLayer({
'id': `outline`,
'type': 'line',
'source': 'maine',
'layout': {},
'paint': {
'line-color': '#0080ff',
'line-width': 1
}
});
}
第二步,然后再调用initDrawLayer()之前务必要将原有的source 清除。
// 绘画区域
const addPolygonOne = (data: any[]) => {
if (!map.current) return;
const source = map.current.getSource('maine');
if (source) {
map.current.removeLayer('maine')
source.setData({
"type": "FeatureCollection",
"features": []
})
initDrawLayer(data)
}
};
useEffect(()=>{
// data为经纬度的集合
addPolygonOne(data)
})
参考资料: