1

I have a Geojson file and have successfully added new properties that comes from a CSV file. Unfortunately, I am not able to display the modified file in Leaflet. Any help is welcome! Here's my code:

<!DOCTYPE html>
<html>
<head>
    <title>add properties to geojson</title>
    <meta name=viewport content=width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no>
        <link rel=stylesheet href=https://unpkg.com/[email protected]/dist/leaflet.css integrity=sha256-kLaT2GOSpHechhsozzB+flnD+zUyjE2LlfWPgU04xyI= crossorigin= />
        <script src=https://unpkg.com/[email protected]/dist/leaflet.js integrity=sha256-WBkoXOwTeyKclOHuWtc+i2uENFpDZ9YPdf5Hf+D7ewM= crossorigin=></script>
    <style>
        body {
            padding: 0;
            margin: 0;
        }
        html, body, #map {
            height: 100%;
            width: 100%;
        }
     </style>
</head>
<body>
    <div id=map></div>
    <script>

//*** CSV-file ***
let KW24 = `wb,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z
02200,U,1,897,374,0,1271,463,1,17,446,1309,137,174,359,192,142,47,15,48,35,12,,17,30,50,51
02300,U,1,816,362,0,1178,446,1,5,441,1275,191,208,248,215,123,58,30,44,30,13,,5,11,42,57
02400,U,1,749,350,0,1099,348,2,8,340,974,92,178,296,99,84,7,22,41,16,16,,4,33,67,19`

//*** CSV to array of objects ***
    function csvToArray(str) {
    const headers = str.slice(0, str.indexOf("\n")).split(",");
    const rows = str.slice(str.indexOf("\n") + 1).split("\n");
    const arr = rows.map(function (row) {
      const values = row.split(",");
      const el = headers.reduce(function (object, header, index) {
        object[header] = values[index];
        return object;
      }, {});
      return el;
    });
    return arr;
  };
    
//*** Popup ***
    function fktPopup(f, l) {l.bindPopup('<pre>'+JSON.stringify(f.properties,null,' ').replace(/[\{\}"]/g,'')+'</pre>')};  

//*** function add properties to Geojson ***
        function featureJoinByProperty(fProps, dTable, joinKey) {
            var keyVal = fProps[joinKey];
            var match = {};
            for (var i = 0; i < dTable.length; i++) {
                if (dTable[i][joinKey] === keyVal) {
                    match = dTable[i];
                    for (key in match) {
                        if (!(key in fProps)) {
                            fProps[key] = match[key];
                        }
                    }
                }
            }
        }

//*** map ***
   let map = L.map("map").setView([51.05, 13.74], 15);
     
//*** baselayer ***
   L.tileLayer("https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_nolabels/{z}/{x}/{y}.png", {
        attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> &copy; <a href="https://carto.com/attribution/">CartoDB</a>',
    }).addTo(map);
        
//*** empty Geojson-layer ***
   let geojson = L.geoJSON(null, {onEachFeature: fktPopup});

//*** adress Geojson-file ***
     const varWB24DD  = 'https://kommisdd.dresden.de/net4/public/ogcapi/collections/L1565/items?limit=3';

//*** fetch Geojson-file ***
   fetch(varWB24DD)
    .then(function(response) {
        return response.json();
    })
    .then(function(data) {
                geojson.addData(data);

        const obj = csvToArray(KW24);
                geojson.eachLayer(function(layers) {
                    featureJoinByProperty(layers.feature.properties, obj, "wb");
                    console.log(layers.feature.properties);
                    console.log(layers);
                });
    })
        geojson.addTo(map);
    </script>
</body>
</html>
1
  • It's probable that we need to see the actual GeoJSON to see why it doesn't work rather than the code. Please edit your question with a small example that shows what your problem is, along with what the actual error message is rather than "it doesn't work".
    – Ian Turton
    Commented Jun 11 at 14:46

1 Answer 1

1

Problem is in the order of adding data to GeoJSON layer. Data is added when there are no additional properties yet. Popup content is created at the time when data is added to the layer. If you change layer feature properties later, that does not effect popup content.

All you have to do is to change order of adding additional properties to the GeoJSON. First add properties to GeoJSON object and then add data to GeoJSON layer.

Relevant part of the code could then look something like this (tested):

fetch(varWB24DD)
.then(function(response) {
  return response.json();
})
.then(function(data) {
  const obj = csvToArray(KW24);
  data.features.forEach(function(feature) {
    featureJoinByProperty(feature.properties, obj, "wb");
  });       
  geojson.addData(data);       
  geojson.addTo(map);
});

This is how popup looks like the:

enter image description here

1
  • Thank you very much! I have been pondering for hours, now it works wonderfully ...
    – RolfDD
    Commented Jun 12 at 20:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.