1

我正在使用 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");
        }
    });

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

4

1 回答 1

2

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

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

于 2016-08-17T14:50:42.977 回答