单击时如何获取Leaflet形状的图层类型? [英] How do I get a Leaflet shape's layer type when clicking on it?

查看:884
本文介绍了单击时如何获取Leaflet形状的图层类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Leaflet项目允许用户绘制形状(线,矩形和多边形).用户可以单击形状以获取其统计信息(区域,周长等).

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

我在FeatureGroup()上尝试了一次单击事件,其中添加了我绘制的所有形状.我不确定这是否是最好的方法.然后,在单击时,将调用带有事件的函数.图层类型是从事件对象推断出来的.

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.

推荐答案

我会利用

I would leverage the instanceof operator for this task, e.g.:

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的实例-这就是为什么代码应首先检查最具体的子类的原因.

Note that due to how inheritance works, any instance of L.Rectangle is also an instance of L.Polygon, and L.Polyline and L.Path - that's why the code should check first for the most specific subclasses.

请记住要签出Leaflet参考,特别是那些用于告诉您有关继承树的位,

Remember to check out the Leaflet reference, specifically for the bits which tell you about the inheritance tree, e.g.:

矩形

用于在地图上绘制矩形叠加层的类.扩展多边形.

Rectangle

A class for drawing rectangle overlays on a map. Extends Polygon.

传单类图对于理解继承树也很有用.

The Leaflet class diagram is also useful for understanding the inheritance tree.

这篇关于单击时如何获取Leaflet形状的图层类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