Hello readers!

Today in this article we will see how to create a map using React, vanilla.js and Leaflet. Before getting into the topic, let’s see about leaflet- it is a powerful tool for building maps. We can create different kinds of maps using this tool. It supports in all web browsers and mobile platforms.

In this project, we are going to represent the locations to the non-medical fire incidents. The Fire Department responded on a map. we are marking only the locations of the fire incidents and display some details about it.

Let’s create a simple example. Now we can setup a Leaflet map, working with markers, and popups.

Let’s get started

The First step, let’s create index.html and app.js files in our /project folder and link to our index.html file.

By using Leaflet, we have to link Leaflet CSS and Leaflet JS in our head tags. Always keep the Leaflet CSS before Leaflet JS.

Add a container that will hold our map to our index.html:

<div id="mapid"></div>

Before that lets set height to our container:

#mapid { height: 1000px; }

Now create a new JavaScript file in script tags and make sure that 

 is added to the dom before calling L.map(’mapid’).

Creating a map

To initialize the map we have to pass the div to L.map() with some options.

const myMap = L.map('mapid', {
 center: [37.7749, -122.4194],
  zoom: 13

The first step we have to use Map class of Leaflet API to create a map on the page. And then we will pass two parameters to this class:

  • We passed a string variable to the DOM ID.
  • An optional object to the map options.

There are many options available we could pass to our class. The main two options are the center and the zoom. The center is an initial geographic centre. The zoom specifies an initial map zoom level.

To initializing the map by using setView(). The coordinates and an integer are assigned in an array for the zoom level.

const myMap = L.map('map').setView([37.7749, -122.4194], 13);

By default, all the mouse and touch controls are enabled on the map.

Creating A Layer

Now we can add a tile layer to our map i.e. a Mapbox Streets tile layer. We can add different types of tile layers by instantiating the TileLayer class.

To create a tile layer first we have to set the URL template for the tile image, the attribution text, and the maximum zoom level of the layer. The URL template will give access to the tile layer from the service provider. And then we are using Mapbox’s Static Tiles API so we need to request an access token.

#web-development #typescript #javascript #react #programming

How to Create a Maps using React, Vanilla JS and Leaflet
12.40 GEEK