Only show filled attributes in leaflet popups (and

2019-09-18 02:12发布

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);
  });

2条回答
来,给爷笑一个
2楼-- · 2019-09-18 03:07

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);

} 
查看更多
疯言疯语
3楼-- · 2019-09-18 03:09

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);
  });
查看更多
登录 后发表回答