Post Top Ad

GIS Tutorial Blogs

Education Blogs

Post Top Ad


Leaflet JS Tutorial For Beginners To Create A Stunning Mobile Friendly Web Map


Leaflet JS is an open-source Javascript Library to create an amazing mobile-friendly and interactive web map. It allows that developer who doesn’t have a GIS background to create a Web Map. It can import feature data from GeoJSON files, style it, and provide interactive layers, such as markers that open popups when clicked.


Web Map Service (WMS), GeoJSON, Vector, and Tile layers are all natively supported by Leaflet. Plugins can support a wide range of additional layer types.


As with other online map frameworks, Leaflet's default display configuration consists of one base map, one or more transparent overlays, and one or more vector objects shown on top.


This leaflet tutorial will guide you throughout the process of creating an amazing web map with a leaflet along with examples and code.

Prerequisites

Before going through the leaflet tutorials, you must know the basics of the following:

  • HTML (Hyper Text Markup Language). 


Table of Contents

  1. Preparing The Page
  2. Initialize the Map Layer
  3. Add a marker in Leaflet
  4. Add Different Tile Layer in Leaflet
  5. Layer Control in Leaflet
  6. ExtrasGeoJSON In Leaflet
  7. Choropleth Map In Leaflet
  8. Search Button In Leaflet
  9. Conclusion


1. Preparing The Page

We will be using Visual Studio Code to edit our code. We will also be using Leaflet CDN. It is the hosted version of Leaflet.


Paste the below CDN code in the header section of your code.

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.8.0/dist/leaflet.css" integrity="sha512-hoalWLoI8r4UszCkZ5kL8vayOGVae1oxXe/2A4AO6J9+580uKHDO3JdHb7NzwwzK5xr/Fs0W40kiNHxM9vyTtQ=="crossorigin=""/>

Also, Include the Leaflet JavaScript file after Leaflet’s CSS:

<!-- Make sure you put this AFTER Leaflet's CSS --> <script src="https://unpkg.com/leaflet@1.8.0/dist/leaflet.js" integrity="sha512-BB3hKbKWOc9Ez/TAwyWxNXeoV9c1v6FIeYiBieIWkpLjauysF18NzgR1MBNBXf8/KABdlkX68nAhlwcDFLGPCQ==" crossorigin=""></script>

After adding our Leaflet CDN and Leaflet Javascript file into our header section of our code. You code now must look like this.

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Leaflet Tutorial</title> <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" /> <link rel="stylesheet" href="https://unpkg.com/leaflet-control-geocoder/dist/Control.Geocoder.css" /> </head> <body> </body> </html>

We will now create a div section inside our body with an id=’map’ which denotes the section where our map will be shown in the website.

<div id="map"></div>

As we go ahead with the tutorial, we will need to give styling to our map. So, we will create a style inside the header. The basic styling will be given that includes a certain height and weight of the map section in order to show our map.

<style> #map{ height: 100vh; width: 100%; } </style>



You will see your code like this:


<html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Document</title> <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A==" crossorigin="" /> <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js" integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA==" crossorigin=""></script> <style> #map { width: 100%; height: 100vh; } </style> </head> <body> <div id="map"></div> </body> </html>

2. Initialize the Map Layer

We will now work in JavaScript from here. To initialize our map we will create a variable name map and set the view to our desired geographic location.


var map = L.map('map').setView([40.7128,-74.0060], 4);


Here, 40.7128, -74.0060 denotes the geographic latitude and longitude whereas 4 refers to the zoom level. Since, the map is dynamic, a proper zoom level will make the map more interactive. Less the zoom level, the extent to which the detail is shown in limited i.e it will be zoomed to large area, while more zoom level gives the detailed information to the minor location as well.




We now add a tile layer to our map. For the example, we will use OpenStreetMap Layer. Typically, creating a tile layer involves specifying the URL template for the tile images, the attribution text, and the layer's maximum zoom level.



Read more documentation here:



https://leafletjs.com/examples/quick-start/




var osm = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' }); osm.addTo(map);


After you run the code, you will see the output like this:


3. Add a marker in Leaflet




