Search code examples
javascriptopenlayersopenlayers-6

How to draw a lineString in Openlayers6


I have a map that uses a WMTS source and is using EPSG:25832 for the projection. I do not understand why it is so difficult for me to add a line between the 2 markers. It should be a line with multiple coordinates but I cant find any documentation on how to add a line. I am assuming that it should be a new vectorLayer with a lineString I will be adding, but the documentation is so hard to understand. Can someone point me in the right direction?

I have been looking at this example, but I don't think it is very clear what is going on. And I will be using data, not allowing the user to draw the line.

var map = new Map({
    target: 'map',
    layers: [
        new TileLayer({
            opacity: 0.7,
            source: new WMTS({
                crossOrigin: 'Anonymous',
                url: `https://kortforsyningen.kms.dk/topo_skaermkort_daempet?TICKET=${TOKEN}`,
                layer: 'dtk_skaermkort_daempet',
                matrixSet: 'View1',
                format: 'image/jpeg',
                tileGrid: tileGrid,
                style: 'default',
                size: SIZE
            })
        }),
        new VectorLayer({
            source: new VectorSource({
                features: [originMarker]
            }),
            style: new Style({
                image: new Icon({
                    anchor: [0.5, 1],
                    src: A_ICON,
                })
            })
        }),
        new VectorLayer({
            source: new VectorSource({
                features: [destinationMarker]
            }),
            style: new Style({
                image: new Icon({
                    anchor: [0.5, 1],
                    src: B_ICON,
                })
            })
        })
    ],
    view: new View({
        center: fromLonLat(centerPoint, 'EPSG:25832'),
        zoom: 3,
        resolutions: tileGrid.getResolutions(),
        projection: projection,
        extent: EXTENT
    })
});

Solution

  • To create a LineString feature joining two Point features

    new Feature(new LineString([
      originMarker.getGeometry().getCoordinates(),
      destination.getGeometry().getCoordinates()
    ]))
    

    then add it to a new layer, or to an existing vector source.