如何在Leaflet.draw中编辑弹出窗口

How to edit a popup in Leaflet.draw

本文关键字:编辑 窗口 draw Leaflet      更新时间:2023-09-26

我使用的是传单和传单。绘制以创建地图。当我(作为用户)在地图上绘制一个矩形时,下面的代码将写出矩形的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");
        }
    });
添加第二个代码块也意味着我只能编辑第一个已创建的矩形。所以它显然不能工作,但我不知道为什么。

我明白了。对于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");
            }
        });
    });

感谢这个关于检索编辑层类型的问题,为我指明了正确的方向。