Vite + Vue3 + OpenLayers 同步兩個(gè)地圖基礎(chǔ)操作
一、本文簡(jiǎn)介
Vite + Vue3 + OpenLayers 同步兩個(gè)地圖基礎(chǔ)操作
兩個(gè)獨(dú)立的容器怕犁,使用了不同的圖源边篮。但不管操作哪個(gè)容器的地圖,另一個(gè)也會(huì)跟著變化奏甫。
二戈轿、開(kāi)發(fā)環(huán)境
Vite + Vue3 + ol6
# 1、使用 Vite 創(chuàng)建項(xiàng)目阵子;取個(gè)好聽(tīng)的項(xiàng)目名思杯;拉取 vue 的代碼模板
npm init vite@latest
# 2、初始化項(xiàng)目
cd you-project
npm install
# 3挠进、安裝 ol
npm i ol -S
# 4色乾、啟動(dòng)項(xiàng)目
npm run dev
使用 Vite
初始化項(xiàng)目并安裝 ol
,更詳細(xì)做法可以查看 『Vite + Vue3 + OpenLayers 起步』
思路
- 兩個(gè)地圖容器领突,分別使用不同的圖源
- 綁定同一個(gè)視圖層
兩個(gè)地圖使用同一個(gè)view暖璧,所以在移動(dòng)、縮放君旦、旋轉(zhuǎn)等操作都是同步的澎办。
編碼
<!-- ol - 同步兩個(gè)地圖 -->
<template>
<div class="map__container">
<!-- OSM地圖容器 -->
<div id="OSM" class="map__x"></div>
<!-- bing地圖容器 -->
<div id="BingMaps" class="map__x"></div>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { Map, View } from 'ol'
import Tile from 'ol/layer/Tile'
import OSM from 'ol/source/OSM'
import BingMaps from 'ol/source/BingMaps'
import 'ol/ol.css'
const mapO = ref(null) // 綁定OSM地圖實(shí)例的變量
const mapB = ref(null) // 綁定Bing地圖實(shí)例的變量
// 公共的視圖
const mapView = new View({
center: [0, 0],
zoom: 2
})
// OSM圖層
const layerO = new Tile({
source: new OSM()
})
// Bing圖層
const layerB = new Tile({
source: new BingMaps({
key: 'AiZrfxUNMRpOOlCpcMkBPxMUSKOEzqGeJTcVKUrXBsUdQDXutUBFN3-GnMNSlso-',
imagerySet: 'Aerial'
})
})
// 初始化2個(gè)地圖
function initMap () {
mapO.value = new Map({
target: 'OSM',
layers: [layerO], // 使用OSM圖層
view: mapView // 使用了同一個(gè)視圖層
})
mapB.value = new Map({
target: 'BingMaps',
layers: [layerB], // 使用Bing圖層
view: mapView // 使用了同一個(gè)視圖層
})
}
onMounted(() => {
// 在元素加載完之后再執(zhí)行地圖初始化
initMap()
})
</script>
<style lang="scss" scoped>
.map__container {
width: 800px;
height: 380px;
margin-bottom: 60px;
display: flex;
justify-content: space-between;
.map__x {
width: 380px;
height: 380px;
box-sizing: border-box;
border: 1px solid #ccc;
position: relative;
}
#OSM::after,
#BingMaps::after {
position: absolute;
display: block;
font-size: 18px;
left: 50%;
bottom: -28px;
transform: translateX(-50%);
}
#OSM::after {
content: 'OSM'
}
#BingMaps::after {
content: 'BingMap'
}
}
</style>
更多推薦
如果不清楚 OpenLayers
是什么,可以閱讀: 『Vite + Vue3 + OpenLayers 起步』