0% found this document useful (0 votes)
57 views39 pages

WebGIS Leaflet

Uploaded by

Aparupa Rez
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views39 pages

WebGIS Leaflet

Uploaded by

Aparupa Rez
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

Javascript Library for WebGIS Application

Leaflet
Leaflet
 Leaflet is the leading open-source JavaScript library for mobile-
friendly interactive maps.
 Weighing just about 42 KB of JS, it has all the mapping features
most developers ever need
 Leaflet is designed with simplicity, performance and usability in
mind.
 It works efficiently across all major desktop and mobile platforms,
can be extended with lots of plugins, has a beautiful, easy to use
and well-documented API and a simple, readable source code that
is a joy to contribute to.
Version
Version Description
Stable version, released on MAY 18,
Leaflet 1.9.4
2023.
Previous stable version, released on
Leaflet 1.8.0
April 18, 2022.
In-progress version, developed on
Leaflet 2.0-dev
the main branch.

Link to download: https://leafletjs.com/download.html


Advantages of Leaf let
 Simplicity: Leaflet is designed to be small and simple, making it easier to
learn and use compared to OpenLayers, which can be more complex and
difficult to navigate for beginners.
 Lightweight: Leaflet is a lightweight library, making it faster and more
efficient for web mapping applications.
 Mobile-Friendly: Leaflet has a mobile-first design approach and is optimized
for mobile devices, which makes it well suited for web mapping applications
that need to work on both desktop and mobile devices.
 Active Community: Leaflet has a large and active community of developers
and users who contribute to the development and maintenance of the library.
This results in a steady stream of updates, bug fixes, and new features.
 Plugins and Extensions: Leaflet has a large collection of plugins and
extensions that can be used to add additional functionality to the library, such
as adding markers, popups, and other features.
How to use leaflet
 Create HTML page
 Load the css and javacript of css in head tag of html file:
 <link rel="stylesheet"
href="https://unpkg.com/[email protected]/dist/leaflet.css" integrity="sha256-
p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin=""
/>
 <script src="https://unpkg.com/[email protected]/dist/leaflet.js"
integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo="
crossorigin=""></script>Create container
 Map options
 Create map object
 Create layer object
 Add layer to map
Using a Downloaded Version of Leaflet
 Unzip the downloaded archive to your website’s directory
 Inside the archives downloaded from the above links, you will see
four things:
 leaflet.js - This is the minified Leaflet JavaScript code.
 leaflet-src.js - This is the readable, unminified Leaflet JavaScript,
which is sometimes helpful for debugging. (integrity=”sha256-
V8Wsw6bWrfTsX9YUzIjKtnIoiUhBdulszoxf177/XjU=”)
 leaflet.css - This is the stylesheet for Leaflet.
 images - This is a folder that contains images referenced
by leaflet.css. It must be in the same directory as leaflet.css.
Create HTML page and load CSS and JS
 <html>
 <head> <title>Leaflet demo</title>
 <link rel="stylesheet" href="leaflet.css" /> <script
src="leaflet.js"></script>
 </head>
 <body>
Create container in html
 To hold the map, we have to create a container element.
Generally, the <div> tag (a generic container) is used for this
purpose.
 Create a container element and define its dimensions :
 <div id = “map" style = "width:800px; height:480px;"></div>
Map Options
 Create a mapOptions object (it is created just like a literal) and
set values for the options center and zoom,
 center − As a value to this option, you need to pass
a LatLng object specifying the location where we want to center
the map.
 specify the latitude and longitude values within [18.5204,
73.8567]
 zoom −you need to pass an integer representing the zoom level of
the map,.
 var mapOptions = { center: [18.5204, 73.8567], zoom: 10 }
Map options
 Leaflet provides several options such as types Control options,
Interaction Options, Map State Options, Animation Options, etc.
 By setting values to these, we can customize the map as desired.
Create a Map Object
 Using the Map class of leaflet API, you can create a map on a page.
 You can create a map object by instantiating the called Map of the
Leaflet API.
 While instantiating this class, you need to pass two parameters
 As a parameter to this option, you need to pass a String variable
representing the DOM id or an instance of the <div> element.
 Here, the <div>element is an HTML container to hold the map.
 An optional object literal with map options.
 Create a Map object by passing the id of the <div> element and
mapOptions object created in the previous step.
 var map = new L.map('map', mapOptions);
Creating the Layer Object
 You can load and display various types of maps (tile layers) by
instantiating the TileLayer class.
 While instantiating it you need to pass an URL template requesting the
