javascript - React-Leaflet/React-Routing-Machine : Remove route and waypoints

标签 javascript leaflet react-leaflet leaflet-routing-machine

我正在为我的 map 使用以下软件包:

    "leaflet-routing-machine": "^3.2.12",
    "leaflet": "^1.7.1",
    "react-leaflet": "^2.7.0",
本质上,我有一个 Routing machine 组件,我已经将它与我的 map 和标记集成在一起,即(点击 map 上的两个点即可获得路线),您可以拖动每个点并更新路线!
但是此时我有一个按钮可以重置所有内容,清除标记,关联的 LAT 和 LONG。但我也只想重置路线。
enter image description here
您可以看到那些以前的路线(在美丽的“黄绿色”中)留在 map 上。
现在我有一个函数应该控制组件何时可见:
function clearMarkers(){
  setIsRoutingDone(false);
}

 {isRoutingDone &&  <Routing isRoutingDone={isRoutingDone} map={map} myMapRef={myMapRef} icon={{startIcon, endIcon}} userLocation={userLocation}  coords={{fromLat, fromLon, toLat, toLon}}  />}
这是我的路由机:
import { MapLayer } from "react-leaflet";
import L from "leaflet";
import "leaflet-routing-machine";
import { withLeaflet } from "react-leaflet";


class Routing extends MapLayer {
 constructor(props) {
    super(props);
  }

  createLeafletElement() {
    const { map, coords, icon,  removeFrom, removeTo } = this.props;


    var dStart = L.latLng(coords.fromLat, coords.fromLon);
    var dGoal = L.latLng(coords.toLat, coords.toLon);


    this.leafletElement = L.Routing.control({
      collapsible: true,
       lineOptions: {
      styles: [{color: 'chartreuse', opacity: 1, weight: 5}]
     },
      waypoints: [dStart, dGoal],
      createMarker: function(i, waypoints, n) {
        if (i === 0) {
         marker_icon = icon.startIcon;
        }


       var marker_icon;
        if (i === 0) {
         marker_icon = icon.startIcon;
        }
        else if (i == n - 1) {
         marker_icon = icon.endIcon
        }
        var marker = L.marker(i === 0 ? dStart : dGoal,{
         draggable: true,
         icon: marker_icon
        });
        return marker;
     }
    }).addTo(map.leafletElement);

    return this.leafletElement.getPlan();
  }

  updateLeafletElement(props) {
    if(this.leafletElement){
      if(this.props.isRoutingDone === false){
this.leafletElement.spliceWaypoints(0, 2); // <-- removes your route
      }
    }
  }

}
export default withLeaflet(Routing);
实际上我在 updateLeafletElement 中记录了一些东西函数和 zzilch。
And this is my map:

    import React, { useState, useEffect, useRef } from 'react'
    import { Map, Marker } from 'react-leaflet';
    import LocateControl from '../LocateControl/LocateControl.jsx';
    import MapboxLayer from '../MapboxLayer/MapboxLayer.jsx';
    import Routing from '../RoutingMachine/RoutingMachine.jsx'
    
    export default function MyMap({getAddressFromLatLong, hillfinderFormButtonRef, setCurrentLocation, setCurrentDestination}) {
 
    var myMapRef = useRef();
        
      useEffect(() => {
       hillfinderFormButtonRef.current = clearMarkers;
    
        return() => {
          hillfinderFormButtonRef.current = null;
        }
      }, []);
    
    
    function resetHandler (){
        return myMapRef.current();
      };
    
    
    function clearMarkers(){
      console.log("markerData ", markerData);
      setMarkerData(markerData => [], ...markerData);
      setFromLat(fromLat => null);
      setFromLon(fromLon => null);
      setToLat(toLat => null)
      setToLon(toLon => null)
      setFrom(from => 0);
      setTo(to => 0);
      setIsRoutingDone(false);
      // setRemoveFrom(removeFrom => null)
      // setRemoveTo(removeTo => null)
    }
    

  function saveMap(map){
    setMap(map);
  }

  function handleOnLocationFound(e){
   setUserLocation(e.latlng)
  }
    
  function markerClick(e){
   e.originalEvent.view.L.DomEvent.stopPropagation(e)
  }

  return (
  <Map animate={animate} center={userLocation} onClick={setMarkers} onLocationFound={handleOnLocationFound} zoom={zoom} ref={saveMap}>

     {markerData && markerData.map((element, index) => {
      return (
      <Marker
        key={index}
        marker_index={index}
        position={element}
        draggable={true}
        onClick={markerClick}
        onDragend={updateMarker}
        icon={element.id === 0 ? startIcon : endIcon}
      />
      )
     })}
    <MapboxLayer
      accessToken={MAPBOX_ACCESS_TOKEN}
      style="mapbox://styles/mapbox/streets-v9"
    />
    <LocateControl startDirectly />

     {isRoutingDone &&  <Routing isRoutingDone={isRoutingDone} map={map} myMapRef={myMapRef} icon={{startIcon, endIcon}} userLocation={userLocation}  coords={{fromLat, fromLon, toLat, toLon}}  />}
  </Map>

  )
}
我摆脱了对手头问题不重要的代码!
提前致谢!

最佳答案

我实际上最终自己解决了它!
认为令人头疼的是 react-leaflet 有它的生命周期方法,即 createLeaflet、updateLeafletElement 你不应该忘记常规的 React 生命方法!
不确定它们是否重叠,但我发现添加了 componentDidMount:

  componentDidMount() {
    const { map } = this.props;

    map.addControl(this.routing);
  }
使用 updateLeafletElement(我现在正确使用该函数的 API)它接受 fromPropstoProps只是检查我传递给路由机的 Prop 的值......
  updateLeafletElement(fromProps, toProps) {
    if (toProps.removeRoutingMachine !== false) {
      this.routing.setWaypoints([]);
    }
  }

 
最后在卸载时,使用 removeControl map上的方法您进入路由机器以移除路由器机器!
import { MapLayer } from 'react-leaflet';
import L from 'leaflet';
import 'leaflet-routing-machine';
import { withLeaflet } from 'react-leaflet';

class Routing extends MapLayer {
  constructor(props) {
    super(props);
  }

  createLeafletElement(props) {
    const { map, coords, icon } = this.props;

    var dStart = L.latLng(coords.fromLat, coords.fromLon);
    var dGoal = L.latLng(coords.toLat, coords.toLon);

    if (map && !this.routing) {
      this.routing = L.Routing.control({
        collapsible: true,
        position: 'bottomleft',
        lineOptions: {
          styles: [{ color: 'chartreuse', opacity: 1, weight: 5 }]
        },
        waypoints: [dStart, dGoal],
        createMarker: function(i, waypoints, n) {
          var marker_icon;

          if (i === 0) {
            marker_icon = icon.startIcon;
          } else if (i == n - 1) {
            marker_icon = icon.endIcon;
          }
          var marker = L.marker(i === 0 ? dStart : dGoal, {
            draggable: true,
            icon: marker_icon
          });
          return marker;
        }
      });
    }

    return this.routing.getPlan();
  }

  componentDidMount() {
    const { map } = this.props;

    console.log('map ', map);
    map.addControl(this.routing);
  }

  updateLeafletElement(fromProps, toProps) {
    if (toProps.removeRoutingMachine !== false) {
      this.routing.setWaypoints([]);
    }
  }

  componentWillUnmount() {
    this.destroyRouting();
  }

  destroyRouting() {
    if (this.props.map) {
      this.props.map.removeControl(this.routing);
    }
  }
}

export default withLeaflet(Routing);
希望这可以帮助!仅供引用:这是 app如果您想浏览其他集成,我正在使用路由机...

关于javascript - React-Leaflet/React-Routing-Machine : Remove route and waypoints,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64963337/

相关文章:

reactjs - map 组件: Cannot read property 'initialize' of undefined

javascript - 在 <div> 标签中包裹 react-leaflet Map 组件使其消失

javascript - React Leaflet - 在 map 中心对齐弹出窗口

javascript - 如何在选中复选框时将类分配给 div

javascript - 在 typescript 中使用 Angular 传单指令的步骤

javascript - 根据变量更改提交和重置按钮值文本语言

javascript - 如何简化这个 javascript 传单代码

r - 在 dplyr 管道运算符中组合条件评估 (%>%)

javascript - 将 promise polyfill 添加到 ES6

javascript - .done 或 .then 中的 Jasmine 测试方法