导入地区geojson数据,使得该地区正常显示,其他地区灰色.
实际就是运用了leaflet的Polygon,传递两个数组的镂空效果.
geojson数据可通过阿里datav geoAtlas获取
使用maxBounds和minZoom限制地图滚动范围
map = new L.Map('mapContainer', {
renderer: streetLabelsRenderer,
center: [29.58332, 106.540327],
maxBounds: [
[33.507245, 105.04296],
[27.751845, 110.681731]
],
zoomControl: false,
attributionControl: false,
maxZoom: 18,
minZoom: 7,
zoom: 12
});
import ChongQingCity from '@/assets/data/重庆市.json';
const polygonArea = ref();
function drawPolygon() {
// 获取此时地图的四个角经纬度
let mapNW = map.value.getBounds().getNorthWest();
let mapNE = map.value.getBounds().getNorthEast();
let mapSE = map.value.getBounds().getSouthEast();
let mapSW = map.value.getBounds().getSouthWest();
// 四个角经纬整理成一组数据
let fourLatlng = [[mapNW.lat, mapNW.lng], [mapNE.lat, mapNE.lng], [mapSE.lat, mapSE.lng], [mapSW.lat, mapSW.lng]];
// 要绘制的区域经纬度数据
//let checkLatlng = [
// [-58.033905029296875, 120.20416259765625],
// [-58.03733825683594, 120.43418884277344],
// [-58.13690185546875, 120.42526245117188],
// [-58.21449279785156, 120.43968200683594],
// [-58.38958740234375, 120.45616149902344],
// [-58.44451904296875, 120.38475036621094],
// [-58.42460632324219, 120.25154113769531],
// [-58.32366943359375, 120.28312683105469],
// [-58.19732666015625, 120.24879455566406],
// [-58.077850341796875, 120.19935607910156]
// ]
// 要绘制的区域经纬度数据
let checkLatlng = ChongQingCity.features[0].geometry.coordinates[0][0];
// 调换checkLatlng数组中顺序
// 默认geojson数据是[经度,纬度]的数组,leaflet格式要求则是[纬度,经度],需要调整一下
checkLatlng = checkLatlng.map(item => {
return [item[1], item[0]];
});
let latlngs = [fourLatlng, checkLatlng]
// 移除图层-不移除图层会不断叠加遮罩
if (polygonArea.value) {
polygonArea.value.remove(map.value);
polygonArea.value = null;
}
// 绘制多边形区域
polygonArea.value = L.polygon(
latlngs,
{
color: "#9cdbff", // 线条颜色,weight为0时不会显示 可以不设置
fillColor: "#000", // 区域颜色
fillOpacity: 0.7, // 区域颜色透明度
weight: 0, // 线条粗细
}
).addTo(map.value);
};