How to Make an Interactive Map with React and Google Maps

Today, I’m excited to share how I built an interactive map using the react-google-maps/api package in a React application. This project features a custom marker with smooth hover transitions and a fully customized map theme using Snazzy Maps. Let’s dive into the code and the explanations behind it!

Setting Up the Project

First, ensure you have a React application set up. If you haven’t created one yet, you can do so using Create React App:

npx create-react-app my-map-app
cd my-map-app

Next, install the necessary packages:

npm install @react-google-maps/api

You will also need an API key from Google Cloud Platform to use the Google Maps API. Make sure to enable the Maps JavaScript API for your project.

Creating the Map Component

Now, let’s create a new component for our map. Create a file named Map.js in the src directory:

// src/Map.js
import React from 'react';
import { GoogleMap, LoadScript, Marker } from '@react-google-maps/api';

const mapContainerStyle = {
  height: "400px",
  width: "800px"
};

const center = {
  lat: 37.7749, // Latitude for San Francisco
  lng: -122.4194 // Longitude for San Francisco
};

const markerPosition = {
  lat: 37.7749,
  lng: -122.4194
};

const Map = () => {
  return (
    <LoadScript googleMapsApiKey="YOUR_API_KEY">
      <GoogleMap
        mapContainerStyle={mapContainerStyle}
        center={center}
        zoom={10}
      >
        <Marker
          position={markerPosition}
          onMouseOver={() => console.log("Hovered over marker!")}
          onMouseOut={() => console.log("Mouse left marker!")}
          icon={{
            url: "http://maps.google.com/mapfiles/ms/icons/red-dot.png",
            scaledSize: new window.google.maps.Size(30, 30) // Custom size
          }}
        />
      </GoogleMap>
    </LoadScript>
  );
};

export default Map;

Explanation of the Code

  1. Imports: We import necessary components from the @react-google-maps/api package.
  2. Map Container Style: We define the height and width of the map.
  3. Center and Marker Position: We set the initial center of the map and the position of the marker.
  4. LoadScript: This component loads the Google Maps API script using your API key.
  5. GoogleMap: This component renders the map itself, with properties for the container style, center, and zoom level.
  6. Marker: We add a marker at the specified position. The onMouseOver and onMouseOut events allow us to handle hover interactions. The marker icon is customized with a specific URL and size.

Adding Smooth Hover Transitions

To enhance the user experience, we can add CSS transitions for the marker. Create a CSS file named Map.css:

/* src/Map.css */
.marker {
  transition: transform 0.3s ease;
}

.marker:hover {
  transform: scale(1.2);
}

Then, import this CSS file in your Map.js:

import './Map.css';

Now, update the Marker component to include the className for the hover effect:

<Marker
  position={markerPosition}
  onMouseOver={() => console.log("Hovered over marker!")}
  onMouseOut={() => console.log("Mouse left marker!")}
  icon={{
    url: "http://maps.google.com/mapfiles/ms/icons/red-dot.png",
    scaledSize: new window.google.maps.Size(30, 30),
    className: "marker" // Add this line
  }}
/>

Customizing the Map Theme with Snazzy Maps

To customize the map’s appearance, you can use Snazzy Maps. Visit Snazzy Maps to choose a theme and the JSON style array.For example, if you choose a theme, you might get a style like this:

const mapStyles = [
  {
    "featureType": "water",
    "elementType": "geometry",
    "stylers": [
      {
        "color": "#e9e9e9"
      },
      {
        "lightness": 17
      }
    ]
  },
  // Add more styles as needed
];

Then, apply these styles to your GoogleMap component:

<GoogleMap
  mapContainerStyle={mapContainerStyle}
  center={center}
  zoom={10}
  options={{ styles: mapStyles }} // Add this line
>

Final Touches

Finally, import and use the Map component in your App.js:

// src/App.js
import React from 'react';
import Map from './Map';

function App() {
  return (
    <div className="App">
      <h1>My Interactive Map</h1>
      <Map />
    </div>
  );
}

export default App;

Conclusion

And there you have it! You’ve built an interactive map using React and the Google Maps API, complete with a custom marker and a personalized map theme. Feel free to experiment with different styles and functionalities to make the map your own. Happy coding!

Related blog posts