Google Maps is a powerful tool for adding interactive maps and location-based features to your web applications. In this tutorial, we'll walk you through the process of integrating Google Maps into a Next.js application. We'll cover everything from setting up your environment to implementing basic map functionalities.
Before we begin, ensure that you have the following prerequisites:
Create a Google Cloud Project:
Enable the Maps JavaScript API:
Create an API Key:
Next, we need to install the necessary packages for integrating Google Maps into our Next.js application.
npm install @react-google-maps/api
This package provides a set of React components that wrap around the Google Maps JavaScript API.
Now, let's create a new component that will render the map. We'll call it MapComponent.
MapComponent.jsx in the components directory.// components/MapComponent.jsx
import { GoogleMap, LoadScript } from '@react-google-maps/api';
const containerStyle = {
width: '400px',
height: '400px'
};
const center = {
lat: -3.745,
lng: -38.523
};
function MapComponent() {
return (
<LoadScript googleMapsApiKey="YOUR_API_KEY">
<GoogleMap
mapContainerStyle={containerStyle}
center={center}
zoom={10}
>
{/* Child components, like markers, info windows, etc. */}
</GoogleMap>
</LoadScript>
);
}
export default MapComponent;
YOUR_API_KEY:
"YOUR_API_KEY" with the API key you generated in Step 1.Now that we have our map component, let's use it in one of our pages.
pages/index.js file (or any other page where you want to display the map).MapComponent.// pages/index.js
import Head from 'next/head';
import styles from '../styles/Home.module.css';
import MapComponent from '../components/MapComponent';
export default function Home() {
return (
<div className={styles.container}>
<Head>
<title>Google Maps Integration</title>
<meta name="description" content="Integrating Google Maps in Next.js" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main className={styles.main}>
<h1>Welcome to Your Map Page</h1>
<MapComponent />
</main>
<footer className={styles.footer}>
<a
href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Powered by{' '}
<span className={styles.logo}>
<img src="/vercel.svg" alt="Vercel Logo" width={72} height={16} />
</span>
</a>
</footer>
</div>
);
}
You can customize the map by adding markers, info windows, and other features. Let's add a marker to our map.
MapComponent.jsx file to include a marker.// components/MapComponent.jsx
import { GoogleMap, LoadScript, Marker } from '@react-google-maps/api';
const containerStyle = {
width: '400px',
height: '400px'
};
const center = {
lat: -3.745,
lng: -38.523
};
function MapComponent() {
return (
<LoadScript googleMapsApiKey="YOUR_API_KEY">
<GoogleMap
mapContainerStyle={containerStyle}
center={center}
zoom={10}
>
<Marker position={center} />
</GoogleMap>
</LoadScript>
);
}
export default MapComponent;
You can handle user interactions like clicking on the map or markers. Let's add an event handler for a marker click.
MapComponent.jsx file to include an event handler.// components/MapComponent.jsx
import { GoogleMap, LoadScript, Marker } from '@react-google-maps/api';
import { useState } from 'react';
const containerStyle = {
width: '400px',
height: '400px'
};
const center = {
lat: -3.745,
lng: -38.523
};
function MapComponent() {
const [markerPosition, setMarkerPosition] = useState(center);
const handleMarkerClick = () => {
alert(`You clicked the marker at ${markerPosition.lat}, ${markerPosition.lng}`);
};
return (
<LoadScript googleMapsApiKey="YOUR_API_KEY">
<GoogleMap
mapContainerStyle={containerStyle}
center={center}
zoom={10}
>
<Marker position={markerPosition} onClick={handleMarkerClick} />
</GoogleMap>
</LoadScript>
);
}
export default MapComponent;
.env.local file for local development and .env.production for production.# .env.local
NEXT_PUBLIC_GOOGLE_MAPS_API_KEY=YOUR_API_KEY
Error Handling: Always handle errors when loading the Google Maps script or interacting with the map.
Performance Optimization: Use lazy loading techniques to load the Google Maps script only when needed. This can improve the performance of your application.
In this tutorial, we've covered how to integrate Google Maps into a Next.js application. We've set up our environment, created a map component, customized it with markers, and handled user interactions. By following these steps, you should be able to add interactive maps to your Next.js projects effectively.
Feel free to explore more advanced features of the @react-google-maps/api package, such as overlays, polylines, polygons, and more, to enhance your map functionalities further.