DEV Community

Cover image for Creating Interactive Maps with React and Mapbox
Rajiv Lochan Dash
Rajiv Lochan Dash

Posted on

Creating Interactive Maps with React and Mapbox

Embark on a journey where the world becomes your canvas, and your React application transforms into an interactive map masterpiece. In this guide, we'll unravel the secrets of seamlessly integrating Mapbox into your React realm, adding markers, popups, and custom layers that beckon exploration.

Setting the Stage: Integrating Mapbox with React

Before the magic unfolds, let's lay the groundwork. Install the react-map-gl library, a React wrapper for Mapbox, to seamlessly blend the power of React with the cartographic prowess of Mapbox.

npm install react-map-gl mapbox-gl

Now, within your React component:

import ReactMapGL from 'react-map-gl';

function InteractiveMap() {
  const [viewport, setViewport] = useState({
    width: '100%',
    height: 400,
    latitude: 37.7577,
    longitude: -122.4376,
    zoom: 8,
  });

  return <ReactMapGL {...viewport} onViewportChange={setViewport} mapboxApiAccessToken={YOUR_MAPBOX_TOKEN} />;
}
Enter fullscreen mode Exit fullscreen mode

Replace YOUR_MAPBOX_TOKEN with your Mapbox API token obtained from the Mapbox website.

Img1

Adding Markers and Popups: Plotting Points of Interest

Now, let's sprinkle some magic onto our map by adding markers and popups to highlight points of interest.

import { Marker, Popup } from 'react-map-gl';

function InteractiveMap() {
  // ... (previous code)

  const [selectedPlace, setSelectedPlace] = useState(null);

  return (
    <ReactMapGL {...viewport} onViewportChange={setViewport} mapboxApiAccessToken={YOUR_MAPBOX_TOKEN}>
      {/* Markers */}
      <Marker latitude={37.7577} longitude={-122.4376} offsetLeft={-20} offsetTop={-10}>
        <div onClick={() => setSelectedPlace('San Francisco')}>πŸ“</div>
      </Marker>

      {/* Popup */}
      {selectedPlace && (
        <Popup
          latitude={37.7577}
          longitude={-122.4376}
          onClose={() => setSelectedPlace(null)}
        >
          <div>
            <h2>{selectedPlace}</h2>
            <p>Beautiful city by the bay!</p>
          </div>
        </Popup>
      )}
    </ReactMapGL>
  );
}
Enter fullscreen mode Exit fullscreen mode

Replace

URL_TO_YOUR_GEOJSON_DATA

with the URL to your GeoJSON data source.

Handling User Interactions: A Map that Responds

React to user interactions on the map by capturing events such as clicks and movements.

function InteractiveMap() {
  // ... (previous code)

  const handleClick = (event) => {
    const { lngLat } = event;
    console.log(`Clicked on: ${lngLat}`);
  };

  return (
    <ReactMapGL {...viewport} onViewportChange={setViewport} mapboxApiAccessToken={YOUR_MAPBOX_TOKEN} onClick={handleClick}>
      {/* ... (previous code) */}
    </ReactMapGL>
  );
}
Enter fullscreen mode Exit fullscreen mode

Now, your map not only displays information but also responds dynamically to the user's actions.

With these spells and incantations, you've now mastered the art of creating interactive maps with React and Mapbox. May your maps be ever-engaging and your users wander in awe of your digital cartography! πŸ—ΊοΈβœ¨

Happy Coding πŸš€ !!!

Top comments (0)