Home > Software engineering >  Route not clearing when setting new route
Route not clearing when setting new route

Time:10-30

I'm using Google Maps Directions API to draw routes on a map. It does what I want on the first call of DirectionsRenderer.setDirections(response), but on the second call, it persists the previous route and uses the new one on top of it. How can I clear the previous route?

Code:

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;
  }

The map component:

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>
    </>
  );
};

I searched up and saw proposed solutions like directionsRenderer.setDirections(null) or directionsRenderer.setMap(null) before setting the new directions, and a couple of others, but none of them worked for me. I would think that .setDirections() would overwrite previous routes, but it seems that the routes drawn on the map and the directions stored in the directionRenderer are decoupled.

CodePudding user response:

I found that calling directionsRenderer({routes: []}) achieved what I was looking for.

  • Related