温馨提示:本文所用OpenLayers版本为6.9.0
解决方案
一开始的想法是,一侧地图拖动时动态更新另一侧地图的Center,但是API没找见实时拖动的move事件,postrender事件可以实现但是影响效率,以下为实现方法,有兴趣的可以试试,但不建议使用。
function togetherMove() {
allMaps[0].on("postrender", function (e) {
var c0 = allMaps[0].getView().getCenter();
var z0 = allMaps[0].getView().getZoom();
if (allMaps[1]) {
allMaps[1].getView().setCenter(c0, z0);
allMaps[1].getView().setZoom(z0);
}
});
if (allMaps[1])
allMaps[1].on("postrender", function (e) {
var c1 = allMaps[1].getView().getCenter();
var z1 = allMaps[1].getView().getZoom();
allMaps[0].getView().setCenter(c1, z1);
allMaps[0].getView().setZoom(z1);
});
}
后来发现,两个map共用一个view即可实现联动
全部代码
<template>
<div id="mapContainer"></div>
<div id="mapContainer2"></div>
</template>
<script>
import "ol/ol.css";
import {
Map, View } from "ol";
import TileLayer from "ol/layer/Tile";
import OSM from "ol/source/OSM";
import {
onMounted } from "@vue/runtime-core";
export default {
setup() {
let view = new View({
projection: "EPSG:4326",
center: [108.961029, 34.208386],
zoom: 12,
});
onMounted(() => {
let map = new Map({
target: "mapContainer",
layers: [
new TileLayer({
source: new OSM(),
}),
],
view: view,
});
let map2 = new Map({
target: "mapContainer2",
layers: [
new TileLayer({
source: new OSM(),
}),
],
view: view,
});
});
},
};
</script>
<style>
#mapContainer {
width: 50%;
height: 100%;
left: 0;
bottom: 0;
position: absolute;
}
#mapContainer2 {
width: 50%;
height: 100%;
right: 0;
bottom: 0;
position: absolute;
}
</style>