React + Leaflet: project template and step by step tutorial

This tutorial helps you to create a React-based application with a Leaflet map. We’ve prepared for you a project template and instructions to develop a Map app from scratch.

We use Geoapify map tiles and Mapbox Style specification to create a map. So at the end of the tutorial, your application will be able to render both vector and raster maps with the Leaflet library.

Before you start

Step 1. Create a React project

We’ve prepared a React-based project template for you. The project already contains a component to visualize a map and uses for Sass3 CSS pre-processor:

  • Download or clone the GitHub repository
  • Switch to the project folder: cd react-based-project
  • Run npm install to install libraries and dependencies
  • Run npm start to start the server
  • Open http://localhost:3000 to view the page in the browser

As the second option, you can generate a React project by yourself with Create React App.

Step 2. Display a map with Leaflet

Install Leaflet + Mapbox GL plugin

By default, Leaflet doesn’t support vector tiles and Mapbox Style specifications. You need to install the Mapbox GL Leaflet plugin together with Leaflet to generate a map from style.json:

npm i leaflet mapbox-gl mapbox-gl-leaflet
Add Leaflet and Mapbox styles

You need to import styles to display a map and it’s elements correctly. You can add the styles to the index.scss file:

@import '~mapbox-gl/dist/mapbox-gl.css';
@import '~leaflet/dist/leaflet.css';
Add a map to a React-component

We already prepared a React-component for you – “src/components/my-map.jsx”:

 
import React, { useEffect } from 'react'; 
import './my-map.scss';

function MyMap() {

  useEffect(() => {
    console.log('This is called when the component is mounted!');
  }, []);

  return (
    <div className="map-container">
      <div className="placeholder">
        <span className="placeholder-text">The map will be displayed here</span>
      </div>
    </div>
  )
}

export default MyMap;

Create one if you’ve generated a project with Create React App. Use can use the MyMap component as an example.

  • Remove the placeholder and add the element reference
  • Make the useEffect() function to be called when the element is ready:
import React, { useEffect } from 'react';
import './my-map.scss';

function MyMap() {
  let mapContainer;

  useEffect(() => {

  }, [mapContainer]);

  return (
    <div className="map-container" ref={el => mapContainer = el}>
    </div>
  )
}

export default MyMap;
  • Add a Leaflet map to the component:
import React, { useEffect } from 'react';
import './my-map.scss';
import L from 'leaflet';
import {} from 'mapbox-gl-leaflet';

function MyMap() {
  let mapContainer;

  useEffect(() => {
    const initialState = {
      lng: 11,
      lat: 49,
      zoom: 4
    };

    const map = L.map(mapContainer).setView([initialState.lat, initialState.lng], initialState.zoom);

    // the attribution is required for the Geoapify Free tariff plan
    map.attributionControl.setPrefix('').addAttribution('Powered by <a href="https://www.geoapify.com/" target="_blank">Geoapify</a> | © OpenStreetMap <a href="https://www.openstreetmap.org/copyright" target="_blank">contributors</a>');

    var myAPIKey = 'YOUR_API_KEY_HERE';
    const mapStyle = 'https://maps.geoapify.com/v1/styles/osm-carto/style.json';

    const gl = L.mapboxGL({
      style: `${mapStyle}?apiKey=${myAPIKey}`,
      accessToken: 'no-token'
    }).addTo(map);
  }, [mapContainer]);

  return (
    <div className="map-container" ref={el => mapContainer = el}>
    </div>
  )
}

export default MyMap;

Note! You may require to restart the development server to apply all changes.

Build the application

Run npm run build from the application directory. This builds the app for production to the build folder.

More code sample

Find more Live demos, JSFiddle samples and Code samples on the Geoapify API Documentation page.

Raster vs vector: pros and cons of both map tile types

“Raster vs vector”. Are rater maps outdated and old fashioned? Are vector tiles the new trend in the mapping world? In this article, we will try to cover the advantages and disadvantages of both tile types.

A layer containing the map by itself, streets, rivers, parks, and other objects is a map tiles layer. It underlies every map and is the base layer for a digital map. Map tiles specify how the map will look like, its style and its type. They’re calculated and rendered based on the GIS database and distributed from a map provider server. The server gives away to client tiles on demand. So client applications are able to visualize them as a map.

Until recently, all map tiles were in raster form. However, the market for digital maps and component expands and evolves. Nowadays more and more map provides together with raster maps offer vector map tiles.

From now w have a choice. Raster maps vs vector maps. But what to choose? There are pros and cons for both approaches and both of them have some specifics in implementation.

Raster map tiles

Raster map tiles are images by nature of size optimized for the web. Below you can see examples of raster tiles. Map frameworks and SDKs place raster map tiles in the correct order to generate a map as a result.

Raster map tiles

Pros

  • It’s proven by time technology, which works on all types of devices (desktop and mobile) and all browsers
  • Rendered on a server, raster map tiles do not create performance load on client site

Cons

  • There is no way to customize or add new styles on the client site
  • Not possible to change labels, show/hide objects in the client application
  • During some moment you can see empty areas on the screen on map move/zoom. That is to say, it takes some time until the required tiles are loaded.
Rendering delays while raster tiles loading

Vector map tiles

In comparison to raster tiles, vector tiles are not images, but binary files. They contain all the required information to generate a map on the client side.

Pros

  • Map and labels style can be changed in client application on a fly
  • Tiles have a very small size, which makes them ideal for streaming and offline maps
  • The map is moved, zoomed in/out smoothly without rendering delays

Cons

  • Rendering happens on the client side, which could create performance problems on slow devices
  • Not all SDKs for vector maps have a mobile version yet. It happens that visualization is not correct or too slow on some devices
  • There is no standard, not binding you to a map provider SDKs yet

Vector vs raster map tiles: what to use?

So what to use? It depends on the needs of your application. We would recommend you to go to vector tiles direction if the size of map tiles and styling flexibility is important for your application. And stay with raster version of maps if maps should work on any types of devices, including slow one.

Geoapify offers raster and vector tiles with different styles for your map

With Geoapify APIs you can create a custom map from scratch. We offer different styles for maps, so you can choose a “look and feel” for the map. We have affordable prices and tariff plans for a different load. Furthermore, you can start using our APIs for free and upgrade later to a tariff plan which corresponds to your budget and needs.