简体   繁体   English

返回单击的层传单

[英]Returning clicked layer leaflet

I want to select a created polygon, created through leaflet.draw by click.我想选择一个创建的多边形,通过单击leaflet.draw创建。 This is how I implement leaflet.draw这就是我实现leaflet.draw

var drawnItems = new L.FeatureGroup();
map.addLayer(drawnItems);

// Initialise the draw control and pass it the FeatureGroup of editable   layers
var drawControl = new L.Control.Draw({
  edit: {
    featureGroup: drawnItems
  }
});
map.addControl(drawControl);

// event when polygon is created
map.on('draw:created', function(e) {
  var type = e.layerType,
    layer = e.layer;

  // add created polygon to Itemcollection
  drawnItems.addLayer(layer);

  // add to map
  map.addLayer(layer);
});

I then want to know, onto which polygon I click.然后我想知道,我点击了哪个多边形。 I do this with each.layer我用each.layer这样做

drawnItems.eachLayer(function(layer) {
  layer.on('click', function() {
    console.log(this._leaflet_id);
  });
});

However, that never returns anything.然而,这永远不会返回任何东西。 When I replace drawnItems with map当我用map替换drawnItems

map.eachLayer(function(layer) {
  layer.on('click', function() {
    console.log(this._leaflet_id);
  });
});

It works – sort of.它有效 - 有点。 It always returns the same id though, even if I click on different polygons... Where is the hickup?它总是返回相同的id ,即使我点击不同的多边形......hickup 在哪里?

As for your click event listener on drawnItems group not displaying anything, this is probably because you loop through drawnItems.eachLayer before it is actually filled with your drawn features / polygons.至于您在drawnItems组上的单击事件侦听drawnItems没有显示任何内容,这可能是因为您在drawnItems.eachLayer实际填充绘制的drawnItems.eachLayer /多边形之前循环了它。

eachLayer will loop through the current child layers. eachLayer将遍历当前的子层。 It will not have any effect on layers that may be added later on.它不会对以后可能添加的图层产生任何影响。

You could rather directly attach your listener to your drawnItems Feature Group.您可以直接将您的侦听器附加到您的drawnItems功能组。 In that case, you can access the child layer that triggered the event trough event.layer where event is the listener argument:在这种情况下,您可以通过event.layer访问触发事件的子层,其中event是侦听器参数:

drawnItems.on("click", function(event) {
    console.log("from drawnItems: " + event.layer._leaflet_id);
});

As for your listener on map , it displays always the same id due to the same original reason ( eachLayer loops through current child layers, ie only drawnItems very probably in your case), and the fact that your drawnItems Feature Group also emits a "click" event.至于您在map上的侦听器,由于相同的原始原因,它始终显示相同的ideachLayer循环遍历当前子层,即在您的情况下很可能仅drawnItems ),并且您的drawnItems Feature Group 也发出"click"事件。 Therefore, you are actually seeing the id of your drawnItems each time.因此,您实际上每次都看到了drawnItemsid

Demo: https://jsfiddle.net/3v7hd2vx/108/演示: https : //jsfiddle.net/3v7hd2vx/108/

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

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