How to Use Google Maps Distance Matrix API in React.js to Calculate Distance Between Two Latitudes and Longitudes
React.js is a popular JavaScript library for building user interfaces, and integrating Google Maps services can add powerful location-based features to your applications. In this tutorial, we’ll explore how to use the Google Maps Distance Matrix API in a React.js application to calculate the distance between two sets of latitude and longitude coordinates.
Prerequisites
Before we begin, make sure you have the following:
- Node.js and npm are installed on your machine.
- Basic understanding of React.js concepts.
Step 1: Create a New React App
If you haven’t already set up a React.js application, you can create a new one using Create React App:
npx create-react-app distance-calculator
cd distance-calculator
Step 2: Get an API Key
To use the Google Maps Distance Matrix API, you’ll need an API key. Follow the steps mentioned in the previous article to obtain your API key.
Step 3: Install Axios
We’ll use Axios to make HTTP requests to the Google Maps API. Install Axios in your React project:
npm install axios
Step 4: Create a Distance Calculator Component
Let’s create a new component that will handle the distance calculation. Inside the src
folder, create a new file named DistanceCalculator.js
:
import React, { useState } from 'react';
import axios from 'axios';
const DistanceCalculator = () => {
const [distance, setDistance] = useState(null);
const calculateDistance = async () => {
const apiKey = 'YOUR_API_KEY';
const origin = '37.7749,-122.4194'; // San Francisco
const destination = '34.0522,-118.2437'; // Los Angeles
const url = `https://maps.googleapis.com/maps/api/distancematrix/json?origins=${origin}&destinations=${destination}&key=${apiKey}`;
try {
const response = await axios.get(url);
const result = response.data;
const distanceInMeters = result.rows[0].elements[0].distance.value;
setDistance(distanceInMeters);
} catch (error) {
console.error('Error fetching data: ', error);
}
};
return (
<div>
<h2>Distance Calculator</h2>
<button onClick={calculateDistance}>Calculate Distance</button>
{distance && <p>Distance: {distance} meters</p>}
</div>
);
};
export default DistanceCalculator;
Step 5: Use the Distance Calculator Component
Now, let’s use the DistanceCalculator
component in the main App.js
file:
import React from 'react';
import './App.css';
import DistanceCalculator from './DistanceCalculator';
function App() {
return (
<div className="App">
<header className="App-header">
<DistanceCalculator />
</header>
</div>
);
}
export default App;
Step 6: Replace YOUR_API_KEY
In the DistanceCalculator.js
file, make sure to replace 'YOUR_API_KEY'
with your actual Google Maps API key.
Step 7: Run the Application
Now, you can run your React.js application:
npm start
Visit http://localhost:3000
in your browser, and you should see the "Distance Calculator" component. Click the "Calculate Distance" button, and it will fetch and display the distance between San Francisco and Los Angeles in meters.
Conclusion
In this tutorial, we’ve learned how to use the Google Maps Distance Matrix API in a React.js application to calculate the distance between two sets of latitude and longitude coordinates. This functionality can be expanded by allowing users to input their coordinates, handling errors, displaying additional information like duration, and more.
Remember to keep your API key secure and consider implementing error handling and loading states for a better user experience. For more details on the Google Maps Distance Matrix API and its parameters, refer to the official documentation.