When I create a layer using a vector source I can force the map to zoom to the layer using
//stuff including setting up defaultStyle
var vectorSource = new ol.source.GeoJSON({ url: geoJsonUrl, projection: 'EPSG:3857', extractStyles: false });
var vectorLayer = new ol.layer.Vector({ source: vectorSource, style: defaultStyle });
//stuff
vectorLayer.addEventListener("change", function () {
map.getView().fitExtent(vectorSource.getExtent(), map.getSize());
}
This works well for me so I'm trying to replicate it with my WMS layer. The layer and source are defined as:
//stuff including setting up params and geoserverRoot
var wmsImageSource = new ol.source.ImageWMS({ url: geoserverRoot + 'wms', params: params });
var wmsImageLayer = new ol.layer.Image({ opacity: 0.3, source: wmsImageSource });
An ImageWMS source doesn't have a getExtent() method (unlike vector sources such as a GeoJSON source), but an Image layer does. So I tried to replicate the way I zoom vector sources with:
wmsImageLayer.addEventListener("change", function () {
alert('change');
map.getView().fitExtent(wmsImage.getExtent(), map.getSize());
});
However, the alert doesn't trigger. I have no idea why this is the case.
What is the best way to automatically zoom into an image layer produced by GeoServer? Additionally, why does the change event not fire for the image layer?
EDIT: I tried using GetCapabilities as per advice from user30184 My layer is generated from a parametrized PostGIS view and the URL I used was:
/geoserver/wms?service=WMS&request=GetCapabilities&layers=areas_for_type&viewparams=typecode:AdministrativeWard
This gives an XML response including:
<EX_GeographicBoundingBox>
<westBoundLongitude>-1.0</westBoundLongitude>
<eastBoundLongitude>0.0</eastBoundLongitude>
<southBoundLatitude>-1.0</southBoundLatitude>
<northBoundLatitude>0.0</northBoundLatitude>
</EX_GeographicBoundingBox>
<BoundingBox CRS="CRS:84" minx="-1.0" miny="-1.0" maxx="0.0" maxy="0.0"/>
<BoundingBox CRS="EPSG:4326" minx="-1.0" miny="-1.0" maxx="0.0" maxy="0.0"/>
so the BB for the passed in parameter is not being calculated.