Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-google-maps/api DirectionsService keeps rerendering itself

I have written this code in react JS to using "react-google-maps/api" to calculate route between two points. Now my google map keeps rerendering itself until it gives "DIRECTIONS_ROUTE: OVER_QUERY_LIMIT" error. I don't know what's the issue. Help would be appreciated because I am a beginner in react and google-API and also I haven't found a lot of guides of google API in react.

Here is my code:

import React from "react";
import {
  GoogleMap,
  useLoadScript,
  DirectionsService,
  DirectionsRenderer,
} from "@react-google-maps/api";

const libraries = ["places", "directions"];
const mapContainerStyle = {
  width: "100%",
  height: "50vh",
};
const center = {
  lat: 31.582045,
  lng: 74.329376,
};
const options = {};

const MainMaps = () => {
  const { isLoaded, loadError } = useLoadScript({
    googleMapsApiKey: "********",
    libraries,
  });

  const [origin2, setOrigin2] = React.useState("lahore");
  const [destination2, setDestination2] = React.useState("gujranwala");
  const [response, setResponse] = React.useState(null);

  const directionsCallback = (response) => {
    console.log(response);

    if (response !== null) {
      if (response.status === "OK") {
        setResponse(response);
      } else {
        console.log("response: ", response);
      }
    }
  };

  const mapRef = React.useRef();
  const onMapLoad = React.useCallback((map) => {
    mapRef.current = map;
  }, []);
  if (loadError) return "Error loading maps";
  if (!isLoaded) return "loading maps";

  const DirectionsServiceOption = {
    destination: destination2,
    origin: origin2,
    travelMode: "DRIVING",
  };

  return (
    <div>
      <GoogleMap
        mapContainerStyle={mapContainerStyle}
        zoom={8}
        center={center}
        onLoad={onMapLoad}
      >
        {response !== null && (
          <DirectionsRenderer
            options={{
              directions: response,
            }}
          />
        )}

        <DirectionsService
          options={DirectionsServiceOption}
          callback={directionsCallback}
        />
      </GoogleMap>
    </div>
  );
};

export default MainMaps;
like image 573
Haseeb Ahmad Avatar asked Oct 28 '25 03:10

Haseeb Ahmad


2 Answers

render should always remain pure. It's a very bad practice to do side effecty things during render.

You are calling setstate continuously in directionCallback. You just need to add another condition count.current < 2.

const [origin, setOrigin] = React.useState('chennai');
  const [destination, setDestination] = React.useState('bangalore');
  const [response, setResponse] = React.useState(null);
let count = React.useRef(0);
  const directionsCallback = res => {
    if (res !== null && && count.current < 2) {
      if (res.status === 'OK') {
        count.current += 1;
        setResponse(res);
      } else {
        count.current = 0;
        console.log('res: ', res);
      }
    }
  };

  <DirectionsService
            options={{
              destination: destination,
              origin: origin,
              travelMode: 'DRIVING'
            }}
            callback={directionsCallback}
          />

But the response from the callback is not getting rendered in DirectionsRenderer.

I am also not getting any error message.

{response !== null && (
            <DirectionsRenderer
              // required
              options={{
                directions: response
              }}
            />
          )}

The callback response is

enter image description here

like image 165
Monish N Avatar answered Oct 30 '25 07:10

Monish N


Its a bit late but anyone facing the same issue can refer from this. DirectionService will rerender again and again and you have to stop it until get a response result from DirectionService callback function for DirectionRender postions(lat and lng). You can set a null variable in the beginning and apply condition for DirectionService to run until this variable is null. In the callback of DirectionService set this variable to the response received from this callback and then you will be fine. There was another issue I was facing in DirectionRender class where it was rerendering again and again once I was updating the state. In options, set preserveViewport to true for preserving the view.

You can refer from here for DirectionService issue: https://react-google-maps-api-docs.netlify.app/#directionsrenderer

like image 43
Shivam Chamoli Avatar answered Oct 30 '25 07:10

Shivam Chamoli