简体   繁体   中英

openlayers - how to center map by bounding box

I'm trying to center the map by given bounding box. On OpenLayers FAQ is even an example of it (with the swissProjection) but it just don't work. Looked around in some forums and just can't figure out how to make it work.

Maybe someone knows.

Here is the code:

var extent = [-9022321.0707,3022167.2243,-8849726.2608,3148441.1951];

var projection = new ol.proj.Projection({
  code: 'EPSG:3857',
  extent: extent,
  units: 'm'
});
ol.proj.addProjection(projection);

var map = new ol.Map({
  layers: [
    new ol.layer.Tile({
      source: new ol.source.OSM()
    })
  ],
  target: 'map',
  view: new ol.View({
    projection: projection,
    center: [0,0],
    zoom: 0
  })
});

Your code is correct but the center is out of range from your extent. There's two way to fix it.

First, set valid view center and level.

eg)

view: new ol.View({
  projection: projection,
  center: [-8936023.66575, 3085304.2097], // guess it's the center of extent
  zoom: 8 // whatever you want. 
}) 

Second, use View.fit instead setting extent on Projection .

var projection = new ol.proj.Projection({
  code: 'EPSG:3857',
  //extent: extent,
  units: 'm'
});
...
map.getView().fit(extent);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM