React Animate Marker on Google Route Map Tutorial
In this tutorial, we will teach you how to animate location marker on Google route maps in React js.
We will also use the function component to animate the Google route marker in React.
Google Maps are well known for making our lives facile. It helps in showing us the correct route for any location.
Google maps api is developer friendly; It offers you various options through which you can easily animate the location marker for Google routes.
You can follow these steps to comprehend the Google route marker animation functionality.
How to Animate Route Marker on Google Maps
- Step 1: Set Up React Project
- Step 2: Install Google Maps Package
- Step 3: Create New Component
- Step 4: Animate Google Route in React
- Step 5: Update App.js File
- Step 6: Start Development Server
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.
Bootstrap is a popular open-source front-end web development framework; It offers a greater collection of CSS and JavaScript components.
Bootstrap can be easily installed through npm package manager for the JavaScript programming language.
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
Head over to src/ folder, search and open the App.js file and import the MapRoute component into this main entry file.
Ensure that you define your Google Map API Key to make the map work flawlessly.
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
Summary
In this guide, we will showed you how to animate location marker point for Google map routes.
We had a chance to use React hooks, such as useEffect, useRef, useState to draw the Google route and marker in React.
We hope this tutorial will help you understand profoundly about Google route Maps in React js application.