Reputation: 516
Assigning the same view to multiple OpenLayers maps result in synchronized views which update across maps (e.g. when user pans or zooms). I want to have the view of maps synchronized, but with an offset. Is this still possible by re-using a view across the maps? Or do I have to handle the events myself?
And what is the difference between using the same view versus using the bindTo
method as described in the OpenLayers docs (https://openlayersbook.github.io/ch03-charting-the-map-class/example-05.html)?
Upvotes: 1
Views: 484
Reputation: 5039
bindTo
was removed in version 3.5.0 (current version is 4.6.4). So using it would force you to use an 2+ years old version of OpenLayers.
One-way binding on the other hand can easily be achieved with event listeners.
Two-way binding is quite difficult to achive, because you have to make sure not to create update-loops. If you place change listeners on both maps, they would repeatedly call each other.
You can easily offset the center position of the second map by fiddling with the event value.
var view = new ol.View({
center: [0, 0], zoom: 2
});
var view2 = new ol.View({
center: [0, 0], zoom: 2
});
var source = new ol.source.OSM();
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: source
})
],
target: 'map',
view: view
});
var map2 = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
target: 'map2',
view: view2
});
function updateView(event, viewRef){
let newValue = event.target.get(event.key);
if(event.key === 'center') {
// we need to transform the value, it comes in the wrong projection
newValue = ol.proj.transform(newValue , source.getProjection(), 'EPSG:3857');
// offset the value somehow here
}
viewRef.set(event.key, newValue);
}
view.on('change:resolution', function(event){
updateView(event, view2);
});
view.on('change:center', function(event){
updateView(event, view2);
});
.map{
max-height: 100px;
}
<link href="https://openlayers.org/en/v4.6.4/css/ol.css" rel="stylesheet"/>
<script src="https://openlayers.org/en/v4.6.4/build/ol-debug.js"></script>
<div id="map" class="map"></div>
<div id="map2" class="map"></div>
Upvotes: 2