Google Maps API Directions Service in React — Plot efficient route on map with total distance and duration.
Use Case:
- 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.
Final Demo!
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 react-google-maps/api
and use-places-autocomplete
packages required.
Step3 — Include Maps JavaScript Library
Include the google maps client-side library in public/index.html
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key [YOUR_API_KEY]&libraries=places"></script>
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
The 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.
On line 13, the route() called takes directions request JavaScript object (with required query parameters origin
, destination
and 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 directionsResult
and directionsStatus
.
And that concludes it!
Source Code!
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!
Originally published at https://anlisha.com.np on August 24, 2022.