You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ReactJS中使用@react-google-maps.api无法清除DirectionRenderer路线

问题:@react-google-maps/api清除路线仅降低透明度无法完全移除

我用Google API结合@react-google-maps.api库实现简单的两点路由功能,路线能正常展示,但调用清除方法后,路线并未完全消失,只是透明度降低。


相关代码

计算路线逻辑:

const calculateRoute = async () => {
    let placeServices = new google.maps.places.PlacesService(map);
    const result = await directionService.route({
      origin: {lat: -6.914864,lng: 107.608238},
      destination: {lat: -6.814864,lng: 107.608238},
      travelMode: google.maps.TravelMode.DRIVING,
    });
    setDirection(result);
  }

清除路线逻辑:

const clearRoute = async () => {
    setDirection(null)
  }

地图渲染部分:

<GoogleMap
  mapContainerStyle={{
        height: '100vh',
        width: '60vw',
      }}
      zoom={14}
      center={center}
      onLoad={(map) => onLoad(map)}
    >
      {placeData.map((item, index) => (
        <MarkerF
          key={index}
          position={{
            lat: item.geometry.location.lat(),
            lng: item.geometry.location.lng(),
          }}
        />
      ))}
      {
        direction &&
          <DirectionsRenderer directions={direction}/>
      }
</GoogleMap>

direction是通过useState声明的状态:const [direction, setDirection] = useState(null);


现象说明

  • 路线显示时:地图上清晰展示两点间的驾车路线
  • 清除路线后:路线未完全消失,仅呈现半透明状态

解决方案

方案1:通过key属性强制组件重渲染

给DirectionsRenderer添加唯一key,当direction状态变化时,触发组件完全卸载和重建,彻底清除旧路线:

{direction && (
  <DirectionsRenderer 
    key={direction.routes[0].summary}
    directions={direction}
  />
)}

方案2:直接操作DirectionsRenderer实例调用setMap

利用ref获取组件实例,手动调用Google Maps原生API的setMap(null)方法移除路线:

  1. 创建ref:
const directionsRendererRef = useRef(null);
  1. 绑定到组件:
{direction && (
  <DirectionsRenderer 
    ref={directionsRendererRef}
    directions={direction}
  />
)}
  1. 修改清除方法:
const clearRoute = () => {
  if (directionsRendererRef.current) {
    directionsRendererRef.current.setMap(null);
  }
  setDirection(null);
};

原因分析

原代码仅通过setDirection(null)让DirectionsRenderer不渲染,但组件内部未正确调用Google Maps的setMap(null)移除地图上的路线图层,导致残留半透明视觉痕迹。上述两种方式,要么强制组件重建,要么手动调用原生API清理,都能解决该问题。

内容的提问来源于stack exchange,提问作者Rokkie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 10:25:35