我正在使用Google Maps Directions API在地图上绘制路线。它在DirectionsRenderer.setDirections(response)
的第一次调用中执行我想要的操作,但在第二次调用中,它保留了以前的路由,并在上面使用新的路由。我如何清除以前的路由?
代码:
export async function testRouteCalculation(
directionsService: google.maps.DirectionsService,
directionsRenderer: google.maps.DirectionsRenderer,
withWaypoints: boolean,
numWaypointsToInclude: number
) {
let request: google.maps.DirectionsRequest = {
origin: testOrigin,
destination: testDestination,
travelMode: google.maps.TravelMode["DRIVING"],
unitSystem: google.maps.UnitSystem.METRIC,
provideRouteAlternatives: false,
// region is specified for region biasing
region: "za",
waypoints: [],
};
if (withWaypoints) {
for (let i = 0; i < numWaypointsToInclude; i++) {
request!.waypoints!.push(testWaypoints[i]);
}
}
try {
const response = await directionsService.route(request);
return response;
} catch (err) {
throw err;
}
地图组件:
const Map = () => {
const ref = React.useRef<HTMLDivElement>(null);
const [map, setMap] = React.useState<google.maps.Map>();
const [directionsRenderer, setDirectionsRenderer] =
React.useState<google.maps.DirectionsRenderer>();
const [directionsService, setDirectionsService] =
React.useState<google.maps.DirectionsService>();
React.useEffect(() => {
let newMap = null;
if (ref.current && !map) {
newMap = new window.google.maps.Map(ref.current, {
center: capeTownCoordinates,
zoom: 13,
streetViewControl: false,
mapTypeControl: false,
});
setMap(newMap);
}
const newDirectionsRenderer = new google.maps.DirectionsRenderer();
newDirectionsRenderer.setMap(newMap);
setDirectionsRenderer(newDirectionsRenderer);
setDirectionsService(new google.maps.DirectionsService());
}, [ref, map]);
if (map && directionsRenderer && !directionsRenderer.getMap()) {
directionsRenderer.setMap(map);
}
const handleClick = async () => {
if (directionsRenderer && directionsService) {
try {
const response = await testRouteCalculation(
directionsService,
directionsRenderer,
true,
2
);
directionsRenderer.setDirections(response);
} catch (err) {
console.log(err);
}
} else {
console.log("no directionsRenderer or directionsService object");
}
};
return (
<>
<div id="map" style={{ height: "300px", width: "400px" }} ref={ref}></div>
<button onClick={handleClick} className={styles["floating-button"]}>
Get route
</button>
</>
);
};
在设置新的方向之前,我搜索了一下,看到了directionsRenderer.setDirections(null)
或directionsRenderer.setMap(null)
等建议的解决方案,还有其他一些,但都不适用。我认为.setDirections()
会覆盖以前的路线,但地图上绘制的路线和directionRenderer中存储的方向似乎是解耦的。
我发现调用directionsRenderer({routes: []})
实现了我想要的。