I have a simple openlayers 4 map that calls an OSM base layer, plus a custom XYZ tile layer stored on my server:

var center = ol.proj.fromLonLat([-123.0, 44.95]);

var basemap = new ol.layer.Tile({
  source: new ol.source.OSM() 

var Salem = new ol.layer.Tile({ 
  source: new ol.source.XYZ({ 
    url: "http://ecotopia.today/cascadia/Tiles/PDX/{z}/{x}/{y}.png"}),
    minResolution: 0,
    maxResolution: 16000 });

var map = new ol.Map({
  layers: [ basemap, Salem ],
  target: 'map',
  view: new ol.View({
  center: center,
  resolution: 45 })

By setting the center and resolution, I can make a particular feature from the custom layer fit perfectly within the viewport of a laptop with a 1366x768 screen (it's the city of Salem, Oregon, working example here). However, on a larger screen there will be lots more space around the feature, and on a smaller screen part of it will be cut, both of which I don't want. I realize I could set an extent or do a constrain center, but I want the user to be able to move freely through the whole map. It is only on the initial view that the feature should be correctly framed. Is there a way to set up a listener that gets the size of the user's viewport and then dynamically adjusts the resolution so as to correctly frame the feature when it first loads? Or is there any other strategy that achieves the same effect?

I made a jsfiddle here. Since my skills are limited, it would be great to see a complete piece of code or a working example.


You will want to use the view fit method, passing the desired extent. The sample page allows testing some of the parameters.

You can put the following code at the end of your JSFidle code

var pt1 = ol.proj.fromLonLat([-123.0, 45.05]);
var pt2 = ol.proj.fromLonLat([-122.92 , 44.85]);
var ext = ol.extent.boundingExtent([pt1, pt2]);

  • That's it, perfect. I saw that example page but often I find it too hard to pull what I need out of a complex array of variable parameters. Your code is crystal clear. For anyone who wants to play around with it I've updated the fiddle: jsfiddle.net/Brian393/5tu0j673/23 Mar 16 '18 at 4:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.