Home > Back-end >  Data duplication on click on the WMS
Data duplication on click on the WMS

Time:02-22

When the user click for the first time on the map, he can see the related information. But if he click again, the informations are duplicated as you can see on the image below.

enter image description here

I expect that the old information is substitute with the newest. For handle this request I've developed the function below:

function getElementInfo(elementID, layerName, layerTitle){
  map.on('singleclick', function (event) {
    var viewResolution = view.getResolution();
    var coordinates = event.coordinate;
    var epsg = 'EPSG:3857';
    var params = {
        'INFO_FORMAT': 'application/json'
      };
    var url = layerName.getSource().getFeatureInfoUrl(
      coordinates,
      viewResolution,
      epsg,
      params,
    );

    async function getFeatureProperties() {
      try {
        var response = await fetch(url);
        if (!response.ok) {
          throw new Error(`HTTP error!\n Status: ${response.status}\n Type: ${response.type}\n URL: ${response.url}`);
        } else {
          var data = await response.text();
          var json = JSON.parse(data).features[0].properties;

          var tableHeadContents = '<thead>'
            '</thead>';
          var tableHead = $(tableHeadContents).attr("id","thead");
          $("#" elementID).append(tableHead);
          var tableBodyContents = '<tbody></tbody>';
          var tableBody = $(tableBodyContents).attr("id","tbody");
          $("#" elementID).append(tableBody);
          for (items in json) {
            key = items;
            value = json[items];
            tableRow = '<tr><td >'   key   '</td><td >'   value   '</td></tr>';
            $("tbody").append(tableRow);
          }

        }
      } catch (e) {
        console.log(e);
      }
    }
    getFeatureProperties();
  });
};

I haven't strong skills with Javascript and probably there is an error here but I can't see it.

I call the function simply adding it after a TileWMS:

getElementInfo('onclickinfo35', wms35, 'NDVI Campania 20150807');

And the informations appears inside a simple table:

<table id="onclickinfo35"></table>

CodePudding user response:

The reason why you are getting more and more values/rows in your table for every click, is because you don't clear the table before adding data.

You need to call $("#" elementID).html(); before $("#" elementID).append(tableHead);

  • Related