PolylineF draw a straight line between the points In addition to path

51 views Asked by At

I use PolylineF from @react-google-maps/api to draw polygon on map.I have some points and I compute the path in route function from google.maps.DirectionsService(). when the first time of the drawing after the map is loaded I accept two polygons between the points one it's OK acoording by DirectionsService but the second is worng it's a drawing of straight lines between the points. It's occures only in the first time after loading the other times the drawing is excellent

here is my code:

const PolygonOnMap = ({ markpoints, close, remove, getPoints, readOnly, ss }) => {
    const { isLoaded } = useContext(GoogleMapAPIContext)
    const [points, setPoints] = useState([])
    const [, setDirRender] = useState(null)
    const dirService = useMemo(()=>{
        console.log('useMemo',isLoaded);
        if(isLoaded)
            return new window.google.maps.DirectionsService();
        return null;
    },[isLoaded])


    const drawPolygon = async (markpoints) => {

        setPoints([])

        for (let i = 0; i < markpoints.length - 1; i++) {
            if (dirService) {
                try {
                    const result = await dirService.route({ origin: markpoints[i], destination:      markpoints[i + 1], travelMode: window.google.maps.TravelMode.WALKING })
                    let newPoints = result.routes[0].overview_path.map(p => ({ lat: p.lat(), lng: p.lng() }))

                    setPoints(prev => [...prev, ...newPoints])
                }
                catch (error) {
                    console.log(error.message)
                }
            }
            
        }
       
    }

    useEffect(() => {

        drawPolygon(markpoints)
    }, [markpoints])


    return <>
        <div>
            {markpoints.map((p, i) => <MarkerF key={i} position={p} index={i} />)}
            {<PolylineF
                path={points}
                geodesic={true}
                options={{
                    fillColor: "red",
                    strokeColor: "#ff2527",
                    strokeOpacity: 0.75,
                    strokeWeight: 2,

                }}
            />}

        </div>
    </>
}

export default PolygonOnMap

And I'll attach screenshot below as well the map with the multiple polygons:(https://i.stack.imgur.com/gpqTc.png)

1

There are 1 answers

0
Alis On BEST ANSWER

The multiple polygons only in the loading beacuse the component is render twice in react on development mode so when delete the strictMode tags in index.js page like this:

// <StrictMode>
        <App />
// </StrictMode>

the problem is solved