react-google-maps-api icon indicating copy to clipboard operation
react-google-maps-api copied to clipboard

Multiple requests, directions api

Open giangr21 opened this issue 6 years ago • 11 comments

Im trying to use the Directions api, following the DirectionsRenderer and DirectionsService example, the route was ok, but i cant understand why it is making multiple requests. help pls

Captura de Tela 2020-05-29 às 15 45 37

import React, { useState } from 'react';
import {
  GoogleMap,
  LoadScript,
  Marker,
  DirectionsService,
  DirectionsRenderer,
} from '@react-google-maps/api';

const mapContainerStyle = {
  width: '100vw',
  height: '100vh',
};

const divStyle = {
  background: `white`,
  border: `1px solid #ccc`,
  padding: 15,
};

const center = {
  lat: -25.42836,
  lng: -49.273251,
};

const Index: React.FC = () => {
  const [selected, setSelected] = useState<boolean>(false);
  const [location, setLocation] = useState({ lat: null, lng: null });
  const [teste, setTeste] = useState<boolean>(false);
  const [teste2, setTeste2] = useState([]);
  const [places, setPlaces] = useState([
    {
      id: '1',
      lat: -25.5030536,
      lng: -49.2748372,
    },
    {
      id: '2',
      lat: -25.499088,
      lng: -49.271916,
    },
    {
      id: '3',
      lat: -25.4859193,
      lng: -49.2913265,
    },
  ]);

  const handleClickMarker = (place: any): void => {
    setTeste(true);
    // setLocation({
    //   lat: place.lat,
    //   lng: place.lng,
    // });
    // places[2].lat = -25.4968363;
    // places[2].lng = -49.2736773;
    // setSelected(true);
  };

  const directionsCallback = (result: any): void => {
    console.log(result);
    setTeste2(result);
  };
  return (
    <LoadScript googleMapsApiKey="x">
      <GoogleMap
        mapContainerStyle={mapContainerStyle}
        zoom={15}
        center={places[0]}
        clickableIcons={false}
      >
        {places.map((place) => (
          <Marker
            key={place.id}
            position={{ lat: place.lat, lng: place.lng }}
            onClick={() => handleClickMarker(place)}
          />
        ))}
        {teste === true && (
          <DirectionsService
            options={{
              destination: '-25.499088 -49.271916',
              origin: '-25.4859193, -49.2913265',
              travelMode: 'DRIVING',
            }}
            callback={directionsCallback}
          />
        )}
        {teste === true && (
          <DirectionsRenderer
            options={{
              directions: teste2,
            }}
          />
        )}
      </GoogleMap>
    </LoadScript>
  );
};

export default Index;

giangr21 avatar May 29 '20 18:05 giangr21

@giangr21 Please provide minimal reproduction in codesandbox.io, but just looking at your code - you are passing new objects as props to components, and this causing re-renders I would recommend to use React.useMemo. Also You need to extract all the children as separate components and wrap exports in React.memo

JustFly1984 avatar May 30 '20 12:05 JustFly1984

thanks for your response, im relative new into react. I changed my DirectionsService options to a useMemo and my callback to a useCallback, and now it is working like a charm. thankss =)

giangr21 avatar Jun 01 '20 18:06 giangr21

closing an issue

JustFly1984 avatar Jun 02 '20 02:06 JustFly1984

@giangr21 Can I see how you solved the issue. having same issue, tried using memo and callback. Would really appreciate a look at your solution. thanks

shammahk avatar Mar 16 '21 13:03 shammahk

Solution I made using useMemo. I Just put it on the Direction Service because it calls the function to render the Direction. It Solved for me, but I don't know if it's the best solution.

CODE:

const memoizedDirectionService = useMemo(()=>{
        if( destination == null){
            return <Marker
                position={{lat: parseFloat(restaurant.lat), lng: parseFloat(restaurant.lng)}}
            />
        }
        return <DirectionsService
            options={{
                destination: destination,
                origin: {lat: parseFloat(restaurant.lat), lng: parseFloat(restaurant.lng)},
                travelMode: 'DRIVING'
            }}
            callback={directionsCallback} />

    }, [restaurant, destination]);

MatheusRmelo avatar Oct 27 '21 11:10 MatheusRmelo

@JustFly1984 I've ran into this issue too... It happens on the demo page:

https://react-google-maps-api-docs.netlify.app/#directionsrenderer

marcsoler avatar Dec 28 '21 17:12 marcsoler

@JustFly1984 I've ran into this issue too... It happens on the demo page:

https://react-google-maps-api-docs.netlify.app/#directionsrenderer

Have you tried @MatheusRmelo solution?

I got it working then, away from my PC. Will post the approach I used one I get home.

shammahk avatar Dec 28 '21 18:12 shammahk

@shammahk Didn't work for me... But I managed to get it working with this simple approach:

const [directionsLoaded, setDirectionsLoaded] = useState(false);
const [response, setResponse] = useState(undefined);

const directionCallback = (response: any) => {
   if(response.status === 'OK') {
      setDirectionsLoaded(true);
      setResponse(response);
   }
}
<GoogleMap ...>
   {!directionsLoaded && (origin && destination && travelMode) && (
      <DirectionsService
         options={{destination: destination, origin: origin, travelMode: travelMode, }}
         callback={directionCallback} />)}
         
         { directionsLoaded && <DirectionsRenderer onLoad={dir => setDirRef(dir)} directions={response}
           options={{draggable: true}} onDirectionsChanged={onDirectionsChange} /> }
</GoogleMap>

marcsoler avatar Dec 28 '21 22:12 marcsoler

@marcsoler awesome, happy you got it working.

shammahk avatar Dec 29 '21 00:12 shammahk

@shammahk thanks. I've thought to report it maybe this issue shouldn't be closed though

marcsoler avatar Dec 29 '21 07:12 marcsoler

Hey! I ran into the same issue, but I chose the @JustFly1984 response. It's the sweetness one and it works for me. Maybe use the @marcsoler also works, but I'm not pretty sure if maybe has side effects due to we're calling with callback prop a side effect, so in that order we need to controlled with useMemo and useCallback hooks provided for React library

jasonohdz1501 avatar Jul 08 '22 23:07 jasonohdz1501