在vue项目的基础上,使用openlayers创建地图,并且实现上下两个地图联动展示
前言
在vue项目的基础上,使用openlayers创建地图,并且实现上下两个地图联动展示。
提示:以下是本篇文章正文内容,下面案例可供参考
一、方法
让上下两个地图联动展示方式很简单,只要让他们使用同一个view就可以了,下面是一个简单的例子记录。
二、创建步骤
1.引入库
代码如下(示例):
import { reactive, onMounted } from 'vue';
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import "ol/ol.css";
import TileArcGISRest from 'ol/source/TileArcGISRest';
2.创建地图
代码如下(示例):
// 初始化地图
const initMap = () => {
state.view = new View({
center: [0, 0],
zoom: 13,
maxZoom: 18,
minZoom: 0,
projection: "EPSG:4326",
center: [104.139919, 30.674801],
enableRotation: false, // 配置不能旋转
});
state.map1 = new Map({
target: 'map-first',
layers: [
new TileLayer({
//OSM地图
//source: new OSM()
source: new TileArcGISRest({
url: 'https://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineCommunity/MapServer'
})
}),
],
view: state.view,
});
state.map2 = new Map({
target: 'map-second',
layers: [
new TileLayer({
//OSM地图
//source: new OSM()
source: new TileArcGISRest({
url: 'https://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineCommunity/MapServer'
})
}),
],
view: state.view,
});
}
这部分是地图的初始化创建,可以看到我们使用了同一个view。
总结
最终效果如图:(拖动地图或者放大缩小,两个地图的操作会同步进行)
完整代码如下展示:
<template>
<div class="map-container">
<div class="map1" id="map-first"></div>
<div class="map2" id="map-second"></div>
</div>
</template>
<script setup>
import { reactive, onMounted } from 'vue';
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import "ol/ol.css";
import TileArcGISRest from 'ol/source/TileArcGISRest';
const state = reactive({
map1: null,
map2: null,
view: null,
});
// 初始化地图
const initMap = () => {
state.view = new View({
center: [0, 0],
zoom: 13,
maxZoom: 18,
minZoom: 0,
projection: "EPSG:4326",
center: [104.139919, 30.674801],
enableRotation: false, // 配置不能旋转
});
state.map1 = new Map({
target: 'map-first',
layers: [
new TileLayer({
//OSM地图
//source: new OSM()
source: new TileArcGISRest({
url: 'https://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineCommunity/MapServer'
})
}),
],
view: state.view,
});
state.map2 = new Map({
target: 'map-second',
layers: [
new TileLayer({
//OSM地图
//source: new OSM()
source: new TileArcGISRest({
url: 'https://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineCommunity/MapServer'
})
}),
],
view: state.view,
});
}
onMounted(() => {
initMap();
})
</script>
<style scoped lang='less'>
.map-container {
position: relative;
width: 100%;
height: 100vh;
box-sizing: border-box;
.map1 {
height: 45%;
box-sizing: border-box;
border: 3px solid aquamarine;
}
.map2 {
height: 45%;
box-sizing: border-box;
border: 3px solid purple;
}
}
</style>