tshckr tshckr - 3 months ago 13
JSON Question

Leafletjs map overlays stops working when markers are added using a loop

If I put the latitude and longitude manually and

.addTo(layer)
. The overlay menu on the top right is displayed and I can filter the markers.

But when I try to pass in a JSON list of markers with latitude and longitude and iterate through to create the markers and then
.addTo(layer)
. The overlay menu disappears but the markers are generated correctly.

Leafletjs script (manually entered lat and long): https://jsfiddle.net/kdu2woLb/1/

var cities = new L.LayerGroup();
L.marker([40.7864742, -73.9393257], {icon: citiesIcon}).bindPopup('Job Title: ').addTo(cities);
L.marker([40.8561684, -73.89659800000001], {icon: citiesIcon}).bindPopup('Job Title: ').addTo(cities);

var jobs = new L.LayerGroup();
L.marker([40.7127837, -74.0059413], {icon: jobIcon}).bindPopup('Job Title: ').addTo(jobs);
L.marker([40.7348796, -73.86348939999999 ], {icon: jobIcon}).bindPopup('Job Title: ').addTo(jobs);


Leafletjs script (using a loop to generate the markers): https://jsfiddle.net/8qmk33kp/2/

var cities = new L.LayerGroup();
for ( var i=0; i < markers.length; ++i )
{
L.marker( [markers[i].latitude, markers[i].longitude], {icon: jobIcon} )
.bindPopup( markers[i].title+ '<br/>' + 'Address: ' + markers[i].address + '<br />' + 'Salary range: ' + '$' + markers[i].min_salary + ' - ' + '$' + markers[i].max_salary )
.addTo(cities);
}

var jobs = new L.LayerGroup();
L.marker([40.7127837, -74.0059413], {icon: jobIcon}).bindPopup('Job Title: ').addTo(jobs);
L.marker([40.7348796, -73.86348939999999 ], {icon: jobIcon}).bindPopup('Job Title: ').addTo(jobs);


I don't really understand why the loop breaks the overlay. When I look through the code it seems to be creating each marker and then adding it to overlay. So it should be generated and passed to the filter? Why does the markers generate correctly but the overlay menu disappear?

Any insight would help. Thanks!




UPDATE: Added the jsfiddle links for both working overlay and non-working overlay. Looks like there is something wrong with my JSON list, when I deleted everything except for 3-4 markers, the overlay works again...https://jsfiddle.net/qm5vd6k4/1/

Answer

See your records 1592 to 1596 included:

//i = 1592
{
  "title": "PRINCIPAL ADMINISTRATIVE ASSOC",
  "latitude": null,
  "longitude": null
}
//i = 1593
{
  "title": "PUBLIC HEALTH ADVISER",
  "latitude": null,
  "longitude": null
}
//i = 1594
{
  "title": "COMMUNITY COORDINATOR",
  "latitude": null,
  "longitude": null
}
//i = 1595
{
  "title": "ADMINISTRATIVE PUBLIC HEALTH N",
  "latitude": null,
  "longitude": null
}
//i = 1596
{
  "title": "FAMILY PUB HEALTH NURSE (HMH)",
  "latitude": null,
  "longitude": null
}

Updated JSFiddle: https://jsfiddle.net/8qmk33kp/3/

Comments