Skip to content
Advertisement

Remove data undefined in popup map Javascript

I have json data, and the data is displayed in a pop up on a map when there is a data that does not exist (Visibility), then the word undefined appears on the pop up

How to remove undefined text, so that it gets deleted on the pop up?

json data :

[{
"date":"03-03-2022",
"lat":-5.67,
"lng":80.65,
"weather":"2",
"temperature": "24.4",
"Humidity": "90",
"Wind": "100"}]

script js :

<script>
for (i = 0; i < dataJSON.length; i++) {
    var weather = parseInt(dataJSON[i].weather)
    var Coordinate = new L.latLng(([dataJSON[i].lat, dataJSON[i].lng]))
    var marker = L.marker(Coordinate, { icon: customIcon })
    marker.bindPopup('Date : ' + dataJSON[i].date + 'Temperature : ' + dataJSON[i].temperature + 'RH :' + dataJSON[i].Humidity
        + 'wind :' + dataJSON[i].Wind + 'Visibility :' + dataJSON[i].Vis
    )
}

Pop Up :

enter image description here

Help me, Please . . .

Advertisement

Answer

You are getting the ‘undefined’ in Visibility since the property ‘Vis’ is not a part of json data.

You can use the following code in script.js to remove undefined from the popup and replace it with blank:

<script>
for (i = 0; i < dataJSON.length; i++) {
var weather = parseInt(dataJSON[i].weather)
var Coordinate = new L.latLng(([dataJSON[i].lat, dataJSON[i].lng]))
var marker = L.marker(Coordinate, { icon: customIcon })
marker.bindPopup('Date : ' + dataJSON[i].date + 'Temperature : ' + dataJSON[i].temperature + 'RH :' + dataJSON[i].Humidity
    + 'wind :' + dataJSON[i].Wind + (dataJSON[i].Vis == undefined?'':'Visibility :' + dataJSON[i].Vis)
)
}
</script>
Advertisement