Search code examples
javascriptopenlayers

OpenLayers overlapping LineStrings issue


I have one set of coordinates from which I create 2 LineStrings

// global variables, I have previously defined map
let route = null;
let routeFeature = null;
let routeOverlay = null;
let routeOverlayFeatur = null;

My main LineString

function createMainRoute(coordinates) {
   route = new LineString(coordinates);

   routeFeature = new Feature({ geometry: route });

   routeFeature.setStyle(styles.mainRoute);

   const routeLayer = new VectorLayer({
     source: new VectorSource({
        features: [routeFeature],
     }),
   });
   
   map.addLayer(routeLayer);
}

My second LineString with the exact coordinates

function createMainRouteOverlay(coordinates) {
   routeOverlay = new LineString(coordinates);

   routeOverlayFeature = new Feature({ geometry: routeOverlay });

   routeOverlayFeature.setStyle(styles.routeOverlay);

   const routeOverlayLayer = new VectorLayer({
     source: new VectorSource({
        features: [routeOverlayFeature],
     }),
   });
   
   map.addLayer(routeOverlayLayer );
}

Now I have a function that draws these 2 lines, this function is called when I get initial data from server

function init(coordinates) {
   createMainRoute(coordinates);
   createMainRouteOverlay(coordinates);
}

Goal is that I want to modify coordinates on the overlay line like the coordinates, style and so on without loosing track of the main route, but they are at the start the same.

Now I have a function that will dynamically change coordinates set of the overlay line. This function is called when the external data is changed.

function readjust(newCoordinates) {
   routeOverlayFeature.getGeomety().setCoordinates(newCoordinates)
}

The problem here is that when I call readjust(), nothing happens on the map, line stays the same with these new coordinates, but when I comment out createMainRoute() from the init function, meaning i only have one line and just call readjust(), line is updated with the new data. Does anyone knows what is the issue here? Is something like this not supported or do I need to set some property to allow this? I don't get why they are in conflict when they are 2 separated variables and only one is updated. Any help is appreciated


Solution

  • Your features are sharing the same geometry

    routeOverlayFeature = new Feature({ geometry: route });
    

    should be

    routeOverlayFeature = new Feature({ geometry: routeOverlay });