Getting Started with building Maps with React and Leaflet.

Peter Ayeni
Nov 23, 2020 · 6 min read
Getting Started with building Maps with React and Leaflet.
Getting Started with building Maps with React and Leaflet.
Photo by NASA on Unsplash

Introduction

A map is a symbolic depiction emphasizing relationships between elements of some space, such as objects, regions, or themes.. Many maps are static, fixed to paper or some other durable medium, while others are dynamic or interactive.

— Wikipedia

Today Maps have become an integral part of my life I would probably get lost in London in some minutes without the help of a Map application on my phone. Aside from city navigation Maps have also had a lot of use cases in application development today, from data visualization, weather forecast, disaster response to big organizations who use Map to help customers find their branches across the globe.

I currently work as a Frontend Engineer at Previsico where we are using cutting edge technology to provide real-time street-level flood warnings. So work on creating a great Map experience for our customers on a daily basis. In this article, I am going to share how you can get started creating Maps to React with Leaflet and links to other resources to help you learn more.

Background

For this article, I will assume you are some working knowledge of JavaScript and especially the ES6 syntax, a basic understanding of React, and the new features Hooks.

Technologies

In this tutorial, we will be using the following technologies:

Create React App Set up a modern web app by running one command.

You don’t need to learn and configure many build tools. Instant reloads help you focus on development. When it’s time to deploy, your bundles are optimized automatically. — Create React App

Leaflet is the leading open-source JavaScript library for mobile-friendly interactive maps. Weighing just about 39 KB of JS, it has all the mapping features most developers ever need.

React Leaflet React components for Leaflet maps

GeoJson GeoJSON is an open standard format designed for representing simple geographical features, along with their non-spatial attributes. It is based on the JSON format. The features include points, line strings, polygons, and multi-part collections of these types. — Wikipedia

VS Code Editor Code editing. Redefined. Free. Built on open source. Runs everywhere. Note: You can use any editor of your choice, I recommend VS Code if you don’t have a preference.

Setup

We will be creating a new React Application using Create React App use the command below where map-tutorial is the project name.

npx create-react-app map-tutorial
cd map-tutorial
npm start

If you’ve previously installed create-react-app globally via npm install -g create-react-app, we recommend you uninstall the package using npm uninstall -g create-react-app or yarn global remove create-react-app to ensure that npx always uses the latest version. — Create React App

or yarn

yarn create react-app map-tutorial
cd map-tutorial
yarn start
Image for post
Image for post

Installing Leaflet and React Leaflet

npm install -s leaflet react-leafletor with yarnyarn add leaflet react-leaflet

Getting Started

Understanding how Leaflet and React-Leaflet work together is of utmost importance. React-Leaflet provides us easy to use React components that bind to Leaflet. Understanding how Leaflet work is highly recommended so check out the Leaflet Documentation.

<!-- public/index.html --><link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css"integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="crossorigin=""/><!-- Make sure you put this AFTER Leaflet's CSS --><script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="crossorigin=""></script>

Place the above Leaflet CSS and JavaScript into the head section of your project index.html in the public folder. This will ensure will load all the Leaflet specifics CSS and JavavaScripts and make sure they are in pasted in that particular order, the CSS and the JS.

Clear out the code in the App.css and place the below CSS

<!-- App.css -->.main {height: 100vh;width: 100%;}

Here we define the `main` CSS class with a height of 100vh and width of 100%, this will make the map to take the whole browser viewport.

Creating our first Map, rendering a Marker and a Popup.

Image for post
Image for post

From the above code, you can see how React-Leaflet gave us an easy component to use that render the corresponding Leaflet element. We import MapContainer,TileLayer Marker and Popup from react-leaflet.

MapContainer

This is a parent container that renders Leaflet Map instance it takes props to set the initial behaviour of the map. center takes an array of Latitude and Longitude so the map centre at that position on the initial load, zoom this set the initial zoom to 13, scrollWheelZoom takes a boolean value it enables zooming with scroll wheel either it set to true or false, we also pass the .main class from App.css that set the height and width of the map. There are other props that MapCaontainer takes you can look up the React-Leaflet documentation.

TileLayer

This renders the map tiles, for this map we are using OpenStreetMap their other several map tile services we can use, OpenStreetMap is free to use.

Image for post
Image for post

Marker

Maker also takes a position which is an array of Longitude and Latitude that set the location of the Marker on the Map.

Popup

The Maker takes a Popup child component, so when the Marker is clicked the Popup is displayed.

Image for post
Image for post

And we have a fully functional map in React that you can use as a starting point for your next map project.

Understanding GeoJson

Image for post
Image for post

The code above is an example of how a GeoJson file is structured, you can see it’s similar to JSON just with some unique features that made it work with Map information and features. Let take a closer look at it.

{
"type": "FeatureCollection",
"features": []
}

At the top level, we have the type key of FeatureCollection and also a features key which will hold an array of different kinds of features. Let take a look at a single feature.

{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "school",
"name": "Camberwell College of Arts"
},
"geometry": {
"type": "Point",
"coordinates": [
-360.08029460906977,
51.47421967407655
]
}
},
]
}

Now in the features array, we have a single feature, there are two things to take note of where properties this can be any kind of properties we want this particular feature to have and geometry this is the main map feature which is of type point. There are other types like LineString, Polygon and there are others you can look up in the documentation.

Conclusion

Either you want to add a simple Maps to your React Application or you are building a full-fledge mapping dashboard I hope this gave you a headstart you need to venture into creating Maps.

Weekly Webtips

Explore the world of web technologies through a series of tutorials

Sign up for 💌 Weekly Newsletter

By Weekly Webtips

Get the latest news on the world of web technologies with a series of tutorial Take a look

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

Peter Ayeni

Written by

I change the world by helping people to get started in Tech and Social Entrepreneurship.

Weekly Webtips

Explore the world of web technologies through a series of tutorials

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store