Geolocation Data Visualization with React Using Leaflet Interactive Maps Library (pt.1)

Mahdi Haris
3 min readOct 12, 2020

--

Leaflet Logo

Before we deep dive into the map, you might be interested to visualize your data with graphics using Highcharts.

I will divide this topic into 2 parts. In this first article, I will explain how to start implementing Leaflet in your React project using React-Leaflet and the second article will be about how to customize react-leaflet maps and make it more interactive.

We need to install the packages that we will use in our project:

Using NPM:

npm install leaflet react-leaflet

Using Yarn:

yarn add leaflet react-leaflet

There’s a couple of steps just to show the map that Leaflet has provided. After we installed those packages, we need a file to create our map component.

import React from 'react';
import { Map, TileLayer } from 'react-leaflet';
function LeafletDemo() {
return (
<Map>
<TileLayer
attribution='&amp;copy
<a href="http://osm.org/copyright">
OpenStreetMap
</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
</Map>
)
}

What will happen if we run the code? Well, we’re not done and the code won’t show the map. We will get this white screen with unstyled zoom in and out buttons and a hyperlink to https://leafletjs.com

Next, we need to add styles to our map. We can add the leaflet CSS file from its source in the index.js file.

import 'leaflet/dist/leaflet.css';

After we import the CSS file and try a re-run, we will get a total white screen. It’s absolutely okay! We just need to add a class in our own CSS file. In this case, I will add it to the index.css file.

.leaflet-container {
width: 100%;
height: 100vh;
}

No! The map still won’t show up! , now we’re just one step further to get into it! The Map component from ‘react-leaflet’ needs 2 props to make it work:

  1. zoom (to show how much zoom do we want when the map renders for the first time)
  2. center (where we want to locate the map focus on the first render)

Now we’re gonna set zoom to 12 and the center will be at the Jakarta History Museum (Museum Fatahillah). Therefore, the map component will look like this.

import React from 'react';
import { Map, TileLayer } from 'react-leaflet';
function LeafletDemo() {
return (
<Map zoom={12} center={[-6.134506, 106.813408]}>
<TileLayer
attribution='&amp;copy
<a href="http://osm.org/copyright">
OpenStreetMap
</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
</Map>
)
}

Voila! The map has been perfectly rendered! So, now we’re done in this part to get started with React-Leaflet. We will talk about how to make this map even more interactive in the next part.

--

--