How to Animate Marker on Google Map Route in React 18

Last Updated on by in React JS

Google Maps makes our lives easy by helping us find an unknown location in a couple of seconds. A marker plays an important role in identifying specific locations on a map; this makes the address-searching process faster and more memorable.

In this comprehensive tutorial, we will learn how to animate location markers on Google Maps routes in React applications using Google Maps API keys, adding a sense of identification to improve the user experience.

Frontend developers must know how to integrate and customize Google Maps in React. This step-by-step guide broadens your understanding of customizing Google Maps route markers, enabling developers to create more appealing, user-friendly, and interactive web projects by incorporating Google Maps for location finding.

To animate markers on a Google Maps route in React, you need a Google Maps API key in combination with multiple coordinates and a setPosition() method. By the end of this guide, you will be able to create a custom location marker on Google Maps in React.

Set Up React Project

In the fist step, you will have to use the given command to install a new React framework.

Avoid this step, if project is already created.

npx create-react-app my-react-app

Get in the application folder.

cd my-react-app

Install Google Maps Package

The @googlemaps/js-api-loader is a handy JavaScript library that offers an easy way to load the Google Maps JavaScript API dynamically.

This library is published as an npm package and can be installed using the npm command:

npm i @googlemaps/js-api-loader --legacy-peer-deps

–legacy-peer-deps is an option that can be passed to the npm command when installing packages.

It is used to instruct npm to install packages that have peer dependencies that do not meet the current package manager’s requirements.

Peer dependencies are dependencies that are required by a package but are not installed by it.

Installing Bootstrap via npm package manager permits you to quite comfortably manage the project.

npm i bootstrap

Create New Component

Now, create the new components/ folder. Next, create the MapRoute.js file and add the below code into components/MapRoute.js file.

import React from 'react'

function MapRoute() {
  return (
    <div></div>
  )
}

export default MapRoute

Animate Google Route in React

Update components/MapRoute.js file using the below code.

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

const MapRoute = () => {
  const mapRouteRef = useRef(null);
  const [routeMap, setRouteMap] = useState(null);

  useEffect(() => {
    const googleMap = evokeGMap();
    setRouteMap(googleMap);
  }, []);

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

    const routeMapOptions = new window.google.maps.Polyline({
      strokeOpacity: 0,
      icons: [
        {
          icon: {
            path: "M 0,-0.2 0,0.2",
            strokeOpacity: 0.9,
            strokeColor: "red",
            scale: 4,
          },
          offset: "0",
          repeat: "12px",
        },
      ],
    });

    const mapDirService = new window.google.maps.DirectionsService();
    const mapDirRenderer = new window.google.maps.DirectionsRenderer({
      polylineOptions: routeMapOptions,
    });
    const routeHeight = new window.google.maps.LatLng(35.1234126, -111.3345235);
    const beachPoint = new window.google.maps.LatLng(
      35.6543201223223,
      -111.42119253516212,
    );

    const rotueReq = {
      origin: routeHeight,
      destination: beachPoint,
      travelMode: "WALKING",
    };
    mapDirService.route(rotueReq, function (response, status) {
      if (status == "OK") {
        mapDirRenderer.setDirections(response);
        mapDirRenderer.setRouteMap(routeMap);
        moveRouteMarker(routeMap, response.routes[0].overview_path);
      }
    });
  }, [routeMap]);

  const evokeGMap = () => {
    return new window.google.maps.Map(mapRouteRef.current, {
      center: new window.google.maps.LatLng(45.5543234, -131.5643268),
      zoom: 13,
    });
  };

  const moveRouteMarker = async (map, routeCoord) => {
    const marker = new window.google.maps.Marker({
      position: routeCoord[0],
      routeMap,
      icon: {
        url: "https://ibb.co/s1KrjvN",
        scaledSize: new window.google.maps.Size(35, 35),
      },
      zIndex: 99,
      optimized: false,
    });

    for (let i = 0; i < routeCoord.length; i++) {
      await animateMarker(marker, marker.getPosition(), routeCoord[i], 0.06);
    }
  };

  const animateMarker = async (marker, moveFrom, moveTo, t, delta = 100) => {
    return new Promise((resolve) => {
      const routeLat = (moveTo.lat() - moveFrom.lat()) / delta;
      const routeLong = (moveTo.lng() - moveFrom.lng()) / delta;
      let delay = 12 * t,
        count = 0;
      for (let i = 0; i < delta; i++) {
        (function (data) {
          setTimeout(function () {
            let lat = marker.position.lat();
            let lng = marker.position.lng();
            lat += routeLat;
            lng += routeLong;
            marker.setPosition(new window.google.maps.LatLng(lat, lng));

            count++;
            if (count === delta) {
              resolve(marker);
            }
          }, delay * data);
        })(i);
      }
    });
  };

  return <div ref={mapRouteRef} style={{ width: 700, height: 350 }} />;
};

export default MapRoute;

Update App.js File

If you don’t know how to create map keys, make sure to checkout following tutorial:

You will get step-by-step instructions to create a Google map API key.

Update App.js File

Head over to src/ folder, search and open the App.js file further Define your Google Map API Keys in the options array,
and import the MapRoute component into this main entry file.

import React, { useState, useEffect } from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import MapRoute from "./components/MapRoute";
import { Loader } from "@googlemaps/js-api-loader";

function App() {
  const [mapLoader, setMapLoader] = useState(false);

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

    new Loader(options)
      .load()
      .then(() => {
        setMapLoader(true);
      })
      .catch((error) => {
        console.error("Something ain't working; try again later.", error);
      });
  }, []);
  return (
    <div className="container mt-3">
      <h2 className="mb-3">React Animate Google Map Route Marker Example</h2>
      {!mapLoader ? <div>Loading...</div> : <MapRoute />}
      <p>
        To make the Google map work; add{" "}
        <strong>YOUR_GOOGLE_MAP_API_KEY</strong> in <strong>src/App.js</strong>{" "}
        entry.
      </p>
    </div>
  );
}

export default App;

Start Development Server

We are now ready to test the feature we just built.

On your command-prompt, copy and paste the below command and press enter.

npm start

After the server started; your app will be seen on the browser:

http://localhost:3000

React Animate Marker on Google Route Map Tutorial

Summary

React provides a powerful framework for building user interfaces, while Google Maps offers robust mapping capabilities. Integrating the two enables developers to create interactive maps, allowing ease of customization in terms of color, size, look, and feel.

Adding animation to UI elements creates a sense of movement and smooth transition effects, resulting in memorable web experiences. In this guide, we have learned learn how to create an animated route marker on Google Maps in React application.