- One can enter source and destination address; For the address field, google places autocomplete is implemented.
- One can also add multiple way-points/stops between source and destination address.
- On change in any address field, The Map and the Directions service is initialized to plot the driving directions and route on map and display the total distance and total duration.
Step1 — Enable Directions API for Google Maps API key
If you are new to Google Maps API key, I recommend you to have a look at it here.
Step2 — Start Basic CRA and Install packages
npx create-react-app axon cd axon npm install @mui/material @emotion/react @emotion/styled
This will create a basic CRA. We also installed MUI 5 for creating UI components.
npm install @react-google-maps/api use-places-autocomplete formik moment
This will install
use-places-autocomplete packages required.
Include the google maps client-side library in
Step4 — Setup App.js
Initialize Formik with empty initial values of address fields. Formik is the most popular open source form library for React.
Step5 — Create source and destination address field with multiple way-points
GoogleAutocomplete field used is a custom google places autocomplete. You can find it here.
Step6 — Configure Request to Direction Service
On line 9, an instance of the DirectionsService Object is created.
travelMode) as an argument. Also
waypoints parameter is included to consider all the stops between origin and destination.
The second argument of route() method which is a response callback function returns
And that concludes it!
The full source code is available here — https://github.com/anlisha-maharjan/react-google-directions-service
Happy Learning! Feel free to give this article a clap and follow to stay up to date with more articles!