Search code examples
nullleafletpopup

Leaflet Popup with null values and unknown properties


When a user drag and drop a CSV point file into the Leaflet map, there is no way to see what kind of properties exist beforehand. So I need to find a solution, when user click a point on the map, only properties with values should be shown.

I been using below sample that works fine but only when the properties are known as shown. How can this be changed to show any properties with values but don't show properties with null or empty values?

    onEachFeature: function(feature, layer) {
    
    var popupText = '';
    
    popupText += (feature.properties.typeId) ? 'Concept:\u00A0<b>' + feature.properties.typeId: ''
    
    popupText += (feature.properties.branchId) ? '</b><br>BranchID:\u00A0<b>' + feature.properties.blomId: '';
    
    popupText += (feature.properties.name) ? '</b><br>Name:\u00A0<b>' + feature.properties.name: '';

    popupText += (feature.properties.streetName) ? '<br></b>StreetName:\u00A0<b>' + feature.properties.streetName.toUpperCase(): '';
    
    popupText += (feature.properties.streetNumber) ? '\u00A0</b><b>' + feature.properties.streetNumber: '';
    
    popupText += (feature.properties.streetLetter) ? '\u00A0</b><b>' + feature.properties.streetLetter: '';
    
    popupText += (feature.properties.postalCode) ? '</b><br>PostalCode, City:\u00A0<b>' + feature.properties.postalCode: '';
    
    popupText += (feature.properties.city) ? '</b>,\u00A0<b>' + feature.properties.city: '';
            

  layer.bindPopup(popupText, {
    closeButton: true,
    offset: L.point(0, -20)
  });
  layer.on('click', function() {
    layer.openPopup();
  });
},

Solution

  • Loop through all properties:

    for(var prop in feature.properties){
       if(feature.properties[prop]){
          popupText += prop + ": "+feature.properties[prop]+"<br>";
       }
    }