Mastering Maps: A Step-by-Step Guide to Setting Up Leaflet.js with React

Hakeem RajiHakeem Raji
5 min read

Navigating the world of geolocation and maps during my recent tech internship was a challenge that led me on a quest to explore Leaflet.js.

In this guide, I'll provide you with a step-by-step tutorial on integrating Leaflet.js seamlessly with React. Let's embark on this mapping adventure together!

Leaflet.js is an open-source JavaScript library for mobile-friendly interactive maps. It's designed with simplicity, performance, and usability in mind. In combination with React, the possibilities for creating dynamic, user-friendly maps are endless.

To achieve this, we use React Leaflet, a set of React components for Leaflet.js maps. React Leaflet provides bindings between React and Leaflet. It does not replace Leaflet but leverages it to abstract Leaflet layers as React components.


Getting Started

Before we dive into the world of maps, assuming you're familiar with React and have a project set up. If that's not the case, please refer to the React documentation first.

Using a package registry, install Leaflet and React-Leaflet:

npm install leaflet react-leaflet

For Typescript support, install Leaflet's type definitions;

npm install -D @types/leaflet

Integration

In this step, let's create a React component for our map container, Map.jsx. Organizing our code in React components enhances maintainability.

Before we proceed, it's important to set up the necessary CSS for our map. We import the required CSS file from Leaflet and define the dimensions for the map container to ensure visibility.

//Map.jsx
import "leaflet/dist/leaflet.css"
.leaflet-container {
    width: 100%;
    height: 100vh;
}

Note: The .leaflet-container class sets the width to 100% and height to 100vh, making the map visible within our React app.

Here's a minimal setup to render a Leaflet map in our React app:

//Map.jsx
import "leaflet/dist/leaflet.css"
import React from "react";
import { MapContainer, TileLayer } from "react-leaflet";

const Map = () => {
    const center = [latitude, longitude]; // Set the center position as an array containing latitude and longitude
    const zoom = 13; // Set an initial zoom level for the map

    return (
        <MapContainer center={center} zoom={zoom} scrollWheelZoom={false}>
            <TileLayer
                attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
                url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
            />
        </MapContainer>
    );
};

export default Map;

Note: In the Map component, the MapContainer component requires a center position specified as an array containing latitude and longitude. The TileLayer component is nested inside the MapContainer, where we specify the map provider (OpenStreetMap in this case) and provide the required props to set it up.

Following these steps, you've successfully set up a Leaflet map in your React app. Organizing the code in React components and ensuring proper CSS and map provider setup are essential for a seamless mapping experience in your web application.


Customisation

Adding markers with popups

To display markers, we use fake data exported from a JavaScript file. The locations.js file exports an array of objects, each containing coordinates and text for the popup:

// locations.js
export const locations = [
    { coordinates: [latitude1, longitude1], text: "Popup text 1" },
    { coordinates: [latitude2, longitude2], text: "Popup text 2" },
    // ... add more locations as needed
];

In our Map.jsx component, we import the locations array and map through it to create markers with popups:

import { MapContainer, TileLayer, Marker, Popup } from "react-leaflet";
import { Icon } from "leaflet";
import { locations } from "./locations";

const Map = () => {
    const center = [latitude, longitude];
    const zoom = 13;

    return (
        <MapContainer center={center} zoom={zoom} scrollWheelZoom={false}>
            <TileLayer
                attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
                url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
            />
            {locations.map((location, index) => (
                <Marker position={location.coordinates} icon={Icon} key={index}>
                    <Popup>{location.text}</Popup>
                </Marker>
            ))}
        </MapContainer>
    );
};

export default Map;

Custom marker icons

To customize marker icons, you can use the Icon class from Leaflet. Here's how you can create a custom marker icon and use it in the Marker component:

import { Icon } from "leaflet";

const customIcon = new Icon({
    iconUrl: "/placeholder.svg", // URL location of the custom icon image
    iconSize: [25, 25], // Size of the icon
});

Changing Map skins

You can change the appearance of your map by switching map providers. You can modify the TileLayer component to use a different map provider. By changing the url property in the TileLayer component, you can use different map providers. You can explore available map providers at Leaflet Providers Preview.


Optimisation

In the realm of creating efficient and trouble-free Leaflet maps, here are some practical pointers to enhance your mapping prowess:

Optimisation:

Cluster Strategically: Prevent map overcrowding by clustering nearby markers. This technique maintains map readability, ensuring a clean and organized visual representation.

Lazy Loading Wisdom: Opt for lazy loading to dynamically load markers based on the visible map area. This approach streamlines your map's performance, making it faster and more responsive.

Troubleshooting:

CSS Rules Matter: If your map disappears unexpectedly, inspect your CSS. Ensure the .leaflet-container has a definite height set. Missing CSS rules can lead to disappearing acts.

Precision with Markers: For accurate marker display, double-check the marker positions and icons. Accurate positioning and visually appealing icons are fundamental for a seamless map interface.

Best Practices:

TypeScript Reliability: Consider incorporating TypeScript for type checking. TypeScript adds an extra layer of confidence to your code, ensuring a robust and error-free mapping experience.

By embracing these strategies, you'll optimize your Leaflet maps and tackle common challenges with finesse, creating maps that are both visually appealing and perform seamlessly. Happy coding! πŸš€πŸ—ΊοΈ


Conclusion

In this guide, we've explored the fundamentals of integrating Leaflet.js with React. Remember, mastering maps comes from exploration and continuous practice.

Keep building, customizing, and refining your maps to elevate your skills. This will empower you to create stunning and interactive maps for your web applications.


Thank you for joining me on this mapping adventure! I hope you found this guide valuable and inspiring for your projects. If you have any questions or want to share your mapping creations, please feel free to reach out. Happy coding!

8
Subscribe to my newsletter

Read articles from Hakeem Raji directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Hakeem Raji
Hakeem Raji

Front End Developer | Passionate about crafting exceptional user experiences | Typescript , React ,HTML, CSS, JavaScript| More than a dev πŸ’» | #WebDevelopment