Mastering Maps in React: A Comprehensive Guide to Using @react-google-maps/api
Integrating maps into modern web applications has become an essential aspect of creating engaging and location-aware user experiences. With the advent of React and libraries like @react-google-maps/api, developers can now easily embed interactive maps within their applications. In this comprehensive guide, we’ll walk you through every step, from setting up your Google Cloud connection to utilizing geolocation, to create stunning maps in your React projects.
Part 1: Setting Up Your Google Cloud Connection
- Visit the Google Cloud Platform website to start. New users should register; don’t fret about credit card requests — Google’s free tier offers access to services like the Google Maps API.
- Enter on “Activate Full Account”
- Go to the menu > Google Maps Platform > Keys & Credentials.
- Copy the key and save
Part 2: Initiating Your React Project and Installing Dependencies
Now that you’ve secured your Google Cloud API key, it’s time to set up your React project and integrate the necessary libraries for creating interactive maps using @react-google-maps/api. Follow these steps to get started:
Step 1: Create new react app:
If you haven’t already, ensure you have Node.js and npm (Node Package Manager) installed on your system. Open your terminal and run the following command to create a new React app:
npm create vite@latest
Step 2: Install @react-google-maps/api
npm install @react-google-maps/api
Now open new component for the map and css file.
Step 3: Import
import { GoogleMap, MarkerF, useLoadScript } from '@react-google-maps/api';
import './google-map.css'
const center = {
lat: -3.745,
lng: -38.523
};
The center
object defines the focal point of the map. Later on, we'll explore how to dynamically set this center using your device's location.
Part 3: Displaying Your First Map
Step 1: Define the Map
Function
Create a separate function called Map
to encapsulate the map rendering logic. This function will contain the <GoogleMap>
component and the <MarkerF>
component.
function Map() {
return (
<GoogleMap zoom={16} center={center} mapContainerClassName="map-container">
<MarkerF
onClick={() => console.log("my location")}
position={center}
/>
</GoogleMap>
);
}
Step 2: Define the GoogleMapExample
Function
Create the GoogleMapExample
function, which serves as your main component. Inside this function, use the useLoadScript
hook to load the Google Maps API. If the API is loaded (isLoaded
is true), render the Map
component. If the API is not loaded, show a loading message.
function GoogleMapExample() {
const { isLoaded } = useLoadScript({
googleMapsApiKey: "YOUR_API_KEY",
});
if (!isLoaded) return <div>Loading...</div>;
return (
<div>
<div>
<Map />
</div>
</div>
);
}
export default GoogleMapExample
Step 3: CSS
In your CSS file (e.g., google-map.css
), add the following code to define the size of the map container:
.map-container {
height: 60vh; /* Adjust the height as needed */
}
Remember to link this CSS file in your HTML or include it in your React component if you’re using CSS-in-JS or a similar approach.
And now your map is ready to use!
Part 4: changing Marker Icon:
Enhancing your map’s aesthetics and visual clarity involves customizing markers to suit your application’s theme. In this segment, we’ll walk you through the process of changing the default marker icon to something more eye-catching. Let’s get started:
Step 1: Choose an Icon
Navigate to a reputable source for icons, such as Icon8 (https://www.icon8.com/), and find an icon that resonates with your app’s context. Once you’ve found the perfect icon, download it to your computer.
Step 2: Add the Icon to Your Project
Within your project’s directory, create a folder named icons
or a relevant name to organize your custom icons. Move the downloaded icon file into this folder.
Step 3: Import the Icon
In your React component file where you’re using the MarkerF
component, import the custom icon. Assuming your custom icon file is named custom-icon.png
and is located in the icons
folder, the import would look like this:
import customIcon from './icons/custom-icon.png'; // Update the path as needed
Step 4: Customize Icon Size
In the icon
object within the MarkerF
component, you can adjust the scaledSize
property to set the desired size of your custom icon.
<MarkerF
onClick={() => console.log("my location")}
position={center}
icon={{
url: customIcon,
scaledSize: new window.google.maps.Size(30, 30) // Adjust the size as needed
}}
/>
Part 5: Dynamic Map Centering with Geolocation
Enabling your map to dynamically center based on the user’s location adds a personalized touch to your application. In this section, we’ll guide you through implementing this dynamic centering functionality using the Geolocation API. Let’s dive in:
Step 1: Import Dependencies and Set Up State
First, import the necessary dependencies for managing state and side effects. Add the following lines at the top of your component file:
import React, { useState, useEffect } from 'react';
Next, set up a state variable to hold the dynamic center coordinates. In your Map
component, initialize the center
state using the useState
hook:
function Map() {
const [center, setCenter] = useState({
lat: -3.745,
lng: -38.523
});
// Rest of your Map component code...
}
Dont forget to delete the previous center
Step 2: Implement Geolocation Logic
Inside the Map
component, add the useEffect
hook to fetch the user's current geolocation and update the center
state accordingly. Place this code right after the const [center, setCenter] = useState(...)
line:
useEffect(() => {
const options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0,
};
function success(pos) {
const crd = pos.coords;
const coords = {
lat: crd.latitude,
lng: crd.longitude,
};
setCenter(coords);
}
function error(err) {
console.warn(`ERROR(${err.code}): ${err.message}`);
}
navigator.geolocation.getCurrentPosition(success, error, options);
}, []);
Summary:
Thank you for exploring this interactive map example! You can find the full code on GitHub- click here
If you have any questions or need assistance, feel free to reach out to me on LinkedIn. I’m here to help and discuss any aspects of this example.
Happy coding!