Interactive maps are an essential part of many web and mobile applications. They provide users with a visual representation of geographical data enabling them to interact with it in meaningful ways. They transcend the limitations of static maps by offering dynamic features that empower users to explore, analyze, and interact with geographical data in real time.
In this tutorial, you'll learn how to build an interactive map application using React Leaflet and Strapi. By the end of this tutorial, you'll learn how to create a map that displays location markers and enables searching for locations. Additionally, you'll discover how to enable the dragging of markers, display location information including images, and allow the drawing of polygons.
To comfortably follow along, you'll need to have:
Begin by creating the geographic data necessary for pinpointing locations on the map and presenting the relevant information. To achieve this run the following command on the terminal:
npx create-strapi-app@latest my-project
The command will initialize a new Strapi project named my-project. When the initialization is complete, on your terminal, navigate to the my-project
directory and run the following command:
npm run develop
The command will start a development server for your Strapi
project. Open the default Strapi Admin URL http://localhost:1337/admin to access the strapi admin registration panel.
Register yourself to access the admin dashboard.
Click on Content-Type Builder and create a new collection type named Location
and click Continue.
Create five fields named: name
, description
, longitude
, latitude
, and finally photo
. The name
and description
should be of type text, longitude
and latitude
should be of type number, and should hold float number format. And the photo
should be a Media field of type single.
Note: Ensure to click save when you are done creating these fields.
Proceed to the Content Manager and create a new entry. Fill all the fields with the data of the location you want to pinpoint and describe on the map. For the purpose of this tutorial, we will input the data of several capital cities around the world. You can obtain the latitude and longitude coordinates from Google Maps.
Enter as many entries as you wish, after each entry, click Save and Publish respectively.
You now have your data stored in the Strapi database. To expose this data to be used by an application or a program, head to Settings > Users & Permissions Plugin > Roles > Public.
Then click on the location and turn on find
and findOne
.
Proceed to the location endpoint at http://localhost:1337/api/locations?populate=photo
to see the structure of your data. The ?populate=photo
parameter at the end of the URL instructs Strapi to include the associated photo data for each location in the response.
Here is a sample data from the endpoint:
This is the data you will later use to create the interactive map. You now need an app that will use the data to showcase an interactive map.
Navigate to the directory where you want to host your project using your preferred IDE. Then, open the terminal and execute the following command:
npx create-next-app@latest
Choose the following options:
The command will set up a new Next.js
project named map-app
using the latest available version.
Then install the required dependencies using this command:
npm install react-leaflet react-leaflet-draw axios
Here is what each library will do:
react-leaflet
: This library provides React
components for building interactive maps using the Leaflet
JavaScript library. react-leaflet-draw
: This library extends react-leaflet
by providing components for adding drawing functionalities to the map.axios
: This library will make HTTP requests to fetch data from the Strapi API containing the geographical data.react-Leaflet
provides bindings between React and Leaflet, leveraging Leaflet to abstract its layers as React components. It does not replace Leaflet but rather works with it. Both leaflet
and leaflet-draw
are installed as peer dependencies of react-Leaflet
and react-leaflet-draw
respectively.
After the dependencies are installed, you are free to start coding.
On your map-app
project, inside the api
folder of the pages
folder, create a new file named locations.js
. This will be the file containing the code responsible for fetching location data from Strapi.
1// pages/api/locations.js
2import axios from "axios";
3
4export default async (req, res) => {
5 try {
6 const response = await axios.get(
7 "http://localhost:1337/api/locations?populate=photo",
8 );
9 res.status(200).json(response.data);
10 } catch (error) {
11 console.error("Error fetching data:", error);
12 if (error.response) {
13 res
14 .status(error.response.status)
15 .json({ error: error.response.data.message });
16 } else {
17 res.status(500).json({ error: "Error fetching data" });
18 }
19 }
20};
The code utilizes the Axios library for HTTP requests. The route sends a GET
request to the Strapi endpoint. Upon successful retrieval of data, the route responds with a status code of 200
and sends the fetched data as JSON
. Error handling logs any encountered errors and provides appropriate error responses to client requests. This includes both server-generated and network-related errors.
After your app has fetched data from Strapi, you are ready to create the interactive map. Proceed to the map-app
project root directory and create a folder named components
. Then create a component named Map.js
inside this folder.
This file will contain the code responsible for creating and rendering the interactive map. The code has been divided into smaller sub-sections for easier understanding.
Open the Map.js
file and start by importing the required libraries and initializing the state variables:
1// components/Map.js
2import React, { useState, useEffect, useRef } from "react";
3import {
4 MapContainer,
5 TileLayer,
6 Marker,
7 Popup,
8 Polygon,
9 FeatureGroup,
10 useMap,
11} from "react-leaflet";
12import { EditControl } from "react-leaflet-draw";
13import "leaflet/dist/leaflet.css";
14import "leaflet-draw/dist/leaflet.draw.css";
15import L from "leaflet";
16
17const Map = () => {
18 const [locations, setLocations] = useState([]);
19 const [filteredLocations, setFilteredLocations] = useState([]);
20 const [selectedLocation, setSelectedLocation] = useState(null);
21 const [searchQuery, setSearchQuery] = useState("");
22 const [polygonPoints, setPolygonPoints] = useState([]);
23 const mapRef = useRef(null);
Here is a breakdown of what each main component does:
MapContainer
: This is the main container for your map.TileLayer
: It defines the background map tiles.Marker
: It represents location markers on the map.Popup
: This is the information window displayed when clicking a marker.Polygon
: Represents a polygon drawn on the map.FeatureGroup
: Groups your map features together for easier management.useMap
: This is a hook used within the component to access the map instance.EditControl
from react-leaflet-draw
: It enables drawing functionalities on the map.leaflet/dist/leaflet.css
) and Leaflet Draw CSS (leaflet-draw/dist/leaflet.draw.css
): They provide styles for the map and drawing tools.These components will be crucial when adding functionalities to your map.
Inside the Map.js
file, Create a useEffect
hook responsible for fetching location data from the server when the Map
component mounts. For each location, it will extract the URL of the photo associated with that location (if available) and construct the photoUrl
property.
1// components/Map.js
2useEffect(() => {
3 const fetchData = async () => {
4 try {
5 const response = await fetch("/api/locations");
6 const data = await response.json();
7 const locationsWithPhotoUrl = data.data.map((location) => ({
8 ...location,
9 photoUrl: `http://localhost:1337${location.attributes.photo?.data[0]?.attributes?.url}`,
10 }));
11 setLocations(locationsWithPhotoUrl);
12 setFilteredLocations(locationsWithPhotoUrl);
13 } catch (error) {
14 console.error("Error fetching data:", error);
15 }
16 };
17 fetchData();
18}, []);
In the code above, we need to construct the photoUrl
property because the data obtained from strapi includes the relative path. But for the browser to display the image it needs the complete URL else the image won't be visible.
The map needs to respond to user interactions, such as clicking on markers or searching for locations. To achieve this define the relevant event handlers:
1// components/Map.js
2const customIcon = L.icon({
3 iconUrl: "/custom-marker.png",
4 iconSize: [30, 30],
5 iconAnchor: [15, 30],
6});
7
8const handleMarkerClick = (location) => {
9 setSelectedLocation(location);
10 mapRef.current.flyTo(
11 [location.attributes.latitude, location.attributes.longitude],
12 14, // Zoom level
13 );
14};
The code above defines a custom marker icon and creates a handleMarkerClick
function that handles user clicks on markers. When a marker is clicked, it updates the state variable selectedLocation
with the details of the clicked location. This enables the map to display the information about that location. It utilizes the Leaflet flyTo
method to smoothly animate the map view to the coordinates of the clicked location.
The image below is what we used as the custom icon. Make sure to download it and put it inside the public
folder with the name custom-maker.png
.
NOTE: you can use any image of your choice and replace with
custom-marker.png
in your code.
1// components/Map.js
2const handleSearch = () => {
3 if (searchQuery.trim() === "") {
4 setFilteredLocations(locations);
5 setSelectedLocation(null);
6 } else {
7 const filtered = locations.filter((location) =>
8 location.attributes.name
9 .toLowerCase()
10 .includes(searchQuery.toLowerCase()),
11 );
12 setFilteredLocations(filtered);
13 if (filtered.length > 0) {
14 setSelectedLocation(filtered[0]);
15 mapRef.current.flyTo(
16 [filtered[0].attributes.latitude, filtered[0].attributes.longitude],
17 14, // Zoom level
18 );
19 } else {
20 setSelectedLocation(null);
21 }
22 }
23};
The handleSearch
function filters the list of locations based on the user-entered search query, updating the filteredLocations
state accordingly. If there are matching locations, it selects the first one from the filtered list and adjusts the map view to focus on its coordinates. If no matching locations are found, it clears the selected location, providing feedback to the user that no results were found.
1// components/Map.js
2const handleDragMarker = (event, location) => {
3 const newLatLng = event.target.getLatLng();
4 const updatedLocations = locations.map((loc) =>
5 loc.id === location.id
6 ? {
7 ...loc,
8 attributes: {
9 ...loc.attributes,
10 latitude: newLatLng.lat,
11 longitude: newLatLng.lng,
12 },
13 }
14 : loc,
15 );
16 setLocations(updatedLocations);
17 setFilteredLocations(updatedLocations);
18};
The handleDragMarker
function updates the position of a marker on the map when it is dragged by the user. When a marker is dragged to a new location, this function captures the new latitude and longitude coordinates of the marker from the drag event. It then updates the locations state variable by mapping over the existing array of locations and modifying the coordinates of the dragged marker.
For the map to be interactive, allowing users to draw polygons and edit them. You need to handle map interactions.
1// components/Map.js
2const _onCreate = (e) => {
3 const { layerType, layer } = e;
4 if (layerType === "polygon") {
5 setPolygonPoints(layer.getLatLngs()[0]);
6 }
7};
8
9const _onEdited = (e) => {
10 const {
11 layers: { _layers },
12 } = e;
13 Object.values(_layers).map(({ editing }) => {
14 setPolygonPoints(editing.latlngs[0]);
15 });
16};
17
18const _onDeleted = (e) => {
19 const {
20 layers: { _layers },
21 } = e;
22 Object.values(_layers).map(() => {
23 setPolygonPoints([]);
24 });
25};
When a new polygon is drawn, its coordinates are extracted and used to update the polygonPoints
state, reflecting the newly drawn polygon. When it is edited, the updated coordinates are captured and applied to the polygonPoints
state, ensuring that changes to the polygon's shape are reflected. Lastly, when a polygon is deleted, the polygonPoints
state is reset to an empty array, indicating the absence of any polygons on the map.
The final step in creating the interactive map component is rendering the user interface elements:
1// components/Map.js
2 return (
3 <div>
4 <input
5 type="text"
6 placeholder="Search locations"
7 value={searchQuery}
8 onChange={(e) => setSearchQuery(e.target.value)}
9 style={{
10 color: "black",
11 border: "1px solid #ccc",
12 borderRadius: "4px",
13 padding: "8px",
14 }}
15 />
16 <button
17 onClick={handleSearch}
18 style={{
19 backgroundColor: "green",
20 color: "white",
21 border: "none",
22 borderRadius: "4px",
23 padding: "8px 16px",
24 marginLeft: "8px",
25 }}
26 >
27 Search
28 </button>
29 <MapContainer
30 center={[0, 0]}
31 zoom={2}
32 style={{ height: "80vh" }}
33 ref={mapRef}
34 >
35 <TileLayer
36 attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
37 url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
38 />
39 <FeatureGroup>
40 <EditControl
41 position="topright"
42 onCreated={_onCreate}
43 onEdited={_onEdited}
44 onDeleted={_onDeleted}
45 draw={{
46 rectangle: false,
47 polyline: false,
48 circle: false,
49 circlemarker: false,
50 marker: false,
51 }}
52 />
53 </FeatureGroup>
54 {Array.isArray(filteredLocations) &&
55 filteredLocations.map((location) => (
56 <Marker
57 key={location.id}
58 position={[
59 location.attributes.latitude,
60 location.attributes.longitude,
61 ]}
62 icon={customIcon}
63 eventHandlers={{
64 click: () => handleMarkerClick(location),
65 dragend: (event) => handleDragMarker(event, location),
66 }}
67 draggable
68 >
69 <Popup>
70 <div
71 style={{ width: "300px", height: "Auto", paddingTop: "10px" }}
72 >
73 <h3>{location.attributes.name}</h3>
74 {selectedLocation?.id === location.id && (
75 <div>
76 <p>{location.attributes.description}</p>
77 {location.photoUrl && (
78 <img
79 src={location.photoUrl}
80 alt={location.attributes.name}
81 style={{ maxWidth: "100%", height: "auto" }}
82 />
83 )}
84 </div>
85 )}
86 </div>
87 </Popup>
88 </Marker>
89 ))}
90 {polygonPoints.length > 0 && (
91 <Polygon positions={polygonPoints} color="blue" fillOpacity={0.5} />
92 )}
93 </MapContainer>
94 </div>
95 );
96};
97
98export default Map;
The code above renders your map's user interface. It consists of several elements: a search input field, a button for filtering locations, a map container initialized with Leaflet
, a tile layer for displaying map tiles from OpenStreetMap
, and an EditControl
component allowing users to draw and edit polygons on the map. For each filtered location, markers are rendered with custom icons.
Proceed to the index.js
file which is located under the pages
directory and paste the following code:
1// pages/index.js
2import React from "react";
3import dynamic from "next/dynamic";
4
5const Map = dynamic(() => import("../components/Map"), {
6 ssr: false,
7});
8
9const Home = () => {
10 return (
11 <div>
12 <h1>Interactive Map</h1>
13 <Map />
14 </div>
15 );
16};
17
18export default Home;
The code renders the map component with all the interactive features you've implemented, such as displaying location markers, enabling search, allowing marker dragging, and drawing polygons.
Look at how the homepage user interface looks:
It shows all the capital cities whose data is stored in Strapi.
Below is a GIF showing all the features we have implemented:
The GIF shows all the functionalities working seamlessly.
In this tutorial, you have learned to set up Strapi, fetch data, build the interactive map, and integrate it into a Next.js app. This shows how integrating Strapi and React-Leaflet can produce visually powerful maps.
Go ahead and implement more custom functionalities on the map!
Denis works as a software developer who enjoys writing guides to help other developers. He has a bachelor's in computer science. He loves hiking and exploring the world.