参考:
openlayers实现四周遮罩,特定区域透明效果_openlayers掩膜效果_月影星云的博客-CSDN博客
<template>
<div id="Map" class="Map"></div>
</template>
<script>
import "ol/ol.css";
import { Map, View, Feature } from "ol";
import { XYZ, Vector as VectorSource } from "ol/source";
import { Tile as TileLayer, Vector as VectorLayer } from "ol/layer";
import { GeoJSON } from "ol/format";
import LinearRing from 'ol/geom/LinearRing.js';
import { fromExtent } from "ol/geom/Polygon";
import { Style, Stroke, Fill } from "ol/style";
import axios from 'axios'
export default {
name: "MaskMap",
data() {
return {
map: null,
}
},
mounted(){
this.initMap();
},
methods: {
//初始化地图
initMap(){
var layers = [
new TileLayer({
source: new XYZ({
// 灰色底图 wgs84
url: "http://map.geoq.cn/arcgis/rest/services/ChinaOnlineStreetGray/MapServer/tile/{z}/{y}/{x}"
})
})
];
//地图对象
this.map = new Map({
target: "Map",
view: new View({
projection: "EPSG:4326",
center: [113.688548,34.761685],
zoom: 7,
}),
layers: layers,
overlays: [],
});
//创建蒙层,凸显河南区域
this.showHenanArea();
},
//创建蒙层,凸显河南区域
showHenanArea(){
let initLayer = new VectorLayer({
zIndex: 3,
source: new VectorSource(),
style: new Style({
fill: new Fill({
color:"rgba( 255, 255, 255, 0.7)",
}),
stroke: new Stroke({
color:"#f4b49f",
width:3
})
})
});
this.map.addLayer(initLayer);
axios.get('https://geo.datav.aliyun.com/areas_v3/bound/geojson?code=410000').then(({ data }) => {
this.addConver(initLayer, data);
});
},
//添加遮罩
addConver(converLayer, data) {
const fts = new GeoJSON().readFeatures(data);
const ft = fts[0];
const converGeom = this.erase(ft.getGeometry());
const convertFt = new Feature({
geometry: converGeom,
});
converLayer.getSource().addFeature(convertFt);
},
//擦除操作,生产遮罩范围
erase(geom) {
const extent = [-180, -90, 180, 90];
const polygonRing = fromExtent(extent);
const coords = geom.getCoordinates();
coords.forEach(coord => {
const linearRing = new LinearRing(coord[0]);
polygonRing.appendLinearRing(linearRing);
});
return polygonRing;
}
}
}
</script>
<style>
html, body, #app, .Map{
width: 100%;
height: 100%;
}
</style>