Skip to content Skip to sidebar Skip to footer

Remove "null" Attributes In Leaflet Popups With An If-statement

I am using external geojson attributes to fill my popup windows in Leaflet, like this: function popUp (feature, geojson) { var popupText= '/*Name:*/' + feature.properties.name +

Solution 1:

What you are looking for is a conditional statement:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else

var popupText = '';

if (feature.properties.name) {
    popupText += '/*Name:*/' + feature.properties.name;
}

if (feature.properties.amount) {
    popupText += '/*Amount*/' + feature.properties.amount;
}

geojson.bindPopup(popupText);

Or even shorter using a conditional ternary operator:

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

var popupText = '';

popupText += (feature.properties.name) ? '/*Name:*/' + feature.properties.name : '';

popupText += (feature.properties.amount) ? '/*Amount*/' + feature.properties.amount : '';

geojson.bindPopup(popupText);

Post a Comment for "Remove "null" Attributes In Leaflet Popups With An If-statement"