[GIS] GeoServer WMS layer won’t load on OpenLayers 5

openlayerswms

I was making some tests using Tiger products: I converted one .shp in a PostGIS database using shp2pgsql, then imported the db into GeoServer; the layer works fine with the preview provided by GeoServer.

But when I try to add this layer to a new map, it doesn't work: I obtain an empty map, as if there weren't any other layers. I tried to look for other solutions to the problem, but none worked for me because they're mainly related to previews versions of OL. I'm sure it's only related to my inexperience with OL and JS in general, but still.

Here is the link provided by the GeoServer preview:

http://localhost:8080/geoserver/Test/wms?service=WMS&version=1.1.0&request=GetMap&layers=Test:Mass&styles=&bbox=-73.5018768310547,41.228515625,-69.9055328369141,42.8950424194336&width=768&height=355&srs=EPSG:4269&format=application/openlayers#toggle

And here the script related to the map:

    const wmsBaseLayer = new ol.layer.Tile({
        source: new ol.source.OSM()
    });

    const wmsMassLayer = new ol.source.TileWMS({
        url: 'http://localhost:8080/geoserver/Test/wms',
        params: {
            'LAYERS' : 'Test:Mass',
            'TILED' : true,
        },
        serverType: 'geoserver',
        projection: 'EPSG:4269'
    });

    const view = new ol.View({
            center:  ol.proj.fromLonLat([-71.0589, 42.3601]),
            zoom: 8,
    });     

    const map = new ol.Map({
        target: 'map',
        layers: [ wmsBaseLayer, wmsMassLayer],
        view: view
    });

**Edit #1
I forgot to mention that I'm using a Docker architecture for my test. One container hosts GeoServer and one PostGIS. The containers are linked and the connection between them and the localhost works. I also tried to import the layer through both containers (as PostGIS db or as a WMS layer) in QGIS and it all works well. I figured that the problem is related to OL.

I made some digging and these are the errors showed in the Web Developer Console (I use Firefox)

TypeError: t.getLayerStatesArray is not a function
oo</e.prototype.getLayerStatesArray/<     Group.js:209
U</e.prototype.forEach                    Collection.js:137
oo</e.prototype.getLayerStatesArray       Group.js:208
lo</e.prototype.renderFrame_              PluggableMap.js:1198
e/this.animationDelay_<                   PluggableMap.js:191
<anonymous> self-hosted:975:17 

I also checked the Network tab, and it doesn't show any request to the WMS service (as instead happens in the GeoServer preview).

Best Answer

OpenLayers needs to make the request for the WMS image in the projection of your map, by adding the line projection: 'EPSG:4269' to your layer you are over ruling it but it doesn't know and so uses the bounding box of the map which will be in meters (EPSG:3857 is the default map projection) so your map is drawn just very small and down by the equator.