I am trying to draw multiple routes in google map using react-google-maps/api. Here i am using DirectionServices and DirectionsRender component to draw the routes. The problem i am facing is, if i have multiple routes direction service data in an array and loop the array to bind the DirectionsRender, only last index route drawing perfectly. first index route not displaying.Please see the code structure i am following.
const [liveCoordinates, setLiveCoordinates] = useState<any>([]);
const routingProcess = () => {
const routeArr: any = [{id: 1, data: [{latitude: 9.343434, longitude: 75.95856}, {}, ...]}, {id: 2, data: [{latitude: 10.343456, longitude: 76.95455}, {}, ...]}];
routeArr.map((route: any, index: number) => {
const snapShotRes = [...route.data];
const directionPoints = [...route.data];
const firstPoint = directionPoints.shift();
const lastPoint = directionPoints.pop();
let wayPointsArr: google.maps.DirectionsWaypoint[] = [];
wayPointsArr = directionPoints.map((doc: any) => ({
location: new google.maps.LatLng(doc.latitude, doc.longitude),
stopover: false,
}));
if (snapShotRes.length > 1) {
if (RouteDirectionsService) {
RouteDirectionsService.route(
{
origin: new google.maps.LatLng(snapShotRes[0].latitude, snapShotRes[0].longitude),
destination: new google.maps.LatLng(snapShotRes[snapShotRes.length - 1].latitude, snapShotRes[snapShotRes.length - 1].longitude),
travelMode: window.google.maps.TravelMode.DRIVING,
waypoints: wayPointsArr,
optimizeWaypoints: true,
},
(result, status) => {
if (status === window.google.maps.DirectionsStatus.OK) {
liveLocationArr.push(result);
if (index + 1 === historyData.length) {
setLiveCoordinates(liveLocationArr);
}
}
},
);
}
}
});
}
Render:
---------
return(
<>
{liveCoordinates.map((route: any, index: number) => (
<DirectionsRenderer
directions={route}
key={`${index}-${new Date().getMilliseconds()}`}
options={{
polylineOptions: {
strokeWeight: 3,
strokeColor: "#f62e4d",
},
preserveViewport: true,
suppressMarkers: true,
}}
/>
))}
</>
)