user2254532
user2254532

Reputation: 2171

How to transform MapTile image to to view

I've created a tile set of an image using MapTiler. MapTiler generates a OL 2 script that centers the tiled image in the viewing window with the following code:

var map, layer;
var mapBounds = new OpenLayers.Bounds(0.000000, -9350.000000, 14450.000000, 0.000000);
var mapMinZoom = 0;
var mapMaxZoom = 6;
var mapMaxResolution = 1.000000;
var gridBounds = new OpenLayers.Bounds(0.000000, -9350.000000, 14450.000000, 0.000000);
function init() {
  var options = {
    controls: [],
    maxExtent : gridBounds,
    minResolution: mapMaxResolution,
    numZoomLevels: mapMaxZoom+1
  };
  map = new OpenLayers.Map('map', options);
  layer = new OpenLayers.Layer.XYZ( "MapTiler layer", "${z}/${x}/${y}.png", {
    transitionEffect: 'resize',
    tileSize: new OpenLayers.Size(256, 256),
    tileOrigin: new OpenLayers.LonLat(gridBounds.left, gridBounds.top)
  });
  map.addLayer(layer);
  map.zoomToExtent(mapBounds);

I want to use OL3 to display the tiled map but do not know how to implement equivalent OL3 methods to achieve this. Using the following script I can display the tiled image but I cannot figure out how to center the tiles to in the view.

map = new ol.Map({
  target: 'map',
  layers: [
    new ol.layer.Tile({
      source: new ol.source.OSM({
        url: map_path + '{z}/{x}/{y}.png'
      })
    })
  ],
  view: new ol.View({
    center: [0, 0],
    zoom: 2
  })
}); 

I've inspected the map extent which turns out to be:

-20037508.342789244,-20037508.342789244,20037508.342789244,20037508.342789244

My tiled image extent is given in the OL2 code, but I don't known how to use this information in OL3. I think it might have something to do with a transformation or fitExtent but without further direction, it seems I'm just guessing at what to do.

Upvotes: 0

Views: 953

Answers (1)

ahocevar
ahocevar

Reputation: 5648

You will have to create a pixel projection for this to work properly. Then you can use fit (replacement for the former fitExtent), as you already suspected, to zoom to the full extent of the image.

The whole OpenLayers 2 code translated to OpenLayers 3 would look like this:

var mapBounds = [0.000000, -9350.000000, 14450.000000, 0.000000];
var mapMaxZoom = 6;
var gridBounds = [0.000000, -9350.000000, 14450.000000, 0.000000];
var projection = new ol.proj.Projection({
  code: 'pixels',
  units: 'pixels',
  extent: gridBounds
});
var map = new ol.Map({
  target: 'map',
  view: new ol.View({
    extent: mapBounds,
    projection: projection
  })
});
var layer = new ol.layer.Tile({
  source: new ol.source.XYZ({
    url: '{z}/{x}/{y}.png',
    projection: projection,
    maxZoom: mapMaxZoom
  })
});
map.addLayer(layer);
map.getView().fit(mapBounds, map.getSize());

Upvotes: 1

Related Questions