官网demo地址:
又是一个轻松简单的示例~
设定地图拖动的限制范围。
new View的时候设置extent为中国,中心点设置为北京。缩小的时候就会发现不能拖到中国以外的地区啦。
const view = new View({
projection: "EPSG:4326",
center: [116.389, 39.903],
zoom: 8,
extent: [73.66, 3.86, 135.05, 53.55], //中国边界
});
限制大小也可以通过 minZoom和maxZoom来设置
const view = new View({
projection: "EPSG:4326",
center: [116.389, 39.903],
zoom: 8,
// extent: [73.66, 3.86, 135.05, 53.55], //中国边界、
minZoom: 9,
maxZoom: 13,
});
左上角的滑块是new Map的时候加上去的,是地图自带的控件,拖动它就可以放大缩小地图。
defaultControls().extend([new ZoomSlider()])
完整代码:
<template>
<div class="box">
<h1>Constrained Extent</h1>
<div id="map"></div>
</div>
</template>
<script>
import Map from "ol/Map.js";
import OSM from "ol/source/OSM.js";
import TileLayer from "ol/layer/Tile.js";
import View from "ol/View.js";
import ZoomSlider from "ol/control/ZoomSlider.js";
import { defaults as defaultControls } from "ol/control.js";
import { XYZ } from "ol/source";
export default {
name: "",
components: {},
data() {
return {
map: null,
};
},
computed: {},
created() {},
mounted() {
// const view = new View({
// center: [328627.563458, 5921296.662223],
// zoom: 8,
// extent: [-572513.341856, 5211017.966314, 916327.095083, 6636950.728974],
// });
const view = new View({
projection: "EPSG:4326",
center: [116.389, 39.903],
zoom: 8,
// extent: [73.66, 3.86, 135.05, 53.55], //中国边界、
minZoom: 9,
maxZoom: 13,
});
new Map({
layers: [
new TileLayer({
source: new XYZ({
url: "http://{a-c}.tile.openstreetmap.org/{z}/{x}/{y}.png",
}),
}),
],
keyboardEventTarget: document,
target: "map",
view: view,
controls: defaultControls().extend([new ZoomSlider()]),
});
},
methods: {},
};
</script>
<style lang="scss" scoped>
#map {
width: 100%;
height: 500px;
}
.box {
height: 100%;
}
</style>