I am trying to create a traffic polyline in React through the Google Maps library. I currently have a polyline from the directions API via the below code:
export const renderDirections = async (map, origin, destination) => {
const directionsService = new google.maps.DirectionsService()
directionsDisplay = new google.maps.DirectionsRenderer({
polylineOptions: {
strokeColor: '#65a30d',
strokeOpacity: 1,
strokeWeight: 6,
},
suppressMarkers: true,
})
const routePolyline = await directionsService.route({
origin: origin,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING,
})
directionsDisplay.setMap(map)
directionsDisplay.setDirections(routePolyline)
}
The objective is to color-code the polyline based on the traffic conditions, as done in the demo Routes API tool on the Google Maps API documentation:
https://developers.google.com/maps/documentation/routes/demo
However, I do not see any option to enable routingPreference: "TRAFFIC_AWARE" as there’s an error that the property does not exist in type DirectionsRequest
My next approach was creating a POST request to the API using the connection (in Postman):
https://routes.googleapis.com/directions/v2:computeRoutes?key=APIKEY (with the API Key)
Request body:
{
"origin": {
"location": {
"latLng": {
"latitude": 37.419734,
"longitude": -122.0827784
}
}
},
"destination": {
"location": {
"latLng": {
"latitude": 37.417670,
"longitude": -122.079595
}
}
},
"travelMode": "DRIVE",
"routingPreference": "TRAFFIC_AWARE",
"departureTime": "2023-10-15T15:01:23.045123456Z",
"computeAlternativeRoutes": false,
"routeModifiers": {
"avoidTolls": false,
"avoidHighways": false,
"avoidFerries": false
},
"languageCode": "en-US",
"units": "IMPERIAL",
}
However, this fails with FieldMask is a required parameter. See https://cloud.google.com/apis/docs/system-parameters on how to provide it. As an example, you can set the header 'X-Goog-FieldMask' to value 'routes.distanceMeters,routes.duration,routes.polyline.encodedPolyline' to ask for the route distance, duration, and polyline in the response
and the documentation is unclear how to address this issue. I appreciate any help on computing a traffic-aware polyline in React or Javascript and how to render it onto a map
Thanks in advance!

