简体   繁体   English

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

[英]How to loop through array of layers in mapbox to listen for a click event?

I am newbie to Mapbox API and I am trying to develop something in which geojson files are returned from the server and the features are plotted on the map. 我是Mapbox API的新手,我正在尝试开发一些东西,其中从服务器返回geojson文件,并在地图上绘制要素。

I am successful in plotting features on the map. 我已成功在地图上绘制要素。 What I do is look through all records and see if the geojson column has a value and if it does I fetch it from the server, make a new layer and plot it on that layer. 我要做的是浏览所有记录,查看geojson列是否具有值,如果可以,则从服务器获取它,创建一个新层并将其绘制在该层上。

These are all polygons. 这些都是多边形。 What I need to do is to fire an event when I click on one of the polygons which is why I am using individual layers. 我需要做的是单击一个多边形时触发一个事件,这就是为什么我要使用单独的图层。 Here is the code: 这是代码:

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

Now I take all the data from the distributor-companies route and make a new layer each time and plot data for every record. 现在,我从分销商-公司路线中获取所有数据,并每次创建一个新层并为每条记录绘制数据。 So at the end I am left with a lot of polygons. 所以最后我剩下很多多边形。

In the end I am trying to individually register a click event listener on the layers which is working perfectly. 最后,我尝试在运行良好的各个层上分别注册一个click事件侦听器。 But the code just before that where I am trying to loop through the layer is not working. 但是在我试图遍历该层之前的代码不起作用。 The console.log function is showing me all the layers as object but when I try to register an on click event on the item it doesn't work and my console says TypeError item is undefined but console.log is working fine with it. console.log函数将所有图层显示为对象,但是当我尝试在该项目上注册on click事件时,该事件将不起作用,并且我的控制台显示TypeError项目未定义,但console.log可以正常使用。

Clearly I am not a JavaScript expert and don't realize what am I doing wrong. 显然,我不是JavaScript专家,也没有意识到我在做什么错。 I just need to loop through all the layers and place an onclick event on them. 我只需要遍历所有层并在它们上放置一个onclick事件。

You don't need to add each feature as a separate featureGroup, it does that for you. 您无需将每个功能添加为单独的featureGroup,它会为您完成。 Just instanciate the featureGroup with a GeoJSON featurecollection object: 只需使用GeoJSON FeatureCollection对象实例化featureGroup即可:

var featureLayer = L.mapbox.featureLayer(geojson).addTo(map);

Then loop over added features, which are in fact just layers and add the onclick event to them: 然后遍历添加的功能(实际上只是图层)并向其添加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);
     });
});

It's a simple as that. 就这么简单。 Working example on Plunker: http://plnkr.co/edit/31nQWnEnDYzNSmroZB8G?p=preview 在Plunker上的工作示例: http ://plnkr.co/edit/31nQWnEnDYzNSmroZB8G?p=preview

If you want to keep it like you've got you can just do the above in your code like this: 如果您想保持它的状态,可以在代码中执行以下操作:

$(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);
                        });
                    });
                });
            }
        });
    });
});

If you want to work with just one featureLayer you could do something like this: 如果您只想使用一个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);
    });
  });
}

Here's a working on Plunker: http://plnkr.co/edit/dIMn9oiSpfsltq4iiilq?p=preview 这是有关Plunker的工作: http ://plnkr.co/edit/dIMn9oiSpfsltq4iiilq?p=preview

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM