← Back

How To Create Maps With React And Leaflet

By Vivek Singh
Picture of the author
Published on
React Leaflet Map

Creating interactive maps is a powerful way to visualize geographic data and enhance user experiences on your web applications. Leaflet is a popular open-source JavaScript library for mobile-friendly interactive maps, and it can be easily integrated with React. In this blog post, we'll walk through the process of creating maps with React and Leaflet, including setting up the project, adding a map, and incorporating custom markers and popups.

Prerequisites

Before you begin, ensure you have the following installed:

  • Node.js and npm
  • A code editor (such as VSCode)

Setting Up the Project

Step 1: Initialize the React Project

First, create a new React project using Create React App.

npx create-react-app react-leaflet-map
cd react-leaflet-map

Step 2: Install Leaflet and React-Leaflet

React-Leaflet is a React wrapper for Leaflet. Install Leaflet and React-Leaflet using npm.

npm install leaflet react-leaflet

Additionally, you need to install @react-leaflet/core which is a peer dependency:

npm install @react-leaflet/core

Creating the Map

Step 3: Setting Up the Basic Map Component

Create a new file named Map.js in the src directory and set up a basic map component.

// src/Map.js
import React from 'react';
import { MapContainer, TileLayer } from 'react-leaflet';
import 'leaflet/dist/leaflet.css';

const Map = () => {
  return (
    <MapContainer center={[51.505, -0.09]} zoom={13} style={{ height: '100vh', width: '100%' }}>
      <TileLayer
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
      />
    </MapContainer>
  );
};

export default Map;

Step 4: Integrating the Map Component

Integrate the Map component into the App.js file.

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

const App = () => {
  return (
    <div>
      <h1>React Leaflet Map</h1>
      <Map />
    </div>
  );
};

export default App;

Run your development server to see the map in action.

npm start

You should see a basic map centered at the specified coordinates.

Adding Markers and Popups

Step 5: Adding Custom Markers

Add custom markers to your map by importing the Marker and Popup components from react-leaflet.

// src/Map.js
import React from 'react';
import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet';
import 'leaflet/dist/leaflet.css';
import L from 'leaflet';

// Custom icon for markers
const customIcon = new L.Icon({
  iconUrl: require('leaflet/dist/images/marker-icon.png'),
  iconSize: [25, 41],
  iconAnchor: [12, 41],
  popupAnchor: [1, -34],
  shadowUrl: require('leaflet/dist/images/marker-shadow.png'),
  shadowSize: [41, 41],
});

const Map = () => {
  return (
    <MapContainer center={[51.505, -0.09]} zoom={13} style={{ height: '100vh', width: '100%' }}>
      <TileLayer
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
      />
      <Marker position={[51.505, -0.09]} icon={customIcon}>
        <Popup>
          A pretty CSS3 popup. <br /> Easily customizable.
        </Popup>
      </Marker>
    </MapContainer>
  );
};

export default Map;

This code snippet adds a marker at the specified position with a popup containing some text. The customIcon ensures that the marker icon is correctly displayed.

Adding Multiple Markers

Step 6: Displaying Multiple Markers

To add multiple markers, you can map through an array of coordinates and render Marker components for each one.

// src/Map.js
import React from 'react';
import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet';
import 'leaflet/dist/leaflet.css';
import L from 'leaflet';

const customIcon = new L.Icon({
  iconUrl: require('leaflet/dist/images/marker-icon.png'),
  iconSize: [25, 41],
  iconAnchor: [12, 41],
  popupAnchor: [1, -34],
  shadowUrl: require('leaflet/dist/images/marker-shadow.png'),
  shadowSize: [41, 41],
});

const locations = [
  { lat: 51.505, lng: -0.09, text: "Location 1" },
  { lat: 51.515, lng: -0.1, text: "Location 2" },
  { lat: 51.525, lng: -0.12, text: "Location 3" },
];

const Map = () => {
  return (
    <MapContainer center={[51.505, -0.09]} zoom={13} style={{ height: '100vh', width: '100%' }}>
      <TileLayer
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
      />
      {locations.map((location, idx) => (
        <Marker key={idx} position={[location.lat, location.lng]} icon={customIcon}>
          <Popup>{location.text}</Popup>
        </Marker>
      ))}
    </MapContainer>
  );
};

export default Map;

This code maps through the locations array and creates a marker with a popup for each location.

Conclusion

Integrating Leaflet with React to create interactive maps is straightforward and powerful. By following the steps outlined in this blog post, you can set up a React project with Leaflet, add a map, and include custom markers and popups. This foundation allows you to build more complex map-based applications, enhancing user interaction and data visualization. Happy mapping!

Related Posts

Stay Tuned

Want to become a Full-Stack pro?
The best articles, links and news related to web development delivered once a week to your inbox.