Prevent panning and zooming beyond map edges in OpenLayers 4.6.4

I've run into this situation and used the following code:

Just after map is initialized:

const nc_array = map.getView().calculateExtent(map.getSize()); const nc_s = nc_array[1]; const nc_w = nc_array[0]; const nc_n = nc_array[3]; const nc_e = nc_array[2];

map.on('moveend', function() { /* uses nc_array data (nc_w, nc_s, nc_e, nc_n) from initial map setup*/ var ext_array = map.getView().calculateExtent(map.getSize()); var ext_s = ext_array[1]; var ext_w = ext_array[0]; var ext_n = ext_array[3]; var ext_e = ext_array[2]; if(ext_s < nc_s) { var now_s = view.getZoom(); view.fit([ext_w, nc_s, ext_e, ext_n+(nc_s-ext_s)]); map.getView().setZoom(now_s); } if(ext_w < nc_w) { var now_w = view.getZoom(); view.fit([nc_w, ext_s, ext_e+(nc_w-ext_w), ext_n]); map.getView().setZoom(now_w); } if(ext_n > nc_n) { var now_n = view.getZoom(); view.fit([ext_w, ext_s-(ext_n-nc_n), ext_e, nc_n]); map.getView().setZoom(now_n); } if(ext_e > nc_e) { var now_e = view.getZoom(); view.fit([ext_w-(ext_e-nc_e), ext_s, nc_e, ext_n]); map.getView().setZoom(now_e); } });

Hope this helps someone.

Tags:

Openlayers