Stylized map with React components and a British shorthair cat

Google Map React: A Cartography Carnival for React Developers

The Gray Cat
The Gray Cat

Google Map React is a powerful library that brings the world of Google Maps into your React applications with style and flexibility. This component, built on top of the Google Maps API, allows developers to render any React component on a map, opening up a world of possibilities for creating interactive and visually appealing map-based interfaces.

Charting the Course: Key Features of Google Map React

Before we dive into the code, let’s explore the treasure trove of features that make Google Map React a must-have tool for any React developer working with maps:

  1. Custom Component Rendering: Say goodbye to standard map markers! With Google Map React, you can render any React component on the map, allowing for rich, interactive, and animated map elements.

  2. Isomorphic Rendering: Your maps can render on the server, making them SEO-friendly and ensuring they work even when JavaScript is disabled in the browser.

  3. Independent Positioning: Components are positioned on the map independently of the Google Maps API, allowing for faster initial renders and better performance.

  4. On-Demand API Loading: The Google Maps API is loaded only when needed, improving your application’s initial load time.

  5. Internal Hover Algorithm: Every object on the map can be hovered, providing a smooth user experience even when zooming out.

Setting Sail: Installation and Basic Setup

Let’s start our journey by installing Google Map React. Open your terminal and run one of the following commands:

npm install --save google-map-react

or if you prefer yarn:

yarn add google-map-react

With the library installed, let’s create a basic map component:

import React from 'react';
import GoogleMapReact from 'google-map-react';

interface MarkerProps {
  lat: number;
  lng: number;
  text: string;
}

const AnyReactComponent: React.FC<MarkerProps> = ({ text }) => <div>{text}</div>;

const SimpleMap: React.FC = () => {
  const defaultProps = {
    center: {
      lat: 10.99835602,
      lng: 77.01502627
    },
    zoom: 11
  };

  return (
    <div style={{ height: '100vh', width: '100%' }}>
      <GoogleMapReact
        bootstrapURLKeys={{ key: "YOUR_GOOGLE_MAPS_API_KEY" }}
        defaultCenter={defaultProps.center}
        defaultZoom={defaultProps.zoom}
      >
        <AnyReactComponent
          lat={59.955413}
          lng={30.337844}
          text="My Marker"
        />
      </GoogleMapReact>
    </div>
  );
}

export default SimpleMap;

This code creates a full-screen map centered on the specified coordinates with a custom marker. Remember to replace “YOUR_GOOGLE_MAPS_API_KEY” with your actual Google Maps API key.

Now that we’ve got our bearings, let’s explore some more advanced features of Google Map React.

Custom Markers with Hover Effects

One of the strengths of Google Map React is the ability to use custom components as markers. Let’s create a more interactive marker with hover effects:

import React, { useState } from 'react';
import GoogleMapReact from 'google-map-react';

interface MarkerProps {
  lat: number;
  lng: number;
  text: string;
}

const Marker: React.FC<MarkerProps> = ({ text }) => {
  const [isHovered, setIsHovered] = useState(false);

  return (
    <div
      style={{
        backgroundColor: isHovered ? 'red' : 'blue',
        color: 'white',
        padding: '10px',
        borderRadius: '50%',
        display: 'inline-flex',
        textAlign: 'center',
        alignItems: 'center',
        justifyContent: 'center',
        transform: 'translate(-50%, -50%)'
      }}
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
    >
      {text}
    </div>
  );
};

const InteractiveMap: React.FC = () => {
  // ... (same setup as before)

  return (
    <div style={{ height: '100vh', width: '100%' }}>
      <GoogleMapReact
        bootstrapURLKeys={{ key: "YOUR_GOOGLE_MAPS_API_KEY" }}
        defaultCenter={defaultProps.center}
        defaultZoom={defaultProps.zoom}
      >
        <Marker
          lat={59.955413}
          lng={30.337844}
          text="Hover me!"
        />
      </GoogleMapReact>
    </div>
  );
}

export default InteractiveMap;

This example creates a circular marker that changes color when hovered, demonstrating how you can create interactive elements on your map.

Accessing Google Maps API

Sometimes you might need to access the underlying Google Maps API. Google Map React makes this possible with the onGoogleApiLoaded prop:

import React from 'react';
import GoogleMapReact from 'google-map-react';

const MapWithAPI: React.FC = () => {
  const handleApiLoaded = (map: google.maps.Map, maps: typeof google.maps) => {
    // You can use the map and maps objects here
    const marker = new maps.Marker({
      position: { lat: 59.955413, lng: 30.337844 },
      map,
      title: 'Hello World!'
    });
  };

  return (
    <div style={{ height: '100vh', width: '100%' }}>
      <GoogleMapReact
        bootstrapURLKeys={{ key: "YOUR_GOOGLE_MAPS_API_KEY" }}
        defaultCenter={{ lat: 59.95, lng: 30.33 }}
        defaultZoom={11}
        yesIWantToUseGoogleMapApiInternals
        onGoogleApiLoaded={({ map, maps }) => handleApiLoaded(map, maps)}
      >
        {/* Your components here */}
      </GoogleMapReact>
    </div>
  );
}

export default MapWithAPI;

This example shows how to create a standard Google Maps marker using the API directly. Remember to set yesIWantToUseGoogleMapApiInternals to true to enable this functionality.

Charting Your Own Course: Conclusion

Google Map React is a versatile and powerful tool for integrating Google Maps into your React applications. Its ability to render custom React components as map elements, coupled with features like isomorphic rendering and on-demand API loading, make it an excellent choice for developers looking to create rich, interactive map experiences.

Whether you’re building a location-based service, a travel application, or just want to add some geographical context to your React app, Google Map React provides the tools you need to bring your ideas to life. So set sail, chart your course, and start exploring the world of interactive maps with Google Map React!

For more React mapping adventures, check out our articles on React Leaflet for an alternative mapping library, or React DnD if you’re interested in adding drag-and-drop functionality to your map components.

Comments