openlayers限制地图显示范围
1.静态限制地图显示范围
适用于创建地图时,限制区域不发生改变
关键在于设置view对象 其中extent 属性是设置视图范围的
export default class CreateMap {
constructor(id) {
this.map = new Map({
controls: [], // 地图控件
target: id,
layers: [
new TileLayer({
id: 'BASEMAP_VECTOR_LAYER',
preload: Infinity,
extent:[], // 长度为4的数组, 传入地图对角投影坐标
source: new Tianditu({ projection: 'PROJECTION_4326', cacheSize: 204800 }),
visible: true,
}),
new TileLayer({
id: 'BASEMAP_VECTOR_LAYER',
preload: Infinity,
extent:[], // 长度为4的数组, 传入地图对角投影坐标
source: new Tianditu({
projection:'PROJECTION_4326',
layerType: 'img',
cacheSize: 204800,
}),
visible: false,
}),
],
view: new View({
projection: PROJECTION_4326,
center: config.map.center,
extent:[], // 长度为4的数组, 传入地图对角投影坐标,
maxZoom: 23,
minZoom: 1,
zoom: 11,
}),
});
}
}
1.动态限制地图显示范围
适用于切换不同的限制区域
const view = map.getView();
// feature为 特征对象
让特征对象填充整个视图 并放在视图中间
view.fit(feature.getGeometry(), {
padding: [0, 0, 0, 0],
maxZoom,
});
limitExtent();
// 限制地图显示范围
limitExtent() {
// 获取地图投影坐标
const extent = this.map.getView().calculateExtent(this.map.getSize());
const viewExtent = new View({
projection: ‘PROJECTION_4326’,
center: this.map.getView().getCenter(),
extent,
zoom: this.map.getView().getZoom(),
maxZoom: 19,
minZoom:1,
constrainResolution: true,
smoothResolutionConstraint: true,
});
this.map.setView(viewExtent);
}
注意因为是创建了一个新View 所以跟之前的view绑定的事件会消失,比如
change:resolution 事件 需要重新进行绑定
要恢复之前的视图 需要恢复地图创建时的view