I'm trying to center a tile layer in OpenLayers 3 but it seems to ignore the center attribute of the map. I know the height and width of the original big image if it helps.
here is my code (also available in jsbin ):
<!DOCTYPE html> <html> <head> <title>XYZ</title> <link rel="stylesheet" href="http://openlayers.org/en/v3.13.0/css/ol.css" type="text/css"> <script src="http://openlayers.org/en/v3.13.0/build/ol.js"></script> </head> <body> <div id="map" class="map" style="width: 100%; height: 500px; border: 1px solid #000;"></div> <script> var layer = new ol.layer.Tile({ source: new ol.source.XYZ({ url: 'http://thinker.cloudapp.net/test/{z}-{x}-{y}.png', wrapX: false }) }); var map = new ol.Map({ target: 'map', layers: [layer], view: new ol.View({ center: [0,0], zoom: 2 }) }); </script> </body> </html>
How can I center the map, and if possible zoom to fit screen width or height?
Update:
I've updated the code and added a jsbin link too. The original image size is 4864x3328 if it helps.
I think this has to do with projection and setting the grid size in pixels, but i couldn't find anything helpful.
My first answer isn't a good one. Go this way:
var pixelProj = new ol.proj.Projection({
code: 'pixel',
units: 'pixels',
extent: [0, 0, 4864, 3328]
});
var layer = new ol.layer.Tile({
source: new ol.source.XYZ({
projection: pixelProj,
wrapX: false,
url: 'http://thinker.cloudapp.net/test/{z}-{x}-{y}.png'
})
});
var map = new ol.Map({
target: 'map',
layers: [layer],
view: new ol.View({
zoom: 2,
center: [1364, 2400],
projection: pixelProj
})
});
http://jsfiddle.net/jonataswalker/6f233kLy/
To achieve this you'll need to wait until all tiles are loaded, then get the
layer extent , finally
fit the view to this extent.
var tile_loading = 0, tile_loaded = 0; yourTileLayer.getSource().on('tileloadstart', function(evt){ ++tile_loading; }); yourTileLayer.getSource().on('tileloadend', function(evt){ ++tile_loaded; if(tile_loaded === tile_loading){ tile_loading = 0; tile_loaded = 0; // put some logic here to do just once // all tiles are loaded - get the layer extent var extent = yourTileLayer.getExtent(); map.getView().fit(extent, map.getSize()); } });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.