前期准备
ol版本7.1.0 node版本16.14.2 npm版本8.5.0
import 'ol/ol.css';
import { Overlay, sphere } from 'ol';
// import { getDistance } from 'ol/sphere';
import Map from 'ol/Map';
import XYZ from 'ol/source/XYZ'
import View from 'ol/View';
import { get, fromLonLat, transform } from 'ol/proj';
import { Tile as TileLayer, Vector as VectorLayer } from 'ol/layer';
import { getTopLeft, getWidth } from 'ol/extent';
import Feature from 'ol/Feature';
import { Fill, Stroke, Icon, Style } from 'ol/style'
import { Polygon, MultiPolygon, LinearRing, Point, Circle } from "ol/geom";//添加图层按钮
import VectorSource from 'ol/source/Vector';
import GeoJSON from 'ol/format/GeoJSON.js';
import { fromExtent } from "ol/geom/Polygon";
// import OLCesium from 'olcs';
import geoJson from '../../../public/json/hf.json'
import markerImg from '@/assets/img/bg.png'
实现,这里与上一篇的4326编码格式的反向遮罩主要的不同在于,需要改变GeoJSON().readFeatures的写法和边界点的坐标
//创建蒙层,凸显json区域
showGuangxiArea() {
let initLayer = new VectorLayer({
zIndex: 5,
visible: true,
source: new VectorSource(),
style: new Style({
fill: new Fill({
color: "rgba( 7, 16, 28, 1)",
}),
stroke: new Stroke({
color: "#26d4fa",
width: 2
})
})
});
this.map.addLayer(initLayer);
this.addConver(initLayer, geoJson);
},
//添加遮罩
addConver(converLayer, data) {
const fts = new GeoJSON().readFeatures(data, {
dataProjection: 'EPSG:4326',
featureProjection: 'EPSG:3857',
});
// console.log('fts :>> ', fts);
const ft = fts[0];
const converGeom = this.erase(ft.getGeometry());
const convertFt = new Feature({
geometry: converGeom,
});
converLayer.getSource().addFeature(convertFt);
},
//擦除操作,生产遮罩范围
erase(geom) {
//边界坐标转换为3857格式
const extent = [-20037508.34, -20037508.34, 20037508.34, 20037508.34];
const polygonRing = fromExtent(extent);
const coords = geom.getCoordinates();
coords.forEach(coord => {
const linearRing = new LinearRing(coord[0]);
polygonRing.appendLinearRing(linearRing);
});
return polygonRing;
},
实现效果