使用循环

时间:2016-09-01 16:48:12

标签: javascript json leaflet

如果我手动设置纬度和经度并.addTo(layer)。显示右上角的叠加菜单,我可以过滤标记。

但是当我尝试传入一个带有纬度和经度的标记的JSON列表并迭代以创建标记然后.addTo(layer)。叠加菜单消失但标记生成正确。

Leafletjs脚本(手动输入lat和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脚本(使用循环生成标记):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);

我真的不明白循环打破叠加层的原因。当我查看代码时,似乎是创建每个标记,然后将其添加到叠加层。那么它应该生成并传递给过滤器?为什么标记生成正确但叠加菜单消失?

任何见解都会有所帮助。谢谢!

更新:为工作叠加层和非工作叠加层添加了jsfiddle链接。看起来我的JSON列表有问题,当我删除除3-4个标记之外的所有内容时,叠加层再次起作用... https://jsfiddle.net/qm5vd6k4/1/

1 个答案:

答案 0 :(得分:1)

查看您的记录1592至1596包括:

//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
}

更新了JSFiddle:https://jsfiddle.net/8qmk33kp/3/