desired tile layer(map) from the service provider, in the form of a String
variable.

 var layer = new


L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');

 we have used the openstreetmap.


Add Layer to the Map
 add the layer created in the previous step to the map object using
the addlayer() method as shown below.

 map.addLayer(layer);
!DOCTYPE html>
<html>
<head>
<title>Leaflet sample</title>
<link rel = "stylesheet" href = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css"/>
<script src = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
 </head> <body>
 <div id = "map" style = "width: 900px; height: 580px"></div>
 <script>
 // Creating map options
 var mapOptions = {
 center: [18.5204, 73.8567],
 zoom: 10
 }

 // Creating a map object
 var map = new L.map('map', mapOptions);

 // Creating a Layer object
Creating a Layer object for layer from
geoserver
var layer1 = new
L.tileLayer.wms("http://localhost:8080/geoserver/ows?",{layers:'
rkd:IND_rails',transparent: true}).addTo(map);
Map providers
 We can load the layers of various service providers such as
like open street map, Open Topo, Thunder forest, Hydda,
ESRI, Open weather, NASA GIBS, etc.
 To do so, you need to pass their respective URL while creating
the TileLayer object:

 var layer = new L.TileLayer('URL of the required map');


Map types and URL
Map Types URL
Mapnik http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png

http://{s}.tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png
Black And White

DE http://{s}.tile.openstreetmap.de/tiles/osmde/{z}/{x}/ {y}.png

France http://{s}.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png

Hot http://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png

BZH http://tile.openstreetmap.bzh/br/{z}/{x}/{y}.png
Markers
 To mark a single location on the map, leaflet provides markers.
 These markers use a standard symbol and these symbols can be
customized
 How to add Marker?
 Instantiate the Marker class by passing a latlng object
representing the position to be marked, as shown below.
 var marker = L.marker([20.5937, 78.9629]);
 marker.addTo(map)
Popups to the marker
 To bind a simple popup displaying a message to a marker:

 Attach popup to the marker using bindPopup() as shown


below.

 marker.bindPopup('Hi Welcome ').openPopup();


Marker Options
 While creating a marker, you can also pass a marker
options variable in addition to the latlang object.
 Using this variable, you can set values to various options of the
marker such as icon, clickable, title, dragable, etc.
 Create map option
 var markerOptions = { title: "MyLocation", clickable: true,
draggable: true }
 Call it
var marker = L.marker([17.385044, 78.486671], markerOptions)
Adding shapes on maps(geometries)
 Adding Linestring
 we can also add various shapes such as circles, polygons,
rectangles, polylines, etc.
 Create a latlangs variable to hold the points to draw polyline,
var latlngs = [ [18.528873080926214, 73.84563950827265],
[18.52524381109223, 73.8739130253106],
[18.515694962907524, 73.8654594650178],
[18.508614077162314, 73.86477281955575] ];
 Create a polyline using the L.polyline().
var polyline = L.polyline(latlngs, {color: 'red'});
 Add the polyline to the map using the addTo() method of
the Polyline class
polyline.addTo(map);
Layer Groups and Layers Control
 Using layer group, you can add multiple layers to a map and
manage them as a single layer.
 Create elements (layers) such as markers, polygons, lines, etc.,
that are needed, by instantiating the respective classes as shown
below:
 var p1Marker = new L.Marker([18.528873080926214,
73.84563950827265]);
 var p2Marker = new L.Marker([18.52524381109223,
73.8739130253106]);
 var p3Marker = new L.Marker([18.515694962907524,
73.8654594650178]);
 Create a latlangs variable to hold the points to draw polygone,
var latlngs = [ [18.528873080926214, 73.84563950827265],
[18.52524381109223, 73.8739130253106],
[18.515694962907524, 73.8654594650178],
[18.508614077162314, 73.86477281955575] ];
 Creating a polygon
 var polygon = L.polygon(latlngs, {color: 'red'});
 Create the Layer Group using l.layerGroup().
 Pass all the created markers, polygons, or other ayers etc.
 var layerGroup = L.layerGroup([p1Marker, p2Marker, p3Marker,
polygon]);
 Add the layer group created in the previous step using
the addTo() method:
 layerGroup.addTo(map);
Adding a layer (to layer group)
 You can add a layer to the feature group using
the addLayer() method.
 you need to pass the element that is to be added.
 // Creating a circle
 var circle = L.circle([18.508614077162314,
73.86477281955575], 500, {color: 'red', fillColor: '#f03',
fillOpacity: 0} );
 // Adding circle to the layer group
 layerGroup.addLayer(circle);
Remove layer (From layergroup)
 You can remove a layer from the feature group using the
removeLayer() method.
 To this method, you need to pass the element that is to be
removed.
 You can remove the marker p1Marker
 // Removing layer from map
layerGroup.removeLayer(p1Marker);
Feature Groups
 It is same as LayerGroup but it allows mouse events and bind
popups to it.
 We can also set style to the entire group
using setStyle() method.
 Create Feature Group using l.featureGroup(). Pass the above-
created markers, polygons, etc.:
 var featureGroup = L.featureGroup(p1Marker, p2Marker,
p3Marker, polygon]);
SetStyle()
 If you set style to the feature group, it will be applied to each
element (layer) in the group.
 We can do so using the setStyle() method and to this method,
you need to pass values to the options such as color and opacity
etc.
 // style to the feature group
featureGroup.setStyle({color:'blue',opacity:.5});
 Bind the popup using the bindPopup() method, as shown
below.
 // Binding popup to the feature group
featureGroup.bindPopup("Feature Group");

 // Adding layer group to map


 featureGroup.addTo(map);
Controls
 Leaflet provide following controls:
 Zoom :
 This control exists at the top left corner of the map.
 It has two buttons "+" and "–", using which you can zoom-in or zoom-out the map.
 You can remove the default zoom control by setting the zoomControl option of the
map options to false.
 Attribution −
 This control exists at the bottom right corner of the map.
 It displays the attribution data in a small textbox.
 By default, it displays the text.You can remove the default attribution control by
setting the attributionControl option of the map options to false.
 Scale −
 this control exists at the bottom left corner of the map. It displays the current center
of the screen.
Zoom control
 By default zoom control are already there
 zoomControl: false //use in map option
 Create the zoomOptions variable and define your own text values for
the zoom-in and zoom-out options, instead of + and -.
 // zoom control options
var zoomOptions = { zoomInText: ‘Z+', zoomOutText: ‘Z-', };
 // Creating zoom control
var zoom = L.control.zoom(zoomOptions);
 Add the zoom control object created in the previous step to the map
using the addTo() method.
 zoom.addTo(map);
Attribution
 To set new attribution control first put by default attribution off:
 attributionControl: false
 To add an attribution of your own to the map using Leaflet JavaScript library:
 Create the attrOptions variable and define your own prefix value instead of
the default one (leaflet).
 Then, create the attribution control by passing the attrOptions variable
to L.control.attribution() as shown below.
var attrOptions = { prefix: 'attribution sample' };
// Creating an attribution
var attr = L.control.attribution(attrOptions);
 Add the attribution control object created in the previous step to the map
using the addTo() method.
attr.addTo(map)
Scale
 To add a scale control of your own to the map using Leaflet
JavaScript library
 Create scale control by passing the using L.control.scale() as
shown below.
 var scale = L.control.scale();
 Add the scale control object created in the previous step to the
map using the addTo() method as shown below.
 scale.addTo(map);
Layers Control
 Leaflet has a nice little control that allows your users to control which
layers they see on your map.
 In addition to showing you how to use it, we’ll also show you another
handy use for layer groups.
 There are two types of layers:
 (1) base layers that are mutually exclusive (only one can be visible on
your map at a time), e.g. tile layers, and
 (2) overlays, which are all the other stuff you put over the base layers.
 In this example, we want to have two base layers (a grayscale and a
colored base map) to switch between, and an overlay to switch on and
off: the city markers we created earlier.
Create objects for base layer and overlay
 One will contain our base layers and one will contain our
overlays.
 These are just simple objects with key/value pairs.
 The key sets the text for the layer in the control (e.g. “Streets”),
while the corresponding value is a reference to the layer
(e.g. streets).
Create basemap
var baseMaps = {
"OpenStreetMap": layer,
//"railway":layer1,
};
Creating overlaymaps
var overlayMaps = {
"feautregroup": fGroup,
"railway": layer1,
"newlayer":polygon,
};
 In this example layer 1 is an WMS layer
 And polygon is geometry crated
Layer Control
 Now, all that’s left to do is to create a Layers Control and add it to the map.
 The first argument passed when creating the layers control is the base layers
object.
 The second argument is the overlays object.
 Both arguments are optional: you can pass just a base layers object by
omitting the second argument, or just an overlays objects by passing null as
the first argument.
 In each case, the omitted layer type will not appear for the user to select.

 var layerControl = L.control.layers(baseMaps, overlayMaps).addTo(map);

You might also like