问题
I have used an adjusted version of the shared views example from 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);
How do I properly unbind these 'new' equal views afterwards? (probably the answer is very simple, but it has given me headaches right now)
P.S: I use the global variable (e.g. window['map2']) because I need to be able to bind and unbind multiple Maps.
回答1:
I don't think you need to listen for changes, if maps share a view they synchronise automatically.
Setting the view of one map to the view of the other will start synchronisation. Giving one of the maps a new view (initially based on the state of the view it shared) will break synchronisation.
<!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>
来源:https://stackoverflow.com/questions/53838791/openlayers-shared-views-side-by-side-how-to-properly-unbind-them