Fixed SVG Layer Position on Open Layers Map

Viewed 45

I have a map with multiple Layers. One of them shall project an SVG on the map, indicating certain regions (if not obvious, it's the red area in the images). I got this working on the default zoom level.

enter image description here

But as soon as I change the zoom in any direction, the SVG layer just moves too much in a direction depending on where I initiate the zoom change.

enter image description here

This is the relevant code I have:

//Map init
    var mapcenter = ol.proj.fromLonLat([10.615219, 51.799502]);
    var layers = [];
    var map = new ol.Map({
        target: 'map',
        layers: [
            new ol.layer.Tile({
                source: new ol.source.OSM()
            })
        ],
        view: new ol.View({
            center: mapcenter,
            zoom: 9.5
        })
    });

//SVG init
    const svgContainer = document.createElement('div');
    const xhr = new XMLHttpRequest();
    xhr.open('GET', '/shared/harzregionen.svg');
    xhr.addEventListener('load', function () {
      const svg = xhr.responseXML.documentElement;
      svgContainer.ownerDocument.importNode(svg);
      svgContainer.appendChild(svg);
    });
    xhr.send();

    const width = 350;
    const height = 0;
    const svgResolution = 360 / width;
    svgContainer.style.width = width + 'px';
    svgContainer.style.height = height + 'px';
    svgContainer.className = 'svg-layer';

//SVG Layer
    map.addLayer(
        new ol.layer.Vector({
            render: function (frameState) {
                const scale = svgResolution / frameState.viewState.resolution;
                const center = frameState.viewState.center;
                const size = frameState.size;
                const cssTransform = ol.transform.composeCssTransform(
                    300,
                    120,
                    480 / frameState.viewState.resolution,
                    480 / frameState.viewState.resolution,
                    frameState.viewState.rotation,
                    -(center[0] - mapcenter[0]) / 420, //These values were kinda
                    (center[1] - mapcenter[1]) / 250 //trial and error for default zoom
                );
                svgContainer.style.transform = cssTransform;
                svgContainer.style.opacity = this.getOpacity();
                return svgContainer;
            }
        })
    );

I'm pretty sure I have to use a certain formula to calculate the values in composeCssTransform but it feels like there should be an easy way to do it instead of trial and error until it somewhat works.

So, my question is: Is there an easy way to lock an SVG layer to a set position on the world map like the layers with markers?

0 Answers
Related