Now, we will create a marker in the leaflet map. Along with a marker you can create a bind popup that will show some information when clicking the marker.


var singleMarker = L.marker([28.25255,83.97669]); singleMarker.addTo(map); var popup = singleMarker.bindPopup('This is a popup') popup.addTo(map);


You can also add polygons of different shapes and sizes including the circle of a certain radius around the given geographic location, a polygon connecting different locations.



Add a circle:


var circle = L.circle([51.508, -0.11], { color: 'red', fillColor: '#f03', fillOpacity: 0.5, radius: 500 }).addTo(map);


Add a polygon:


var polygon = L.polygon([ [51.509, -0.08], [51.503, -0.06], [51.51, -0.047] ]).addTo(map);

Figure: Marker In Leaflet

4. Adding Different Tile Layer In Leaflet

We can use different map tile layers as our base map in Leaflet. You can find them from https://leaflet-extras.github.io/leaflet-providers/preview/


Add tile layers:


var CartoDB_DarkMatter = L.tileLayer('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png', { attribution: '© OpenStreetMap contributors © CARTO', subdomains: 'abcd', maxZoom: 19 }); CartoDB_DarkMatter.addTo(map); // Google Map Layer googleStreets = L.tileLayer('http://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}',{ maxZoom: 20, subdomains:['mt0','mt1','mt2','mt3'] }); googleStreets.addTo(map); // Satelite Layer googleSat = L.tileLayer('http://{s}.google.com/vt/lyrs=s&x={x}&y={y}&z={z}',{ maxZoom: 20, subdomains:['mt0','mt1','mt2','mt3'] }); googleSat.addTo(map); var Stamen_Watercolor = L.tileLayer('https://stamen-tiles-{s}.a.ssl.fastly.net/watercolor/{z}/{x}/{y}.{ext}', { attribution: 'Map tiles by Stamen Design, CC BY 3.0 — Map data © OpenStreetMap contributors', subdomains: 'abcd', minZoom: 1, maxZoom: 16, ext: 'jpg' }); Stamen_Watercolor.addTo(map);

5. Layer Control In Leaflet

Leaflet offers an option to control the layer which you want to show on your map. Working with many layers sometimes might not be productive, so using layer control might help you turn off that layer and work on the one you want.

There are two types of layers:

1) Base Layer: The one you put in the background, i.e different layers of the map. For this purpose, we will use all the above tile layers that we created.

2) Overlays: These are all the other stuff that you put above the base layer that may be markers, polygons, geojson files, and many more.



Figure: Example of Layer Control

Example:


var baseLayers = { "Satellite":googleSat, "Google Map":googleStreets, "Water Color":Stamen_Watercolor, "OpenStreetMap": osm, }; var overlays = { "Marker": singleMarker, "PointData":pointdata, "LineData":linedata, "PolygonData":polygondata }; L.control.layers(baseLayers, overlays).addTo(map);

6. Extras
There are many features that are available in Leaflet, using them you can create a useful and informative map for your website. Some of them are listed below
6.1. GeoJSON In Leaflet
You can add your own location, line, or polygon inside the overlay layer using GeoJSON file format. The below video shows the way to add the GeoJSON file in Leaflet.




6.2. Choropleth Map In Leaflet
Another way to make your map beautiful and informative is making them choropleth. A choropleth map visualizes the statistics in a map using different color shades. The different color shades makes the map more pleasing. We can use leaflet to create a choropleth map for our website. The below video shows the way to create a choropleth map in leaflet.

6.3. Search Button In Leaflet

Another important feature of the leaflet is the search feature using which we can search around the different locations in the map. The below video shows how to create a search button in the leaflet.



7. Conclusion

In conclusion, we have learned a basic of using Leaflet to add a web map to your website. We learned to add a base map, marker, polygon, layer control, GeoJSON file format, create a choropleth map in the leaflet, search button in a leaflet, and many more. I hope this tutorial was helpful.

You can find the entire code here: https://github.com/Gauravparajuli09/leaflet

Also, I have created a whole playlist of Leaflet JS Tutorial on Youtube. You can watch the entire video here:











Thank you very much for visiting this site. 😊





Realted Posts

No comments:

Post a Comment

Post Top Ad