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 + "/*Amount*/" + feature.properties.amounts; geojson.bindPopup(popupText); };

The problem: some of the amounts are "null". So, how do I write an if statement, so that if an amount is "null" then both the string ("Amount") and the attribute ("null") don't show up in the popup?

Answer1:

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

人吐槽 人点赞

Recommend

Comment

用户名: 密码:
验证码: 匿名发表

你可以使用这些语言

查看评论:Remove “null” attributes in Leaflet popups with an if-statement