2

您对将绘图功能实现到 react-leafletV3 有任何想法吗?我添加了一个事件侦听器,但它无法正常工作并对任何事情做出反应。

  useEffect(() => {
    if (!map) return;

    map.addEventListener("mousemove", function (event) {
      setCoords({ lat: event.latlng.lat, lng: event.latlng.lng });
    });

    map.on("draw:drawstart", function (event) {
      console.log("event here", event);
    });

    const drawControl = new L.Control.Draw({
      position: "topleft",
    });
    drawControl.addTo(map);

    const leftLayer = L.tileLayer(
      layers[leftLayerIndex].url,
      layerOptions
    ).addTo(map);

    const rightLayer = L.tileLayer(
      layers[rightLayerIndex].url,
      layerOptions
    ).addTo(map);

    const sbs = L.control.sideBySide(leftLayer, rightLayer).addTo(map);
    setSideBySide(sbs);
  }, [map]);

  useEffect(() => {
    if (sideBySide) {
      sideBySide.setLeftLayers(
        L.tileLayer(layers[leftLayerIndex].url, layerOptions).addTo(map)
      );
    }
  }, [leftLayerIndex, rightLayerIndex, sideBySide]);

4

1 回答 1

1

这是对我有用的代码。我添加了一个事件侦听器来侦听创建的图层,并在创建图层后添加了要素组图层。我已经提到这部分是必需的,因为我已经在选项对象中评论过。

      edit: {
        featureGroup: editableLayers, //REQUIRED!!
      }

  useEffect(() => {
    if (!map) return;

    map.addEventListener("mousemove", function (event) {
      setCoords({ lat: event.latlng.lat, lng: event.latlng.lng });
    });

    const editableLayers = new L.FeatureGroup();
    map.addLayer(editableLayers);

    const options = {
      position: "topleft",
      draw: {
        polyline: false,
        polygon: false,
        rectangle: {
          shapeOptions: {
            clickable: false,
            color: "dodgerblue",
          },
        },
      },
      edit: {
        featureGroup: editableLayers, //REQUIRED!!
      },
    };

    const drawControl = new L.Control.Draw(options);
    map.addControl(drawControl);

    map.on(L.Draw.Event.CREATED, function (e) {
      var type = e.layerType,
        layer = e.layer;

      if (type === "marker") {
        layer.bindPopup("A popup!");
      }

      editableLayers.addLayer(layer);
    });

    const leftLayer = L.tileLayer(
      layers[leftLayerIndex].url,
      layerOptions
    ).addTo(map);

    const rightLayer = L.tileLayer(
      layers[rightLayerIndex].url,
      layerOptions
    ).addTo(map);

    const sbs = L.control.sideBySide(leftLayer, rightLayer).addTo(map);
    setSideBySide(sbs);
  }, [map]);

于 2021-03-12T22:17:27.750 回答