Search code examples
javascriptleafletgeojson

How to hide a text property in popup when it's not filled in Leaflet?


I have geoJson layer:

var test_layer = {
    "type": "FeatureCollection",
    "crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },                                                                         
    "features": [{ 
        "type": "Feature", 
        "properties": { 
            "name": "Name 1",
            "description": "Desc 1", 
        "geometry": { 
        "type": "Point", 
        "coordinates": [ 
        72.6, 44.3]
        }
        }]
    }

and pop-up function:

onEachFeature: function (feature, layer) {
        var popupContent = "<div class=popup><b>Object's name: </b>" + feature.properties.name + "<br /><b>Object's description: </b>" + feature.properties.description</p>";
        layer.bindPopup(popupContent);
            }

Not all of my objects have description. If I click on a point without description, in the popup window I can see:

Description: undefined

What should I change to get description's field hidden in a popup, when value is empty or deleted?


Solution

  • Try this:

     onEachFeature: function (feature, layer) {    
          var popupContent = "<div class=popup><b>Object's name: </b>" + feature.properties.name;
          if(typeof(feature.properties.description) !== 'undefined'){
              popupContent += "<br /><b>Object's description: </b>" + feature.properties.description+"</p>"
          }
    
            layer.bindPopup(popupContent);
          }