Draw a route between two points using Google Maps API in React

Drawing a route between two points is a common feature in many applications that rely on Google Maps API. It can be used for various purposes, such as showing directions to a specific location, calculating the distance between two points, or finding the shortest route to a destination. With the help of Google Maps API and React, it’s easy to implement this feature in a web application.

To get started, you will need to create a Google Maps API key, which will allow you to use the Maps API services. Once you have the API key, you can install the Google Maps JavaScript API library and the React Google Maps package in your React project. Next, you can create a Map component in your application and use the DirectionsService and DirectionsRenderer classes to draw the route between two points. The DirectionsService class calculates the route based on the start and end points, while the DirectionsRenderer class displays the route on the map. You can also customize the appearance of the route using various options, such as stroke color and width, and add markers to the start and end points to make it more user-friendly.

Demo Application

Output - Draw a route between two points using Google Maps API in React - Clue Mediator
Output – Draw a route between two points using Google Maps API in React – Clue Mediator

Draw a route between two points using Google Maps API in React

  1. Project structure
  2. Package dependencies
  3. Implementation
  4. Output

1. Project structure

  • draw-route-google-maps-react
    • node_modules
    • public
      • index.html
    • src
      • App.js
      • GMap.js
      • index.css
      • index.js
    • package-lock.json
    • package.json
    • README.md

2. Package dependencies

Run the following command to install @googlemaps/js-api-loader npm package.

You will find the version of the following packages in React application.

react
^18.2.0
@googlemaps/js-api-loader
^1.15.1

Before using the Directions service in the Maps JavaScript API, first ensure that the Directions API is enabled in the Google Cloud Console, in the same project you set up for the Maps JavaScript API.

3. Implementation

Refer to the following files for implementation.

GMap.js
App.js

4. Output

Run your application and check the output in the browser.
Live Demo

That’s it for today.
Thank you for reading. Happy Coding..!!

Demo & Source Code

GitHub Repository StackBlitz Project
If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

3 Responses

  1. LHB says:

    Thank you soo much!
    Thanks to you, I solved my problem
    Have a good one

  2. sfp says:

    Hello,
    I am trying to add waypoints between origin and destination but i couldn’t. What is the correct way to add waypoints?

Leave a Reply

Your email address will not be published. Required fields are marked *