Leaflet – Binding Nested Arrays as GeoJSON Popups in Leaflet

geojsonleafletpopup

I am struggling with geojson popups in leaflet.js
I have nested arrays as properties for my features –
an example would be counts of fish caught at a location (not my actual project data!)

{"type":"FeatureCollection",
"features":[{"geometry":{"type":"Point",
"coordinates":[-122.679416,
45.516632]},
"type":"Feature",
"properties":{"fisher_id":"401",
"river":"Willamette",
"fishcaught":[{"type":"Salmon",
"count":5},
{"type":"Sturgen",
"count":1},
{"type":"Bass",
"count":2}]}},
{"geometry":{"type":"Point",
"coordinates":[-121.318584,
44.050165]},
"type":"Feature",
"properties":{"fisher_id":"401",
"river":"Deschutes",
"fishcaught":[{"type":"Trout",
"count":10},
{"type":"Whitefish",
"count":1}]}},
{"geometry":{"type":"Point",
"coordinates":[-124.102962,
43.983057]},
"type":"Feature",
"properties":{"fisher_id":"401",
"river":"Siuslaw",
"fishcaught":[{"type":"Steelhead",
"count":2},
{"type":"Salmon",
"count":6}]}},
{"geometry":{"type":"Point",
"coordinates":[-121.776289,
42.220382]},
"type":"Feature",
"properties":{"fisher_id":"401",
"river":"Klamath",
"fishcaught":[{"type":"Trout",
"count":3},
{"type":"Steelhead",
"count":2},
{"type":"Salmon",
"count":3}]}}]}

I am trying to put a popup on each feature (onEachFeature) that states river and a count of each type caught.

I'm binding using a function like this

function onEachFeature(feature, layer) {
        if (feature.properties.fishcaught) {
            var popupcontent;
            popupcontent = "<span style='font-weight:bold'>River: </span>"+feature.properties.river
            for (i=0;i<feature.properties.fishcaught.length;i=i+1){
                var fishstring = "<br><span style='font-weight:bold'>"+feature.properties.fishcaught[i].type+": </span>"
                +feature.properties.fishcaught[i].count
                popupcontent = popupcontent+fishstring;
            }
            layer.bindPopup(popupcontent);
        }
    }

geojson = L.geoJson(inData, {
    onEachFeature: onEachFeature
}).addTo(map);

The problem is that the onEachFeature is caught in an endless loop. If I remove the for loop from the function, everything works fine.

Any thoughts on this?

Best Answer

It looks like you have a typo in your for loop. It should be:

for (i=0;i<feature.properties.fishcaught.length;i++)

instead of:

for (i=0;i<feature.properties.fishcaught.length;i=i+1)

Notice that the first is incrementing i by one not adding 1 to i.