Search code examples
openlayersopenlayers-5

OL: changing projection (using Proj4) does not show geojson layer (despite setVisible is true)


Using a layerswitcher the visibility of several GEOJSON-layers can be toggled. E.g. layer A is visible (so setVisible is true) on a map with projection 3857. When I change the projection to e.g. 4326 (or another one by using Proj4), I get the new map showing this new projection but my layer A is not visible. In the layerswitcher this layer A is still checked. Even check/uncheck the checkbox does not do anything. And when I do a getVisible on layer A it still returns 'true'.

If I change the map-projection to the original one (3857) my layer is visible.

How can I get layer A to stay visible even if I change my projection?


Solution

  • Vector layers (and overlays) don't automatically reproject. If you change the view projection you also need to transform vectors and overlays to the new projection. This code will work as long as you are not using layer groups.

    map.getOverlays().getArray().forEach(function(overlay){
        if (overlay.getPosition()) {
            overlay.setPosition(ol.proj.transform(overlay.getPosition(), oldProjection, newProjection));
        }
    });
    
    map.getLayers().getArray().forEach(function(layer){
        if (layer.getSource() && layer.getSource().forEachFeature) {
            layer.getSource().forEachFeature(function(feature){
                feature.getGeometry().transform(oldProjection, newProjection);
            });
        }
    });