Only show filled attributes in leaflet popups (and not “null”-attributes)

倖福魔咒の 提交于 2019-12-12 00:44:59

问题


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


来源:https://stackoverflow.com/questions/37562830/only-show-filled-attributes-in-leaflet-popups-and-not-null-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!