我使用了openlayers.org中共享视图示例的调整版本:https://openlayers.org/en/latest/examples/side-by-side.html
var layer = new TileLayer({
source: new OSM()
});
window['view1'] = new ol.View({
center: [0, 0],
zoom: 1
});
window['view2'] = new ol.View({
center: [0, 0],
zoom: 1
});
window['map1'] = new ol.Map ({
target: 'map1',
layers: [layer],
view: window['view1']
});
window['map2'] = new ol.Map({
target: 'map2',
layers: [layer],
view: window['view2']
});
window['map1'].addEventListener('change:resolution', function
(evt) {
window['view1'] = window['view2'];
window['map1'].setView(window['view1']);
}, false);
window['map2'].addEventListener('change:resolution', function
(evt) {
window['view2'] = window['view1'];
window['map2'].setView(window['view2']);
}, false);
此后,我如何正确解开这些“新的”平等观点? (可能答案很简单,但现在让我头疼)
PS:我使用全局变量(例如window ['map2']),因为我需要能够绑定和取消绑定多个地图。
答案 0 :(得分:2)
我认为您不需要听更改,如果地图共享一个视图,它们会自动同步。
将一个地图的视图设置为另一个地图的视图将开始同步。给其中一个地图一个新视图(最初基于它所共享的视图的状态)将中断同步。
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/css/ol.css" type="text/css">
<style>
html, body, .map {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
.map1 {
width: 50%;
height: 40%;
}
.map2 {
width: 50%;
height: 40%;
}
</style>
<script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script>
<title>OpenLayers example</title>
</head>
<body>
<div id="map1" class="map1"></div>
<input type="submit" onclick="sync1()" value="Sync with 1">
<input type="submit" onclick="unsync()" value="Unsync">
<input type="submit" onclick="sync2()" value="Sync with 2">
<div id="map2" class="map2"></div>
<script type="text/javascript">
var layer = new ol.layer.Tile({
source: new ol.source.OSM()
});
var map1 = new ol.Map({
target: 'map1',
layers: [layer],
view: new ol.View({
center: [0, 0],
zoom: 1
})
});
var map2 = new ol.Map({
target: 'map2',
layers: [layer],
view: new ol.View({
center: [0, 0],
zoom: 1
})
});
function sync1() {
map2.setView(map1.getView());
}
function sync2() {
map1.setView(map2.getView());
}
function unsync() {
map2.setView(new ol.View({
projection: map2.getView().getProjection(),
center: map2.getView().getCenter(),
resolution: map2.getView().getResolution(),
rotation: map2.getView().getRotation(),
maxZoom: map2.getView().getMaxZoom(),
minZoom: map2.getView().getMinZoom()
}));
}
</script>
</body>
</html>