Reputation: 2431
I'm now overlaying some tile image maps on basemap, by using OpenLayers 4. But some layer data is not accurate, so feature positions of the layer are little shift from that of basemap. To avoid this, I want to show the layer little shift from original tile position... is it possible in OpenLayers 4?
Upvotes: 0
Views: 1125
Reputation: 5039
OpenLayers normally uses canvas rendering (you can tell it not to) and exposes hooks so that you can manipulate the rendering context.
The Layer Spy examples shows us how to do that. The API for can be found here, including a list of all the available methods. One is void ctx.translate(x, y);
The sample below has two base layer, of which one is offset by 50 pixel. Note that you might have to factor in the zoom level, if your offset is spatial and not just pixels (calculating the offset for the current zoom level is up to you).
const tileA = new ol.layer.Tile({
source: new ol.source.OSM(),
opacity: 1
});
const tileB = new ol.layer.Tile({
source: new ol.source.OSM(),
opacity: 0.5
});
// before rendering the layer, move it
tileB.on('precompose', function(event) {
var ctx = event.context;
// in case 1 pixel is not really 1 pixel, e.g iPhone
var pixelRatio = event.frameState.pixelRatio;
ctx.save();
ctx.translate(pixelRatio * 50, pixelRatio * 50);
});
// after rendering the layer, restore the canvas context,
// so that continous rendering cycles do not stack
tileB.on('postcompose', function(event) {
var ctx = event.context;
ctx.restore();
});
const map = new ol.Map({
target: document.getElementById('map'),
view: new ol.View({
center: ol.proj.fromLonLat([76.8512, 43.2220]),
zoom: 15
}),
layers: [ tileA, tileB ]
});
#map {
/* just for testing purposes */
width: 100%;
min-width: 240px;
max-width: 500px;
margin-top: 50px;
height: 200px;
}
<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"></div>
Upvotes: 1