效果图
完整代码
<!DOCTYPE html>
<html>
<head>
<title>遮罩</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<!-- Openlayers -->
<link rel="stylesheet" href="https://openlayers.org/en/latest/css/ol.css" />
<script type="text/javascript" src="https://openlayers.org/en/latest/build/ol.js"></script>
<style>
html,
body,
.map {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
overflow: hidden;
}
</style>
</head>
<body>
<div id="map" class="map"></div>
<script>
var xyzLayer = new ol.layer.Tile({
source: new ol.source.XYZ({
url: 'http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}'
})
});
var map = new ol.Map({
target: 'map',
view: new ol.View({
zoom: 14.5,
center: [12127495.117988808, 4058905.64276462],
extent: [12100000, 4050000, 12150000, 4069000]
}),
layers: [xyzLayer]
});
// 添加遮罩图层
var maskSource = new ol.source.Vector()
var maskLayer = new ol.layer.Vector({
source: maskSource,
style: new ol.style.Style({
stroke: new ol.style.Stroke({
color: '#5fcac7',
width: 3
}),
fill: new ol.style.Fill({
color: "rgba(0,0,0,0.4)",
}),
})
})
map.addLayer(maskLayer)
$.getJSON("./xiaozhai_gcj02_3857.geojson", e => {
features = new ol.format.GeoJSON().readFeatures(e);
// 一个大致的范围
let extent = [12100000, 4050000, 12150000, 4069000];
let polygonRing = ol.geom.Polygon.fromExtent(extent);
features.forEach(f => {
var coords = f.getGeometry().getCoordinates();
coords.forEach(coord => {
let linearRing = new ol.geom.LinearRing(coord[0]);
polygonRing.appendLinearRing(linearRing);
})
})
let ft = new ol.Feature({
geometry: polygonRing
})
// maskLayer.getSource().addFeature(ft);
maskSource.addFeature(ft);
})
</script>
</body>
</html>