Step-by-Step Guide: Integrating Leaflet and React.js with GeoJSON for Dynamic Maps

Step-by-Step Guide: Integrating Leaflet and React.js with GeoJSON for Dynamic Maps
Photo by GeoJango Maps / Unsplash

Leaflet is a leading open-source JavaScript library for mobile-friendly interactive maps. Integrating it with React.js to display a map with multiple markers using GEOJson data is a powerful combination for web mapping applications.

What is GeoJSON?

GeoJSON is a format for encoding geographic data structures using JavaScript Object Notation (JSON). It is commonly used for representing geographical features such as points, lines, polygons, and collections of these objects.

Some use cases of GeoJSON include:

  • Storing and exchanging geographic data in a standardized format.
  • Displaying and visualizing geographic data on maps.
  • Performing spatial analysis and geoprocessing tasks.

Key features of GeoJSON include:

  • Support for different geometry types, such as Point, LineString, Polygon, MultiPoint, MultiLineString, and MultiPolygon.
  • Ability to represent feature collections, which can contain multiple features.
  • Support for properties to associate additional attributes with geographic features.
  • Flexibility in representing both simple and complex geometries.

GeoJSON provides a widely adopted and interoperable format for working with geographic data in various applications and platforms.

This Tutorial

This tutorial will guide you through setting up Leaflet with React.js and adding a GEOJson feed to display multiple markers.

Prerequisites

  • Basic knowledge of React.js
  • Node.js and NPM installed

Setting Up Your React Project

First, create a new React application if you haven't already:

npx create-react-app leaflet-react-demo
cd leaflet-react-demo

Installing Dependencies

You need to install leaflet and react-leaflet, which is a React wrapper for Leaflet:

npm install leaflet react-leaflet

Also, install leaflet-defaulticon-compatibility to fix an issue with the default marker icon path in Leaflet when used with Webpack:

npm install leaflet-defaulticon-compatibility

Setting Up the Map Component

Create a new component for your map. Let's call it MapView.js. First, import necessary modules and set up Leaflet's CSS:

import React from 'react';
import { MapContainer, TileLayer, GeoJSON } from 'react-leaflet';
import 'leaflet/dist/leaflet.css';
import 'leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.css';
import L from 'leaflet';
import 'leaflet-defaulticon-compatibility';

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

export default MapView;

In this component:

  • MapContainer is the container for the map.
  • TileLayer is the layer for the map tiles, using OpenStreetMap in this example.
  • GeoJSON will be used to render the GEOJson feed.

Adding GEOJson Data

For this tutorial, we'll use a simple GEOJson object. In a real-world scenario, this data might come from an API or a static file:

// Add this inside your MapView.js or import it from an external file
const geojsonData = {
    "type": "FeatureCollection",
    "features": [
        {
            "type": "Feature",
            "properties": { "name": "Location 1" },
            "geometry": {
                "type": "Point",
                "coordinates": [-0.09, 51.505]
            }
        },
        // ... more features
    ]
};

Pass this data to the MapView component.

Integrating the MapView Component in Your App

Now, integrate the MapView component into your main app. In App.js, import and use MapView:

import React from 'react';
import './App.css';
import MapView from './MapView'; // adjust the path as necessary

function App() {
  return (
    <div className="App">
      <MapView />
    </div>
  );
}

export default App;

Customizing Marker Appearance (Optional)

To customize the appearance of markers or add popups, you can modify the GeoJSON component. For instance, you can define a pointToLayer function to customize markers:

<GeoJSON
    data={geojsonData}
    pointToLayer={(feature, latlng) => {
        return L.marker(latlng, { /* options */ });
    }}
/>

Or, use onEachFeature to add popups:

<GeoJSON
    data={geojsonData}
    onEachFeature={(feature, layer) => {
        if (feature.properties && feature.properties.name) {
            layer.bindPopup(feature.properties.name);
        }
    }}
/>

Conclusion

You have now set up Leaflet with React.js and added a GEOJson feed to display multiple markers. This setup allows you to integrate interactive maps into your React applications effectively.

You can further explore Leaflet's extensive features to add more functionalities like custom marker icons, event handling, and more.

Read more