-->

如何在其上点击时,我得到了一份传单形状的层类型?(How do I get a Leaflet sh

2019-10-29 13:48发布

My Leaflet project allows the users to draw shapes (lines, rectangles and polygons). The user can click on the shapes to get their statistics (area, perimeter, etc).

I tried a click event on my FeatureGroup(), where all the shapes I have drawn is added. I am not sure if this is the best approach. Then upon click, a function taking an event is called. The layer type is inferred from the event object.


 //Handlers for when drawn shapes are clicked
        editableLayers.on('click', onLayerClick);

        function onLayerClick(e)
        {
            let type = e.layerType,
                layer = e.layer;
            if (type === 'polygon') {
                polygons.push(e.layer);
                let area = L.GeometryUtil.geodesicArea(layer.getLatLngs()[0]);
                console.log("New polygon area: " + area);
            }

            if (type === 'rectangle') {
                rectangles.push(e.layer);
                let area = L.GeometryUtil.geodesicArea(layer.getLatLngs()[0]);
                console.log("New rectangle area: " + area);
            }     
        }

The type object returns an undefined, and the layer object returns a bunch of parameters making no reference to the shape type. Because of that, I cannot infer the shape type and perform the correct calculations to get their stats.

Answer 1:

我会充分利用instanceof运算符此任务,例如:

function onLayerClick(ev) {
  var targetLayer = ev.sourceTarget;
  if (targetLayer instanceof L.Rectangle) {
     // Do something
  } else if (targetLayer instanceof L.Polygon) {
     // Do something
  } else if (targetLayer instanceof L.Polyline) {
     // Do something
  } else {
     // Do something
  }
}

需要注意的是,由于继承是如何工作的 ,任何情况下L.Rectangle也是一个实例L.Polygon ,并L.PolylineL.Path -这就是为什么代码应该首先检查最具体的子类。

记住要检查出的单张参考,专门为位,告诉你关于继承树, 例如 :

长方形

一类为在地图上绘制矩形覆盖。 扩展多边形。

该单张类图也是理解继承树有用。



Answer 2:

根本原因是, event.layerType是一种特殊的财产Leaflet.draw插件添加的,只有当一个新的功能已经由用户创建的。

当您将在单张标准功能组点击事件监听器,单击事件对象不具有这样的layerType属性,你可以在检查文档 。

作为一个解决方案,请参阅IvanSanchez的答案。



文章来源: How do I get a Leaflet shape's layer type when clicking on it?