如何遍历mapbox中的图层数组以侦听click事件?

Roh*_*han 0 javascript jquery leaflet mapbox

我是Mapbox API的新手,我正在尝试开发一些东西,其中从服务器返回geojson文件,并在地图上绘制要素。

我已成功在地图上绘制要素。我要做的是浏览所有记录,查看geojson列是否具有值,如果可以,则从服务器获取它,创建一个新层并将其绘制在该层上。

这些都是多边形。我需要做的是在单击一个多边形时触发一个事件,这就是为什么我使用单个图层的原因。这是代码:

<script type="text/javascript">
        L.mapbox.accessToken = 'someKey';
        var map = L.mapbox.map('map', 'someMap')
            .setView([-39.67, -69.26], 4);

        $(document).ready(function(){
            $('header h2').text('Equipment Map');

            $.getJSON('distributor-companies', function (data) {
                var layers = [];
                $.each(data, function(i, item) {
                    if(item.geojson != ''){
                        var file = item.geojson;
                        layers[i] = L.mapbox.featureLayer().addTo(map);
                        $.getJSON('/geojson/' + file, function(data){
                            console.log('layer' + i);
                            layers[i].setGeoJSON(data);
                        });
                    }
                });
                $.each(layers, function(i, item){
                    console.log(item);
                    // item.on('click', function(e){
                    //  alert('hello');
                    // });
                });

                layers[32].on('click', function(e){
                    alert('hello');
                });
                layers[31].on('click', function(e){
                    alert('hello hi');
                });
            });
        });
    </script>
Run Code Online (Sandbox Code Playgroud)

现在,我从分销商-公司路线中获取所有数据,并每次创建一个新层并为每条记录绘制数据。所以最后我剩下很多多边形。

最后,我尝试在运行良好的各个层上分别注册一个click事件侦听器。但是在我试图遍历该层之前的代码不起作用。console.log函数将所有图层显示为对象,但是当我尝试在该项目上注册on click事件时,该事件将不起作用,并且我的控制台显示TypeError项目未定义,但console.log可以正常使用。

显然,我不是JavaScript专家,也没有意识到我在做什么错。我只需要遍历所有层并在它们上放置一个onclick事件。

iH8*_*iH8 5

您无需将每个功能添加为单独的featureGroup,它会为您完成。只需使用GeoJSON FeatureCollection对象实例化featureGroup即可:

var featureLayer = L.mapbox.featureLayer(geojson).addTo(map);
Run Code Online (Sandbox Code Playgroud)

然后遍历添加的功能(实际上只是图层)并向其添加onclick事件:

featureLayer.eachLayer(function (layer) {
    layer.on('click', function (e) {
        // here e.target holds the layer
        // and e.target.feature holds the actual feature
        alert('Clicked layer ID: ' + e.target.feature.id);
     });
});
Run Code Online (Sandbox Code Playgroud)

就这么简单。在Plunker上的工作示例:http ://plnkr.co/edit/31nQWnEnDYzNSmroZB8G?p=preview

如果您想保持它的状态,可以在代码中执行以下操作:

$(document).ready(function(){
    $('header h2').text('Equipment Map');
    $.getJSON('distributor-companies', function (data) {
        var layers = [];
        $.each(data, function (i, item) {
            if (item.geojson != '') {
                layers[i] = L.mapbox.featureLayer().addTo(map);
                $.getJSON('/geojson/' + item.geojson, function (data) {
                    layers[i].setGeoJSON(data);
                    // Loop over the added layer
                    layers[i].eachLayer(function (layer) {
                        // Add click event
                        layer.on('click', function (e) {
                            // Do stuff
                            alert('Clicked layer ID: ' + e.target._leaflet_id);
                        });
                    });
                });
            }
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

如果您只想使用一个featureLayer,则可以执行以下操作:

// Add empty featureLayer
var featureLayer = L.mapbox.featureLayer().addTo(map);

// Get URL index
$.getJSON('index.json', function (index) {
  // Create empty feature array
  var features = [];
  // Loop over URLs
  $.each(index, function (i, url) {
    // Fetch GeoJSON from URL
    $.getJSON(url, function (geojson) {
      // Push GeoJSON to array
      features.push(geojson);
      // Check if is last URL
      if (i == index.length - 1) {
        // Call addFeature with array
        addFeatures(features);
      }
    });
  });
});

function addFeatures (features) {
  // Set features in featureLayer
  featureLayer.setGeoJSON(features);
  // Loop over layers in featureLayer
  featureLayer.eachLayer(function (layer) {
    // Attach click handler
    layer.on('click', function (e) {
      // Do stuff
      alert('Clicked layer ID: ' + e.target.feature.id);
    });
  });
}
Run Code Online (Sandbox Code Playgroud)

这是有关Plunker的工作:http ://plnkr.co/edit/dIMn9oiSpfsltq4iiilq?p=preview