I would like to retrieve the extent of an ImageWMS layer in OpenLayers dynamically from the BBOX param.
I would use it for (e.g.) zooming to layers'extent.
At the moment, my code looks like this:
var layer2 = new ol.layer.Image({
title: 'zone',
visible: false,
source: wmsSource2,
extent: [952014.59,5571269.68,1272301.10,5862273.22]
});
...
// in the layers tab, zoom map to layer when zoom icon is clicked
$('.fa-search').on('click', function() {
var layer = layer2;
view.fit(layer.getExtent(), {
duration:1000
});
});
As you can see, now I am defining the extent in the layer
variable.
Rather, I would love to get it from the WMS itself, instead of re-defining it again in my js.
From the documentation, I see I can set the BBOX WMS parameter in the ol.source.ImageWMS params
option. Better, it's automagically set by OL4!
So, the question is: how would I retrieve the BBOX from this parameter if possible? I am using Mapserver as WMS server if that matters.
I ended up following the example at this site.
It's been a bit tricky but I hope it will worth the work.
Basically, with the below code I am now able to retrieve the layer extent (at least for one of them as of now) by parsing the WMS GetCapabilities rather than hardcoding it in the js.
This way, if my WMS layer will change, I don't have to update the js. With the same parser I'll hopefully loop through each layer to automagically insert them in my openlayers code (it will be one of the next improvements of my project).
// WMS PARSER (https://bl.ocks.org/ThomasG77/5f9e62d3adeb5602d230a6eacbb9c443)
var base_url = 'https://localhost/cgi-bin/mapserver/mapserv.exe?map=C:\\DATI\\git\\shire\\\mapfile\\\mapfile\\mymapWINDOWS.map&'
var parser = new ol.format.WMSCapabilities();
// Parse WMS Capabilities to retrieve layer extent
fetch(base_url + 'SERVICE=WMS&VERSION=1.3.0&REQUEST=GetCapabilities').then(function(response) {
return response.text();
}).then(function(text) {
var result = parser.read(text);
var extent = result.Capability.Layer.Layer.find(l => l.Name === 'zone').EX_GeographicBoundingBox;
var extent_3857 = ol.proj.transformExtent(extent, 'EPSG:4326', 'EPSG:3857')
...
var layer2 = new ol.layer.Image({
title: 'zone',
visible: false,
source: wmsSource2,
extent: extent_3857
});
...
// in the layers tab, zoom map to layer when zoom icon is clicked
$('.fa-search').on('click', function() {
var layer = layer2;
view.fit(layer.getExtent(), {
duration: 1000
});
});