Clue Mediator

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

๐Ÿ“…April 10, 2023
๐Ÿ—ReactJS

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.

npm i @googlemaps/js-api-loader

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

import React, { useEffect, useRef, useState } from 'react';

const GMap = () => {
  const googleMapRef = useRef(null);
  const [map, setMap] = useState(null);

  useEffect(() => {
    const googleMap = initGoogleMap();
    setMap(googleMap);
  }, []);

  useEffect(() => {
    if (!map) return;

    var directionsService = new window.google.maps.DirectionsService();
    var directionsRenderer = new window.google.maps.DirectionsRenderer();
    var haight = new window.google.maps.LatLng(37.7699298, -122.4469157);
    var oceanBeach = new window.google.maps.LatLng(37.7683909618184, -122.51089453697205);
    var request = {
      origin: haight,
      destination: oceanBeach,
      travelMode: 'WALKING'
    };
    directionsService.route(request, function (response, status) {
      if (status == 'OK') {
        directionsRenderer.setDirections(response);
        directionsRenderer.setMap(map);
      }
    });
  }, [map])

  const initGoogleMap = () => {
    return new window.google.maps.Map(googleMapRef.current, {
      center: new window.google.maps.LatLng(37.7699298, -122.4469157),
      zoom: 8
    });
  }

  return <div 500="" ref={googleMapRef} style={{ width: 600, height: }}>
}

export default GMap;</div>

App.js

import React, { useState, useEffect } from 'react';
import { Loader } from '@googlemaps/js-api-loader';
import GMap from './GMap';

// API key of the google map
const GOOGLE_MAP_API_KEY = '<your_google_map_api_key>';

const App = () => {
  const [loadMap, setLoadMap] = useState(false);

  useEffect(() => {
    const options = {
      apiKey: GOOGLE_MAP_API_KEY,
      version: "weekly",
      libraries: ['geometry']
    };

    new Loader(options).load().then(() => {
      setLoadMap(true);
    }).catch(e => {
      console.error('Sorry, something went wrong: Please try again later. Error:', e);
    });
  }, []);

  return (
    <div class="App">
      <h4>Draw a route between two points using Google Maps API in React - <a href="https://www.cluemediator.com">Clue Mediator</a></h4>
      {!loadMap ? <div>Loading...</div> : <gmap>}
      <br>
      <small><b>Note:</b> In order to make it work, you have to set the YOUR_GOOGLE_MAP_API_KEY in App.js file. </small>
    </gmap></div>
  );
}

export default App;
</your_google_map_api_key>

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