A Quick Guide to Integrating Leaflet.js and React
An easy tutorial for showing different locations on a map in a React app
We live in a fascinating, yet confusing time for web developers. With so many frameworks, libraries, plugins, and who-knows-what-else, it is sometimes hard to decide which to use and how to integrate them to work in synergy.
It gives you the ability to easily display tiled web maps, hosted on a public server, with optional tiled overlays.
So, let’s see how we can integrate it into our React App with the fewest steps possible.
As of September 2019, this is the structure of the created project:
Now, let’s add the Leaflet library. In the project directory, run:
npm install leaflet
Finally, we should add the CSS reference in our
<link rel="stylesheet" href="https://email@example.com/dist/leaflet.css" />
Cool, now we are ready to create our map component. We will use OpenSteetMap as our tile source and position the center at my home town — Sofia, Bulgaria.
The next step is to level up and add a marker to our map. As an example, I will use the coordinates of the Bulgarian National Assembly Building.
Now, you would probably say: “Yeah, a map with a static marker….Very useful, thank you”. But hold on, Leaflet is capable of much more and we are just warming up.
What fascinated me when I first got to know the library is how easy it is to show simple geographical features on the map, presented in GeoJSON format.
Basically, GeoJSON is an open-standard format, designed for representing simple geographical features — points (addresses and locations), line strings (streets, public transport lines, etc.), polygons (regions, states, etc.).
The great thing about it is that it is based on the well-known JSON format.
For our example, I will use a simple GeoJSON, found on the internet, representing the different regions in Sofia.
And here is the result:
Let’s now build upon this a little more. We will add the functionality to move the marker at the center of the polygon when the user clicks on one and paint it in a different color.
For this, we will need two things:
- Store the selected feature (polygon) in the component’s state.
- Add it to the
If you are still new to React Hooks, I highly recommend checking out Dan Abramov’s post Making Sense of React Hooks.
To calculate the center of the polygon, we will use the formula for finding the centroid of a non-self-intersecting closed polygon, defined by n vertices (x0,y0), (x1,y1), …, (xn−1,yn−1).
Props to this StackOverflow answer.
And lastly, we will add a click handler on each feature, where we will set the newly selected one, calculate the centroid, and set the new position of the marker.
So, that is a simple and quick way to integrate LeafletJS in a React component. Of course, there are numerous ways to improve it further.
I hope that this article will save some time for its readers.