【问题标题】:How to edit a popup in Leaflet.draw如何在 Leaflet.draw 中编辑弹出窗口
【发布时间】:2016-08-17 14:26:04
【问题描述】:

我正在使用 Leaflet 和 Leaflet.draw 创建地图。当我(作为用户)在地图上绘制一个矩形时,以下代码会写出矩形的 LatLng 边界。

    // add the newly drawn items to a layer
    map.on('draw:created', function (e) {
        var type = e.layerType,
            layer = e.layer;

        // binds things upon creation
        if (type === 'rectangle') {
            var bounds = layer.getBounds();
            layer.bindPopup(bounds.getNorthWest().toString() + "NW" + bounds.getSouthEast().toString() + "SE");
        }

        drawnItems.addLayer(layer);
    });

我想在用户编辑矩形时更新它。我认为应该使用 'draw:edited' 事件和 '_popup.SetContent' 来更新这样的内容,但是其中的 LatLng 不会更新。

    // update LatLng when edited
    map.on('draw:edited', function (e) {
        var type = e.layerType,
            layer = e.layer;

        // update popup
        if (type === 'rectangle') {
            var bounds = layer.getBounds();
            layer._popup.SetContent(bounds.getNorthWest().toString() + "NW" + bounds.getSouthEast().toString() + "SE");
        }
    });

添加第二个代码块也意味着我只能编辑曾经创建的第一个矩形。所以它显然不起作用,但我不知道为什么。

【问题讨论】:

    标签: javascript leaflet gis leaflet.draw


    【解决方案1】:

    我想通了。对于draw:edited事件,我需要使用eachLayer方法遍历e.layers中的每一层,然后instanceof检查层类型。我还绑定了一个新的弹出窗口,而不是编辑旧的弹出窗口。

    这里是代码,在弹出窗口中也有一个换行符以使其更具可读性:

        // update LatLng value
        map.on('draw:edited', function (e) {
            var layers = e.layers;
    
            layers.eachLayer(function (layer) {
                // do whatever you want to each layer, here update LatLng
                if (layer instanceof L.Rectangle) {
                    var bounds = layer.getBounds();
                    layer.bindPopup(bounds.getNorthWest().toString() +  " NW<br>" + bounds.getSouthEast().toString() + " SE");
                }
            });
        });
    

    感谢this question about retrieving layer type on edit 为我指明了正确的方向。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-21
      • 2022-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多