Search code examples
javascriptopenlayersgeoserver

How can I set a custom SRS to a layer with openLayers?


The thing is that i have a DB with a list of zones, they are stored in a table with a data type column "geometry". So i want to load some zones and then show them in the map. I manage to load the zones and show them in the map, but they are not in the place i want them to be, they always appear in the gulf of guinea that is the center of a non projection map. Before trying to load some zones the map was loading all zones at the same time with a geoServer layer. So my question is, how can I set a custom projection to a vectorLayer? and if i can't do it, how can i create automatically layers with an specified part of de DB?

I'm using postgres DB with postgis.

This is the code i've before:

ar wmsSource = new ImageWMS({
            url: 'URL TO GEOSERVER',
            params: {
                Layers: "LAYER IN GEOSERVER" ,
                SRS: 'EPSG:4258'
            },
            ratio: 2,
            serverType: 'geoserver'
        });

        var mainMap = new ImageLayer({
            opacity: 0.3,
            source: wmsSource,
            maxResolution: 500
        });
this.map = new Map({
            layers: [
                new TileLayer({
                    preload: Infinity,
                    source: new OSM()
                }),
                mainMap
            ]
            ,
            target: 'map',
});

This is the code i've trying to make work:

 var vectorSource = new VectorSource({
            params: {
                CRS: 'EPSG:4258'
            },
            ratio: 2,
            serverType: 'geoserver'
        });
        var z;
        for(z of nextProps.zoneState.zona){
            var f = new Feature({
                geometry: new MultiPolygon(z.geom.coordinates) 
        });
            vectorSource.addFeature(f);
        }

        var vectorLayer = new VectorLayer({
            source: vectorSource, style:new Style({
                stroke: new Stroke({
                    color: 'red',
                    width: 3
                })
            })
        });
var map = new Map({
            layers: [
            new TileLayer({
                source: new OSM()
            }),
            vectorLayer
            ],
            target: 'map'
});

Solution

  • If you are using VectorSource with url and format options some formats such as GeoJSON can be transformed to view projections as they are loaded. But if you are adding features in your own code you also need to transform the geometry

    geometry: new MultiPolygon(z.geom.coordinates).transform('EPSG:4258', 'EPSG:3857')