Only show filled attributes in leaflet popups (and

2019-09-18 02:16发布

问题:

My leaflet map shows polygons from a GeoJSON file. This file has several attributes (attribute_1, attribute_2, etc.). However, some are filled with text and some are empty.

How can I only show the attributes which are filled with text in my popup and not the empty ones?

Using my code beneath every attribute is shown and if it's empty "null" is shown in the popup:

// Integrate GeoJSON and style polygons
  $.getJSON("klimagutachten_2001.geojson",function(klimagutachten){
    L.geoJson( klimagutachten, {
        style: function(feature){
            return {
                color: "#e60000",
                weight: 4,
                fillColor: "#e60000",
                fillOpacity: .3
            };
        },

// Call popup
        onEachFeature: function( feature, layer ){
            layer.bindPopup("<strong> Attribute 1: \"" + feature.properties.attribute_1 + " and the second attribute is: " + feature.properties.attribute_2)
        }                                                                                                       
    }).addTo(map);
  });

回答1:

Create a validation:

onEachFeature: function( feature, layer ){

var text = "";

if (!feature.properties.attribute_1) {
    text += feature.properties.attribute_1 +" "; 
}
if (!feature.properties.attribute_2) {
    text += feature.properties.attribute_2 +" "; 
}
layer.bindPopup(text);

} 


回答2:

I solved the question using a simple if...else statement. The additions are highlighted in bold:

// Integrate GeoJSON and style polygons
  $.getJSON("klimagutachten_2001.geojson",function(klimagutachten){
    L.geoJson( klimagutachten, {
        style: function(feature){
            return {
                color: "#e60000",
                weight: 4,
                fillColor: "#e60000",
                fillOpacity: .3
            };
        },

// Call popup
        onEachFeature: function( feature, layer ){
        var attribute_1 = feature.properties.attribute_1;
        if (attribute_1 == null) {
            attribute_1 = "";
        } else {
            var attribute_1 = feature.properties.attribute_1;
        };

            layer.bindPopup("<strong> Attribute 1: \"" + attribute_1 + " and the second attribute is: " + feature.properties.attribute_2)
        }   
    }).addTo(map);
  });