Integrating Interactive Mapping into your web application using Leaflet

Integrating Interactive Mapping into your web application using Leaflet

A beginner’s guide to implementing interactive mapping system in a React web application.

·

6 min read

Table of Contents:

  • Introduction

  • Why Leaflet

  • React application Set-up

  • Installing Leaflet

  • Integrating Leaflet into your application

  • Implementing auto geolocation

  • Other additional features

  • Conclusion

Introduction

Hello Coder, in this tutorial we would be learning well about implementing a web application with realistic mapping features. Currently, there are several mapping packages both free and paid provided by several vector-graphics developer organizations. Some of the popular ones include Google Maps API, MapBox, Tom Tom, etc. However, this tutorial promises to be unique as we would implement this feature using Leaflet JS. Now, why are we using leaflet JS?

Why Leaflet JS?

  • Leaflet JS is free. Development has never been more interesting when one can easily try new libraries and easily experiment with new features without losing a cent. Also, for coding hobbyists just like me, free efficient libraries are one’s companion. However, even for big organizations and large-scale products, Leaflet JS still proves efficient and is up to the task.

  • Open Source: An open-source library provides a lot of advantages. Some of these are; the ability to tweak the code to suit one’s interest, provision of access to reusable functionality and increased speed of operations.

  • Enhanced Map graphics: Leaflet JS uses an open source Mapping tool known as OpenStreetMap. This tool provides geographical location data in the vector format which is well interactive and detailed.

  • Lightweight: Research has shown that faster-loading websites tend to give its users a better experience compared to slower-loading sites. With a total package size of just 42 kilobytes, it is just the perfect package providing features that conveniently rival Google Map API.

Having gone through the benefits of Leaflet, let’s move on to setting up the tutorial. First of all, to fully understand this tutorial, there are some basic requirements expected of you. These are;

  • Having a basic knowledge of JavaScript and React

  • Knowledge of NPM package installation

  • Having access to a steady Internet connection

  • Willingness to learn new things

React Application Set-up

So right now, let’s set up our React web application. First, navigate to the folder you intend to create your project using the command prompt. The enter npm create-react-app React-map-app

Wait for a few minutes and viola, your web application is set up. You can then navigate to the project folder and launch the application by entering npm start on the command prompt.

Navigating to http://localhost:3000 will show your default react home screen.

Installing Leaflet JS:

Right now, let’s return back to our command prompt user interface. To successfully integrate Leaflet, we would need to install 2 packages namely; React-leaflet and Leaflet.

Leaflet: This package is the default mapping package generally deployed for applications (web, mobile, desktop)

React-leaflet: the package is an implementation of Leaflet in React applications. It also provides methods containing functions that can be easily imported into react codes.

Now, let’s move on to the installation process. We would now install these packages by running npm i react-leaflet leaflet in the command prompt. With that, we have now completed the installation process.

Integrating Leaflet into your application

Having completed the installation, we would now implement a basic web application showing an interactive map.

Open the project file in the code editor and edit the app.jsx file.

import L from 'leaflet';

This imports the default Leaflet library into the web application. It also provides some default map icons which can then be modified.

import leaflet/dist/leaflet.css

import {MapContainer, TileLayer, Marker,useMapEvents, useMap} from 'react-leaflet';

This statement must be imported to ensure that your map shows on the screen as it provides the necessary styling to give your map its default look.

The MapContainer components wrap up the entire map application. It has some variables that help to ensure the map is properly displayed.

Center: This variable takes the desired longitude and latitude as an array the user enters and renders it on the web application page.

Zoom: This variable helps to determine the depth of the map you intend to see. You can also adjust it by clicking on the + button on the edge of the screen.

TileLayer: This displays the vector images of the map. This vector image is provided by OpenStreetMap.

The Full Code:

import React from 'react';
import "leaflet/dist/leaflet.css"
import L from 'leaflet';
import {MapContainer, TileLayer, Marker, useMapEvents} from 'react-leaflet';


delete L.Icon.Default.prototype._getIconUrl;

L.Icon.Default.mergeOptions({
    iconRetinaUrl: require('leaflet/dist/images/marker-icon-2x.png'),
    iconUrl: require('leaflet/dist/images/marker-icon.png'),
    shadowUrl: require('leaflet/dist/images/marker-shadow.png')
});

const Mappy = () => {
    return (
        <div>
<MapContainer   center={[42.3265, -122.8756]} zoom={6} 
        style={{ height: "100vh", width: "100%",position: "relative" }} whenCreated={setMap}>
      <TileLayer
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
      />
</MapContainer>
        </div>
    )
}

export default Mappy

Running this code will give you this;

Implementing Auto Geo-Location

Now to round up our tutorial on Leaflet JS, let’s implement an auto geo-locate mapping feature on our web application.

The Geo-locate (useEffect function) Code:

  useEffect(() => {
        if (!map) return;

        L.easyButton("fa-map-marker", () => {
          map.locate().on("locationfound", function (e) {

            map.flyTo(e.latlng, map.getZoom());
          });
        }).addTo(map);
      }, [map]);

This code uses the useEffect function.

Leafltet package provides an easyButton feature that comes pe-implemented. On clicking this button, an anonymous function begins execution.

This function runs by default immediately after the web page is loaded or if there is any change in the initial function. The function locate() is executed and tries to locate the web application user location making use of the coordinates. It then flies to the location and zooms on it to be more precise.



import React from 'react';
import "leaflet/dist/leaflet.css"
import L from 'leaflet';
import {MapContainer, TileLayer, Marker,useMapEvents, useMap, Popup} from 'react-leaflet';
import { useEffect } from 'react';

delete L.Icon.Default.prototype._getIconUrl;

L.Icon.Default.mergeOptions({
    iconRetinaUrl: require('leaflet/dist/images/marker-icon-2x.png'),
    iconUrl: require('leaflet/dist/images/marker-icon.png'),
    shadowUrl: require('leaflet/dist/images/marker-shadow.png')
});

const Mappy = () => {
    const [map, setMap] = useState(null);

    useEffect(() => {
        if (!map) return;

        L.easyButton("fa-map-marker", () => {
          map.locate().on("locationfound", function (e) {

            map.flyTo(e.latlng, map.getZoom());
          });
        }).addTo(map);
      }, [map]);



    return (
        <div>
<MapContainer   center={[42.3265, -122.8756]} zoom={6} whenCreated={setMap}
        style={{ height: "100vh", width: "100%",position: "relative" }} whenCreated={setMap}>
      <TileLayer
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
      />
</MapContainer>
        </div>

    )

}

export default Mappy

Upon running this, your computer if GPS enabled will send a prompt to allow access to the device location. It will then use the coordinates provided to approximate a location.

Other Features

I hope this tutorial has given you enough flames to spark your creative ideas to life. You can explore generating the longitude and latitude features included in the react-leaflet and then compute the distance between two cities or countries.

Also, there is the Map Icon landmark feature which can be implemented to aid the tracking of crime and other community-wide activities. I am still discovering new features included in the leaflet library and I would also encourage you to do so too. Feel free to send a comment if you need a bit of assistance with any advanced leaflet feature or make a reference to the Leaflet documentation here.

Conclusion

So we have been able to harness the power of Leaflet in generating a realistic, interactive map feature for our web application. We have also enjoyed its simplicity and speed but there are still a whole lot of untapped features that Leaflet has to offer which we didn’t delve into in this tutorial which you can still learn about.

I sincerely hope you learned and enjoyed this innovative tutorial on integrating mapping features in your web app. Feel free to check out my other article here. Till next time, keep on coding.