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)方法移除路线:
- 创建ref:
const directionsRendererRef = useRef(null);
- 绑定到组件:
{direction && ( <DirectionsRenderer ref={directionsRendererRef} directions={direction} /> )}
- 修改清除方法:
const clearRoute = () => { if (directionsRendererRef.current) { directionsRendererRef.current.setMap(null); } setDirection(null); };
原因分析
原代码仅通过setDirection(null)让DirectionsRenderer不渲染,但组件内部未正确调用Google Maps的setMap(null)移除地图上的路线图层,导致残留半透明视觉痕迹。上述两种方式,要么强制组件重建,要么手动调用原生API清理,都能解决该问题。
内容的提问来源于stack exchange,提问作者Rokkie
相关产品推荐
相关产品推荐

