vectoropenlayersopenlayers-8

OpenLayers: display the new features and clear the old features (vector source), when map clicked again?


I have a map with polygon displayed highlighted in red with the first click on the map. When another polygon is clicked, (features prop changes), new features are rendered as expected and they appear on map alongside the old ones. After attempting to remove the old features by calling vectorLayer.getSource().removeFeature(feature); and before adding the new features to the source, vectorLayer.GetSource().GetFeatures(). I've tried creating a whole new source and even tried creating a whole new layer without success.

Please steps & code below:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/ol@v8.2.0/ol.css"
      type="text/css"
    />
    <style>
      html,
      body {
        height: 100%;
        margin: 0;
      }
      #map {
        width: 100%;
        height: 100%;
      }
    </style>
    <script src="https://cdn.jsdelivr.net/npm/ol@v8.2.0/dist/ol.js"></script>
  </head>
  <body>
    <div id="map" class="map"></div>
    <script>
      var map = new ol.Map({
        target: "map",
        layers: [
          new ol.layer.Tile({
            source: new ol.source.OSM(),
          }),
        ],
        view: new ol.View({
          projection: "EPSG:4326",
          center: [7.07999451721341, 51.16739903438118],
          zoom: 17,
        }),
      });


      map.on("singleclick", function (evt) {
        const coordinate = evt.coordinate;

        var tol ='your tolerance';
        var bbox = 'your bounding box';

        var url =
          'your url'+bbox;

        fetch(url)
          .then((response) => response.text())
          .then((text) => {
            const source = new ol.source.Vector({
              features: new ol.format.WFS().readFeatures(text, {
                dataProjection: "EPSG:4326",
                featureProjection: map.getView().getProjection(),
              }),
            });
            map.addLayer(
              new ol.layer.Vector({
                source: source,
                style: new ol.style.Style({
                  stroke: new ol.style.Stroke({
                    color: "red",
                    width: 5,
                  }),
                }),
              })
            );

            map.getView().setCenter(source.getExtent());

          });
      });
    </script>
  </body>
</html>

Problem: is there method (best strategy), that the ol-source is always cleared before new features are added with new click. An example would be greatly appreciated. Thank you!


Solution

  • Easiest way would be to clear the source before adding new features

      const source = new ol.source.Vector();
    
      map.addLayer(
        new ol.layer.Vector({
          source: source,
          style: new ol.style.Style({
            stroke: new ol.style.Stroke({
              color: "red",
              width: 5,
            }),
          }),
        })
      );
    
      map.on("singleclick", function (evt) {
        const coordinate = evt.coordinate;
    
        var tol = 0.000001;
        var bbox = [evt.coordinate[0] - tol,evt.coordinate[1] - tol,evt.coordinate[0] + parseInt(tol),evt.coordinate[1] + parseInt(tol),];
    
        var url =
          "https://geoportal.solingen.de/SG_WFS2/service.svc/get?service=wfs&request=GetFeature&version=1.1.0&format=GML2&typename=Gebaeude_Photovoltaik_2016" +
          "&srsName=EPSG:4326&bbox=" +bbox;
    
        fetch(url)
          .then((response) => response.text())
          .then((text) => {
            const features = new ol.format.WFS().readFeatures(text, {
              dataProjection: "EPSG:4326",
              featureProjection: map.getView().getProjection(),
            });
            source.clear();
            source.addFeatures(features);
    
            map.getView().setCenter(source.getExtent());
    
          });
      });