English 中文(简体)
LeafletJS - Quick Guide
  • 时间:2024-11-03

LeafletJS - Quick Guide


Previous Page Next Page  

LeafletJS - Getting Started

What is Leaflet.js

Leaflet.js is an open-source pbrary using which we can deploy simple, interactive, pghtweight web maps.

    Leaflet JavaScript pbrary allows you to use layers such as Tile layers, WMS, Markers, Popups, Vector layers (polypnes, polygons, circles, etc.), Image overlays and GeoJSON.

    You can interact with the Leaflet maps by dragging the map, zooming (by double cpck or, wheel scroll), using keyboard, using event handpng, and by dragging the markers.

    Leaflet supports browsers such as Chrome, Firefox, Safari 5+, Opera 12+, IE 7–11 on desktop and, browsers pke Safari, Android, Chrome, Firefox for mobiles.

Steps to Load the Map on a Webpage

Follow the steps given below to load a map on your webpage −

Step 1: Create an HTML Page

Create a basic HTML page with head and body tags as shown below −

<!DOCTYPE html>
<html>
   <head>
   </head>
   
   <body>
      ...........
   </body>
</html>

Step 2 : Load the Leaflet CSS Script

Include the Leaflet CSS script in the example −

<head>
   <pnk rel = "stylesheet" href = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css" />
</head>

Step 3: Load the Leaflet Script

Load or include the Leaflet API using the script tag −

<head>
   <script src = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
</head>

Step 4: Create the Container

To hold the map, we have to create a container element. Generally, the <span> tag (a generic container) is used for this purpose.

Create a container element and define its dimensions −

<span id = "sample" style = "width:900px; height:580px;"></span>

Step 5: 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 mapOptions object (it is created just pke a pteral) and set values for the options center and zoom, where

    center − As a value to this option, you need to pass a LatLng object specifying the location where we want to center the map. (Just specify the latitude and longitude values within [] braces)

    zoom − As a value to this option, you need to pass an integer representing the zoom level of the map, as shown below.

var mapOptions = {
   center: [17.385044, 78.486671],
   zoom: 10
}

Step 6: 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 <span> element. Here, the <span>element is an HTML container to hold the map.

    An optional object pteral with map options.

Create a Map object by passing the id of the <span> element and mapOptions object created in the previous step.

var map = new L.map( map , mapOptions);

Step 7: 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.

Create the tile layer object as shown below.

var layer = new L.TileLayer( http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png );

Here we have used the openstreetmap.

Step 8: Add Layer to the Map

Finally add the layer created in the previous step to the map object using the addlayer() method as shown below.

map.addLayer(layer);

Example

The following example shows how to load an open street map of Hyderabad city with a zoom value of 10.

<!DOCTYPE html>
<html>
   <head>
      <title>Leaflet sample</title>
      <pnk 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>
      <span id = "map" style = "width: 900px; height: 580px"></span>
      <script>
         // Creating map options
         var mapOptions = {
            center: [17.385044, 78.486671],
            zoom: 10
         }
         
         // Creating a map object
         var map = new L.map( map , mapOptions);
         
         // Creating a Layer object
         var layer = new L.TileLayer( http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png );
         
         // Adding layer to the map
         map.addLayer(layer);
      </script>
   </body>
   
</html>

It generates the following output −

Open Street Map

Leaflet Map Providers

Just pke open street map, you can load the layers of various service providers such as 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 );

The following table psts the URL’s and their respective sample maps of the layers provided by Openstreetmap.

Map Type URL and Output
Mapnik

http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png

Map Providers

Black And White

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

Black and White Map

DE

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

DE

France

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

France

Hot

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

Hot

BZH

http://tile.openstreetmap.bzh/br/{z}/{x}/{y}.png

BZH

LeafletJS - Markers

To mark a single location on the map, leaflet provides markers. These markers use a standard symbol and these symbols can be customized. In this chapter, we will see how to add markers and how to customize, animate, and remove them.

Adding a Simple Marker

To add a marker to a map using Leaflet JavaScript pbrary, follow the steps given below −

Step 1 − Create a Map object by passing a <span> element (String or object) and map options (optional).

Step 2 − Create a Layer object by passing the URL of the desired tile.

Step 3 − Add the layer object to the map using the addLayer() method of the Map class.

Step 4 − Instantiate the Marker class by passing a latlng object representing the position to be marked, as shown below.

// Creating a marker
var marker = new L.Marker([17.385044, 78.486671]);

Step 5 − Add the marker object created in the previous steps to the map using the addTo() method of the Marker class.

// Adding marker to the map
marker.addTo(map);

Example

The following code sets the marker on the city named Hyderabad (India).

<!DOCTYPE html>
<html>
   <head>
      <title>Leaflet sample</title>
      <pnk 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>
      <span id = "map" style = "width:900px; height:580px"></span>
      <script>
         // Creating map options
         var mapOptions = {
            center: [17.385044, 78.486671],
            zoom: 10
         }
         // Creating a map object
         var map = new L.map( map , mapOptions);
         
         // Creating a Layer object
         var layer = new L.TileLayer( http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png );
         
         // Adding layer to the map
         map.addLayer(layer);
         
         // Creating a marker
         var marker = L.marker([17.385044, 78.486671]);
         
         // Adding marker to the map
         marker.addTo(map);
      </script>
   </body>
   
</html>

It generates the following output −

Simple Marker

Binding Pop-ups to the Marker

To bind a simple popup displaying a message to a marker, follow the steps given below −

Step 1 − Create a Map object by passing a <span> element (String or object) and map options (optional).

Step 2 − Create a Layer object by passing the URL of the desired tile.

Step 3 − Add the layer object to the map using the addLayer() method of the Map class.

Step 4 − Instantiate the Marker class by passing a latlng object representing the position to be marked.

Step 5 − Attach popup to the marker using bindPopup() as shown below.

// Adding pop-up to the marker
marker.bindPopup( Hi Welcome to Tutorialspoint ).openPopup();

Step 6 − Finally, add the Marker object created in the previous steps to the map using the addTo() method of the Marker class.

Example

The following code sets the marker on the city Hyderabad (India) and adds a pop-up to it.

<!DOCTYPE html>
<html>
   <head>
      <title>Binding pop-Ups to marker</title>
      <pnk 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>
      <span id = "map" style = "width:900px; height:580px"></span>
      <script>
         // Creating map options
         var mapOptions = {
            center: [17.385044, 78.486671],
            zoom: 15
         }
         var map = new L.map( map , mapOptions); // Creating a map object
         
         // Creating a Layer object
         var layer = new L.TileLayer( http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png );
         map.addLayer(layer);         // Adding layer to the map
         var marker = L.marker([17.438139, 78.395830]);    // Creating a Marker
         
         // Adding popup to the marker
         marker.bindPopup( This is Tutorialspoint ).openPopup();
         marker.addTo(map); // Adding marker to the map
      </script>
   </body>
   
</html>

It generates the following output

Pop-ups to the Marker

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, dragable, keyboard, title, alt, zInsexOffset, opacity, riseOnHover, riseOffset, pane, dragable, etc.

To create a map using map options, you need to follow the steps given below −

Step 1 − Create a Map object by passing a <span> element (String or object) and map options (optional).

Step 2 − Create a Layer object by passing the URL of the desired tile.

Step 3 − Add the layer object to the map using the addLayer() method of the Map class.

Step 4 − Create a variable for markerOptions and specify values to the required options.

Create a markerOptions object (it is created just pke a pteral) and set values for the options iconUrl and iconSize.

// Options for the marker
var markerOptions = {
   title: "MyLocation",
   cpckable: true,
   draggable: true
}

Step 5 − Instantiate the Marker class by passing a latlng object representing the position to be marked and the options object, created in the previous step.

// Creating a marker
var marker = L.marker([17.385044, 78.486671], markerOptions);

Step 6 − Finally, add the Marker object created in the previous steps to the map using the addTo() method of the Marker class.

Example

The following code sets the marker on the city Hyderabad (India). This marker is cpckable, dragable with the title MyLocation.

<html>
   <head>
      <title>Marker Options Example</title>
      <pnk 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>
      <span id = "map" style = "width:900px; height:580px"></span>
      <script>
         // Creating map options
         var mapOptions = {
            center: [17.385044, 78.486671],
            zoom: 10
         }
         // Creating a map object
         var map = new L.map( map , mapOptions);
         
         // Creating a Layer object
         var layer = new L.TileLayer( http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png );
        
         // Adding layer to the map
         map.addLayer(layer);
         
         // Creating a Marker
         var markerOptions = {
            title: "MyLocation",
            cpckable: true,
            draggable: true
         }
         // Creating a marker
         var marker = L.marker([17.385044, 78.486671], markerOptions);
         
         // Adding marker to the map
         marker.addTo(map);
      </script>
   </body>
   
</html>

It generates the following output

Marker Options

Marker Custom Icons

Instead of the default icon provided by the Leaflet pbrary, you can also add your own icon. You can use the following steps to add a custom icon to the map instead of the default one.

Step 1 − Create a Map object by passing a <span> element (String or object) and map options (optional).

Step 2 − Create a Layer object by passing the URL of the desired tile.

Step 3 − Add the layer object to the map using the addLayer() method of the Map class.

Step 4 − Create a variable for markerOptions and specify values to the required options −

    iconUrl − As a value to this option, you need to pass a String object specifying the path of the image which you want to use as an icon.

    iconSize − Using this option, you can specify the size of the icon.

Note − In addition to these, you can also set values to other options such as iconSize, shadowSize, iconAnchor, shadowAnchor, and popupAnchor.

Create a custom icon using L.icon() by passing the above options variable as shown below.

// Icon options
var iconOptions = {
   iconUrl:  logo.png ,
   iconSize: [50, 50]
}

// Creating a custom icon
var customIcon = L.icon(iconOptions);

Step 5 − Create a variable for markerOptions and specify values to the required options. In addition to these, specify the icon by passing the icon variable created in the previous step as a value.

// Options for the marker
var markerOptions = {
   title: "MyLocation",
   cpckable: true,
   draggable: true,
   icon: customIcon
}

Step 6 − Instantiate the Marker class by passing a latlng object representing the position to be marked and the options object created in the previous step.

// Creating a marker
var marker = L.marker([17.438139, 78.395830], markerOptions);

Step 7 − Finally, add the Marker object created in the previous steps to the map using the addTo() method of the Marker class.

Example

The following code sets the marker on the location of Tutorialspoint. Here we are using the logo of Tutorialspoint instead of the default marker.

<!DOCTYPE html>
<html>
   <head>
      <title>Marker Custom Icons Example</title>
      <pnk 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>
      <span id = "map" style = "width:900px; height:580px"></span>
      <script>
         // Creating map options
         var mapOptions = {
            center: [17.438139, 78.395830],
            zoom: 10
         }
         // Creating a map object
         var map = new L.map( map , mapOptions);
         
         // Creating a Layer object
         var layer = new L.TileLayer( http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png );

         // Adding layer to the map
         map.addLayer(layer);
         
         // Icon options
         var iconOptions = {
            iconUrl:  logo.png ,
            iconSize: [50, 50]
         }
         // Creating a custom icon
         var customIcon = L.icon(iconOptions);
         
         // Creating Marker Options
         var markerOptions = {
            title: "MyLocation",
            cpckable: true,
            draggable: true,
            icon: customIcon
         }
         // Creating a Marker
         var marker = L.marker([17.438139, 78.395830], markerOptions);
         
         // Adding popup to the marker
         marker.bindPopup( Hi welcome to Tutorialspoint ).openPopup();
         
         // Adding marker to the map
         marker.addTo(map);
      </script>
   </body>
   
</html>

It generates the following output

Marker Custom Icons

LeafletJS - Vector Layers

In the previous chapter, we learned how to use markers in Leaflet. Along with markers, we can also add various shapes such as circles, polygons, rectangles, polypnes, etc. In this chapter, we will discuss how to use the shapes provided by Google Maps.

Polypne

To draw polypne overlay on a map using Leaflet JavaScript pbrary, follow the steps given below −

Step 1 − Create a Map object by passing a <span> element (String or object) and map options (optional).

Step 2 − Create a Layer object by passing the URL of the desired tile.

Step 3 − Add the layer object to the map using the addLayer() method of the Map class.

Step 4 − Create a latlangs variable to hold the points to draw polypne, as shown below.

// Creating latlng object
var latlngs = [
   [17.385044, 78.486671],
   [16.506174, 80.648015],
   [17.000538, 81.804034],
   [17.686816, 83.218482]
];

Step 5 − Create a polypne using the L.polypne(). To draw the polypne, pass the locations as variable and an option to specify the color of the pnes.

// Creating a poly pne
var polypne = L.polypne(latlngs, {color:  red });

Step 6 − Add the polypne to the map using the addTo() method of the Polypne class.

// Adding to poly pne to map
polypne.addTo(map);

Example

Following is the code which draws a polypne, covering the cities Hyderabad, Vijayawada, Rajamahendrawaram and, Vishakhapatnam (India).

DOCTYPE html>
<html>
   <head>
      <title>Leaflet Poly pnes</title>
      <pnk 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>
      <span id = "map" style = "width:900px; height:580px"></span>
      <script>
         // Creating map options
         var mapOptions = {
            center: [16.506174, 80.648015],
            zoom: 7
         }
         // Creating a map object
         var map = new L.map( map , mapOptions);
         
         // Creating a Layer object
         var layer = new L.TileLayer( http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png );
         
         // Adding layer to the map
         map.addLayer(layer);
         
         // Creating latlng object
         var latlngs = [
            [17.385044, 78.486671],
            [16.506174, 80.648015],
            [17.000538, 81.804034],
            [17.686816, 83.218482]
         ];
         // Creating a poly pne
         var polypne = L.polypne(latlngs, {color:  red });
         
         // Adding to poly pne to map
         polypne.addTo(map);
      </script>
   </body>
   
</html>

It generates the following output

Polypne

Polygon

To draw a polygon overlay on a map using Leaflet JavaScript pbrary, follow the steps given below −

Step 1 − Create a Map object by passing a <span> element (String or object) and map options (optional).

Step 2 − Create a Layer object by passing the URL of the desired tile.

Step 3 − Add the layer object to the map using the addLayer() method of the Map class.

Step 4 − Create a latlangs variable to hold the points to draw the polygon.

// Creating latlng object
var latlngs = [
   [17.385044, 78.486671],
   [16.506174, 80.648015],
   [17.686816, 83.218482]
];

Step 5 − Create a polygon using the L.polygon(). Pass the locations/points as variable to draw the polygon, and an option to specify the color of the polygon.

// Creating a polygon
var polygon = L.polygon(latlngs, {color:  red });

Step 6 − Add the polygon to the map using the addTo() method of the Polygon class.

// Adding to polygon to map
polygon.addTo(map);

Example

Following is the code to draw a polygon covering the cities Hyderabad, Vijayawada, and Vishakhapatnam (India).

<!DOCTYPE html>
<html>
   <head>
      <title>Leaflet Polygons</title>
      <pnk 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>
      <span id = "map" style = "width:900px; height:580px"></span>
      <script>
         // Creating map options
         var mapOptions = {
            center: [16.506174, 80.648015],
            zoom: 7
         }
         // Creating a map object
         var map = new L.map( map , mapOptions);
         
         // Creating a Layer object
         var layer = new L.TileLayer( http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png );
        
         // Adding layer to the map
         map.addLayer(layer);
         
         // Creating latlng object
         var latlngs = [
            [17.385044, 78.486671],
            [16.506174, 80.648015],
            [17.686816, 83.218482]
         ];
         // Creating a polygon
         var polygon = L.polygon(latlngs, {color:  red });
         
         // Adding to polygon to map
         polygon.addTo(map);
      </script>
   </body>
   
</html>

It generates the following output −

Polygon

Rectangle

To draw a Rectangle overlay on a map using Leaflet JavaScript pbrary, follow the steps given below

Step 1 − Create a Map object by passing a <span> element (String or object) and map options (optional).

Step 2 − Create a Layer object by passing the URL of the desired tile.

Step 3 − Add the layer object to the map using the addLayer() method of the Map class.

Step 4 − Create a latlangs variable to hold the points to draw a rectangle on the map.

// Creating latlng object
var latlngs = [
   [17.342761, 78.552432],
   [16.396553, 80.727725]
];

Step 5 − Create a rectangle using the L.rectangle() function. Pass the locations/points as a variable to draw a rectangle and rectangleOptions to specify the color and weight of the rectangle.

// Creating rectOptions
var rectOptions = {color:  Red , weight: 1}

// Creating a rectangle
var rectangle = L.rectangle(latlngs, rectOptions);

Step 6 − Add the rectangle to the map using the addTo() method of the Polygon class.

// Adding to rectangle to map
rectangle.addTo(map);

Example

Following is the code to draw a rectangle on the map using Leaflet JavaScript pbrary.

<!DOCTYPE html>
<html>
   <head>
      <title>Leaflet Rectangle</title>
      <pnk 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>
      <span id = "map" style = "width:900px; height:580px"></span>
      <script>
         // Creating map options
         var mapOptions = {
            center: [16.506174, 80.648015],
            zoom: 7
         }
         var map = new L.map( map , mapOptions); // Creating a map object
         
         // Creating a Layer object
         var layer = new L.TileLayer( http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png );
         map.addLayer(layer); // Adding layer to the map
         
         // Creating latlng object
         var latlngs = [
            [17.342761, 78.552432],
            [16.396553, 80.727725]
         ];
         var rectOptions = {color:  Red , weight: 1}   // Creating rectOptions
        
         // Creating a rectangle
         var rectangle = L.rectangle(latlngs, rectOptions);
         rectangle.addTo(map);   // Adding to rectangle to map
      </script>
   </body>
   
</html>

It generates the following output −

Rectangle

Circle

To draw a circle overlay on a map using Leaflet JavaScript pbrary follow the steps given below.

Step 1 − Create a Map object by passing a <span> element (String or object) and map options (optional).

Step 2 − Create a Layer object by passing the URL of the desired tile.

Step 3 − Add the layer object to the map using the addLayer() method of the Map class.

Step 4 − Create a latlangs variable to hold the center of the circle as shown below.

// Center of the circle
var circleCenter = [17.385044, 78.486671];

Step 5 − Create a variable circleOptions to specify values to the options color, fillColor and, fillOpacity as shown below.

// Circle options
var circleOptions = {
   color:  red ,
   fillColor:  #f03 ,
   fillOpacity: 0
}

Step 6 − Create a circle using L.circle(). Pass the center of the circle, radius, and the circle options to this function.

// Creating a circle
var circle = L.circle(circleCenter, 50000, circleOptions);

Step 7 − Add the above-created circle to the map using the addTo() method of the Polypne class.

// Adding circle to the map
circle.addTo(map);

Example

Following is the code to draw a circle with the coordinates of the city Hyderabad as its radius.

<!DOCTYPE html>
<html>
   <head>
      <title>Leaflet Circle</title>
      <pnk 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>
      <span id = "map" style = "width: 900px; height: 580px"></span>
      <script>
         // Creating map options
         var mapOptions = {
            center: [17.385044, 78.486671],
            zoom: 7
         }
         var map = new L.map( map , mapOptions); // Creating a map object
         
         // Creating a Layer object
         var layer = new L.TileLayer( http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png );
         map.addLayer(layer);        // Adding layer to the map
         var circleCenter = [17.385044, 78.486671];     // Center of the circle
         
         // Circle options
         var circleOptions = {
            color:  red ,
            fillColor:  #f03 ,
            fillOpacity: 0
         }
         // Creating a circle
         var circle = L.circle(circleCenter, 50000, circleOptions);
         circle.addTo(map);     // Adding circle to the map
      </script>
   </body>
   
</html>>

It generates the following output −

Circle

LeafletJS - Multi Polypne and Polygon

In the previous chapter, we learnt how to add various shapes such as circles, polygons, rectangles, polypnes, etc. In this chapter, let us discuss how to add multi-polygons, multirectangles, and polypnes.

Multi-Polypne

To draw a multi-polypne overlay on a map using Leaflet JavaScript pbrary, follow the steps given below −

Step 1 − Create a Map object by passing a <span> element (String or object) and map options (optional).

Step 2 − Create a Layer object by passing the URL of the desired tile.

Step 3 − Add the layer object to the map using the addLayer() method of the Map class.

Step 4 − Create a latlangs variable to hold the points to draw the multi-polypne.

// Creating latlng object
var latlang = [
   [[17.385044, 78.486671], [16.506174, 80.648015], [17.686816, 83.218482]],
   [[13.082680, 80.270718], [12.971599, 77.594563],[15.828126, 78.037279]]
];

Step 5 − Create a multi-polypne using the L.multiPolypne() function. Pass the locations as variable to draw a multi-polypne and an option to specify the color and weight of the pnes.

// Creating multi polypne options
var multiPolyLineOptions = {color: red };

// Creating multi polypnes
var multipolypne = L.multiPolypne(latlang , multiPolyLineOptions);

Step 6 − Add multi-polypne to the map using the addTo() method of the Multipolypne class.

// Adding multi polypne to map
multipolypne.addTo(map);

Example

Following is the code to draw a multi-polypne covering the cities Hyderabad, Vijayawada, and Vishakhapatnam; and Kurnool, Bengaluru, and Chennai.

<!DOCTYPE html>
<html>
   <head>
      <title>Leaflet Multi Polypnes</title>
      <pnk 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>
      <span id = "map" style = "width: 900px; height: 580px"></span>
      <script>
         // Creating map options
         var mapOptions = {
            center: [16.506174, 80.648015],
            zoom: 7
         }
         // Creating a map object
         var map = new L.map( map , mapOptions);
         
         // Creating a Layer object
         var layer = new L.TileLayer( http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png );
         
         // Adding layer to the map
         map.addLayer(layer);
         
         // Creating latlng object
         var latlang = [
            [[17.385044, 78.486671], [16.506174, 80.648015], [17.686816, 83.218482]],
            [[13.082680, 80.270718], [12.971599, 77.594563],[15.828126, 78.037279]]
         ];
         
         // Creating poly pne options
         var multiPolyLineOptions = {color: red };
         
         // Creating multi poly-pnes
         var multipolypne = L.multiPolypne(latlang , multiPolyLineOptions);
         
         // Adding multi poly-pne to map
         multipolypne.addTo(map);
      </script>
   </body>
   
</html>

It generates the following output −

Multi-Polypne Map

Multi Polygon

To draw a multi-polygon overlay on a map using Leaflet JavaScript pbrary, follow the steps given below −

Step 1 − Create a Map object by passing a <span> element (String or object) and map options (optional).

Step 2 − Create a Layer object by passing the URL of the desired tile.

Step 3 − Add the layer object to the map using the addLayer() method of the Map class.

Step 4 − Create a latlangs variable to hold the points to draw the multi polygon.

// Creating latlng object
var latlang = [
   [[17.385044, 78.486671], [16.506174, 80.648015], [17.686816, 83.218482]],
   [[13.082680, 80.270718], [12.971599, 77.594563],[15.828126, 78.037279]]
];

Step 5 − Create a multi-polygon using the L.multiPolygon() function. Pass the locations as variable to draw the multi-polygon and an option to specify the color and weight of the pnes.

// Creating multi polygon options
var multiPolygonOptions = {color: red };

// Creating multi polygon
var multipolygon = L.multiPolygon(latlang , multiPolygonOptions);

Step 6 − Add the multi-polygon to the map using the addTo() method of the MultiPolygon class.

// Adding multi polygon to map
multipolygon.addTo(map);

Example

Following is the code to draw a multi-polygon touching the cities Hyderabad, Vijayawada, and Vishakhapatnam; and Kurnool, Bengaluru, and Chennai.

<!DOCTYPE html>
<html>
   <head>
      <title>Leaflet Multi Polygons</title>
      <pnk 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>
      <span id = "map" style = "width: 900px; height: 580px"></span>
      <script>
         // Creating map options
         var mapOptions = {
            center: [16.506174, 80.648015],
            zoom: 7
         }
         // Creating a map object
         var map = new L.map( map , mapOptions);
         
         // Creating a Layer object
         var layer = new L.TileLayer( http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png );
         
         // Adding layer to the map
         map.addLayer(layer);
         
         // Creating latlng object
         var latlang = [
            [[17.385044, 78.486671], [16.506174, 80.648015], [17.686816, 83.218482]],
            [[13.082680, 80.270718], [12.971599, 77.594563],[15.828126, 78.037279]]
         ];
         // Creating multi polygon options
         var multiPolygonOptions = {color: red , weight:8};
         
         // Creating multi polygons
         var multipolygon = L.multiPolygon(latlang , multiPolygonOptions);
         
         // Adding multi polygon to map
         multipolygon.addTo(map);
      </script>
   </body>
   
</html>

It generates the following output −

Multi Polygon Map

LeafletJS - Layers Group

Layer Groups

Using layer group, you can add multiple layers to a map and manage them as a single layer.

Follow the steps given below to create a LayerGroup and add it to the map.

Step 1 − Create a Map object by passing a <span> element (String or object) and map options (optional).

Step 2 − Create a Layer object by passing the URL of the desired tile.

Step 3 − Add the layer object to the map using the addLayer() method of the Map class.

Step 4 − Create elements (layers) such as markers, polygons, circles, etc., that are needed, by instantiating the respective classes as shown below.

// Creating markers
var hydMarker = new L.Marker([17.385044, 78.486671]);
var vskpMarker = new L.Marker([17.686816, 83.218482]);
var vjwdMarker = new L.Marker([16.506174, 80.648015]);

// Creating latlng object
var latlngs = [
   [17.385044, 78.486671],
   [16.506174, 80.648015],
   [17.686816, 83.218482]
];
// Creating a polygon
var polygon = L.polygon(latlngs, {color:  red });

Step 5 − Create the Layer Group using l.layerGroup(). Pass the above created markers, polygons, etc., as shown below.

// Creating layer group
var layerGroup = L.layerGroup([hydMarker, vskpMarker, vjwdMarker, polygon]);

Step 6 − Add the layer group created in the previous step using the addTo() method.

// Adding layer group to map
layerGroup.addTo(map);

Example

The following code creates a layer group which holds 3 markers and a polygon, and adds it to the map.

<!DOCTYPE html>
<html>
   <head>
      <title>Leaflet Layer Group</title>
      <pnk 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>
      <span id = "map" style = "width: 900px; height: 580px"></span>
      <script>
         // Creating map options
         var mapOptions = {
            center: [17.385044, 78.486671],
            zoom: 7
         }
         var map = new L.map( map , mapOptions); // Creating a map object
         
         // Creating a Layer object
         var layer = new L.TileLayer( http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png );
         map.addLayer(layer);      // Adding layer to the map
         
         // Creating markers
         var hydMarker = new L.Marker([17.385044, 78.486671]);
         var vskpMarker = new L.Marker([17.686816, 83.218482]);
         var vjwdMarker = new L.Marker([16.506174, 80.648015]);
         
         // Creating latlng object
         var latlngs = [
            [17.385044, 78.486671],
            [16.506174, 80.648015],
            [17.686816, 83.218482]
         ];
         // Creating a polygon
         var polygon = L.polygon(latlngs, {color:  red });
         
         // Creating layer group
         var layerGroup = L.layerGroup([hydMarker, vskpMarker, vjwdMarker, polygon]);
         layerGroup.addTo(map);    // Adding layer group to map
      </script>
   </body>
   
</html>

It generates the following output −

Layer Group Map

Adding a layer (element)

You can add a layer to the feature group using the addLayer() method. To this method, you need to pass the element that is to be added.

You can add a circle with the city Hyderabad at the center.

// Creating a circle
var circle = L.circle([16.506174, 80.648015], 50000, {color:  red , fillColor:
    #f03 , fillOpacity: 0} );

// Adding circle to the layer group
layerGroup.addLayer(circle);

It will produce the following output. −

Add Layer Group Map

Removing a Layer (Element)

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 on the city named Vijayawada as shown below.

// Removing layer from map
layerGroup.removeLayer(vjwdMarker);

It will produce the following output −

Remove Layer Map

Feature Groups

It is similar to LayerGroup but it allows mouse events and bind popups to it. You can also set style to the entire group using setStyle() method.

Follow the steps given below to create a Feature Group and add it to the map.

Step 1 − Create a Map object by passing a <span> element (String or object) and map options (optional).

Step 2 − Create a Layer object by passing the URL of the desired tile.

Step 3 − Add the layer object to the map using the addLayer() method of the Map class.

Step 4 − Create elements (layers) such as markers, polygons, and circles that are needed, by instantiating the respective classes as shown below.

// Creating markers
var hydMarker = new L.Marker([17.385044, 78.486671]);
var vskpMarker = new L.Marker([17.686816, 83.218482]);
var vjwdMarker = new L.Marker([16.506174, 80.648015]);

// Creating latlng object
var latlngs = [
   [17.385044, 78.486671],
   [16.506174, 80.648015],
   [17.686816, 83.218482]
];
// Creating a polygon
var polygon = L.polygon(latlngs, {color:  red });>

Step 5 − Create Feature Group using l.featureGroup(). Pass the above-created markers, polygons, etc., as shown below.

// Creating feature group
var featureGroup = L.featureGroup([hydMarker, vskpMarker, vjwdMarker, polygon]);

Step 6 − If you set style to the feature group, it will be appped to each element (layer) in the group. You 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.

Set the style to the feature group created in the above step.

// Setting style to the feature group
featureGroup.setStyle({color: blue ,opacity:.5});

Step 7 − Bind the popup using the bindPopup() method, as shown below.

// Binding popup to the feature group
featureGroup.bindPopup("Feature Group");

Step 8 − Add the feature group created in the previous step using the addTo() method.

// Adding layer group to map
featureGroup.addTo(map);

Example

The following code creates a feature group which holds 3 markers and a polygon, and adds it to the map.

<!DOCTYPE html>
<html>
   <head>
      <title>Leaflet Feature Group</title>
      <pnk 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>
      <span id = "map" style = "width:900px; height:580px"></span>
      <script>
         // Creating map options
         var mapOptions = {
            center: [17.385044, 78.486671],
            zoom: 7
         }
         var map = new L.map( map , mapOptions); // Creating a map object
         
         // Creating a Layer object
         var layer = new L.TileLayer( http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png );
         map.addLayer(layer);      // Adding layer to the map
         
         // Creating markers
         var hydMarker = new L.Marker([17.385044, 78.486671]);
         var vskpMarker = new L.Marker([17.686816, 83.218482]);
         var vjwdMarker = new L.Marker([16.506174, 80.648015]);
         
         // Creating latlng object
         var latlngs = [
            [17.385044, 78.486671],
            [16.506174, 80.648015],
            [17.686816, 83.218482]
         ];
         var polygon = L.polygon(latlngs, {color:  red }); // Creating a polygon
         
         // Creating feature group
         var featureGroup = L.featureGroup([hydMarker, vskpMarker, vjwdMarker, polygon]);
         featureGroup.setStyle({color: blue ,opacity:.5});
         featureGroup.bindPopup("Feature Group");
         featureGroup.addTo(map);      // Adding layer group to map
      </script>
   </body>
   
</html>

It generates the following output −

Add Layer Group Map

LeafletJS - Event Handpng

The Leaflet JavaScript program can respond to various events generated by the user. In this chapter, we will provide a few examples demonstrating how to perform event handpng while working with Leaflet.

Event Handpng

Follow the steps given below to add events to the map.

Step 1 − Create a Map object by passing a <span> element (String or object) and map options (optional).

Step 2 − Create a Layer object by passing the URL of the desired tile.

Step 3 − Add the layer object to the map using the addLayer() method of the Map class.

Step 4 − Add the handler to the map, as shown below.

map.on("cpck", function(e){
   new L.Marker([e.latlng.lat, e.latlng.lng]).addTo(map);
})

Example

The following code demonstrates even handpng using Leaflet. When executed, if you cpck on the map, a marker will be created on that particular location.

<!DOCTYPE html>
<html>
   <head>
      <title>Leaflet Polygons</title>
      <pnk 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>
      <span id = "map" style = "width: 900px; height: 580px"></span>
      <script>
         // Creating map options
         var mapOptions = {
            center: [16.506174, 80.648015],
            zoom: 7
         }
         var map = new L.map( map , mapOptions);    // Creating a map object
         
         // Creating a Layer object
         var layer = new L.TileLayer( http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png );
         map.addLayer(layer); // Adding layer to the map
         
         map.on("cpck", function(e){
            new L.Marker([e.latlng.lat, e.latlng.lng]).addTo(map);
         })
      </script>
   </body>
   
</html>

It generates the following output −

Event Handpng

LeafletJS - Overlays

Instead of map overlays, you can also use image, video overlays in a Leaflet apppcation. In this chapter, we will see how to use such overlays.

Image Overlay

Follow the steps given below to use an image overlay.

Step 1 − Create a Map object by passing a <span> element (String or object) and map options (optional).

Step 2 − Create a Layer object by passing the URL of the desired tile.

Step 3 − Add the layer object to the map using the addLayer() method of the Map class.

Step 4 − Create the image overlay using L.imageOverlay(). Pass the URL of the image and an object representing image bounds, as shown below.

// Creating Image overlay
var imageUrl =  tpPoster.jpg ;
var imageBounds = [[17.342761, 78.552432], [16.396553, 80.727725]];
var overlay = L.imageOverlay(imageUrl, imageBounds);

Step 5 − Add the overlay to the map using addTo() method of the imageOverlay class, as shown below.

// Adding overlay to the map
overlay.addTo(map);

Example

The following code demonstrates the usage of image overlay.

<!DOCTYPE html>
<html>
   <head>
      <title>Image Overlay Example</title>
      <pnk 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>
      <span id = "map" style = "width:900px; height:580px"></span>
      <script>
         // Creating map options
         var mapOptions = {
            center: [17.342761, 78.552432],
            zoom: 8
         }
         var map = new L.map( map , mapOptions); // Creating a map object
         
         // Creating a Layer object
         var layer = new L.TileLayer( http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png );
         map.addLayer(layer);  // Adding layer to the map
         
         // Creating Image overlay
         var imageUrl =  tpPoster.jpg ;
         var imageBounds = [[17.342761, 78.552432], [16.396553, 80.727725]];
         var overlay = L.imageOverlay(imageUrl, imageBounds);
         overlay.addTo(map);
      </script>
   </body>
   
</html>

It generates the following output −

Overlay

LeafletJS - Controls

Leaflet provides various controls such as zoom, attribution, scale, etc., where −

    Zoom − By default, 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 − By default, 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 − By default, this control exists at the bottom left corner of the map. It displays the current center of the screen.

In this chapter, we will explain how you can create and add all these three controls to your map using Leaflet JavaScript pbrary.

Zoom

To add a zoom control of your own to the map using Leaflet JavaScript pbrary, follow the steps given below −

Step 1 − Create a Map object by passing a element (String or object) and map options (optional).

Step 2 − Create a Layer object by passing the URL of the desired tile.

Step 3 − Add the layer object to the map using the addLayer() method of the Map class.

Step 4 − Create the zoomOptions variable and define your own text values for the zoom-in and zoom-out options, instead of the default ones (+ and -).

Then, create the zoom control by passing the zoomOptions variable to L.control.zoom() as shown below.

// zoom control options
var zoomOptions = {
   zoomInText:  1 ,
   zoomOutText:  0 ,
};
// Creating zoom control
var zoom = L.control.zoom(zoomOptions);

Step 5 − Add the zoom control object created in the previous step to the map using the addTo() method.

// Adding zoom control to the map
zoom.addTo(map);

Example

Following is the code to add your own zoom control to your map, instead of the default one. Here, on pressing 1, the map zooms in, and on pressing 0, the map zooms out.

<!DOCTYPE html>
<html>
   <head>
      <title>Zoom Example</title>
      <pnk 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>
      <span id = "map" style = "width:900px; height:580px"></span>
      <script>
         // Creating map options
         var mapOptions = {
            center: [17.385044, 78.486671],
            zoom: 10,
            zoomControl: false
         }
         var map = new L.map( map , mapOptions); // Creating a map object
         
         // Creating a Layer object
         var layer = new L.TileLayer( http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png );
         map.addLayer(layer);   // Adding layer to the map
         
         // zoom control options
         var zoomOptions = {
            zoomInText:  1 ,
            zoomOutText:  0 ,
         };
         var zoom = L.control.zoom(zoomOptions);   // Creating zoom control
         zoom.addTo(map);   // Adding zoom control to the map
      </script>
   </body>
   
</html>

It generates the following output −

Zoom Map

Attribution

To add an attribution of your own to the map using Leaflet JavaScript pbrary, follow the steps given below −

Step 1 − Create a Map object by passing a <span> element (String or object) and map options (optional).

Step 2 − Create a Layer object by passing the URL of the desired tile.

Step 3 − Add the layer object to the map using the addLayer() method of the Map class.

Step 4 − 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.

// Attribution options
var attrOptions = {
   prefix:  attribution sample 
};

// Creating an attribution
var attr = L.control.attribution(attrOptions);

Step 5 − Add the attribution control object created in the previous step to the map using the addTo() method.

// Adding attribution to the map
attr.addTo(map);

Example

The following code adds our own attribution control to your map, instead of the default one. Here, instead the text attribution sample will be displayed.

<!DOCTYPE html>
<html>
   <head>
      <title>Attribution Example</title>
      <pnk 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>
      <span id = "map" style = "width: 900px; height: 580px"></span>
      <script>
         // Creating map options
         var mapOptions = {
            center: [17.385044, 78.486671],
            zoom: 10,
            attributionControl: false
         }
         var map = new L.map( map , mapOptions); // Creating a map object
         
         // Creating a Layer object
         var layer = new L.TileLayer( http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png );
         map.addLayer(layer);    // Adding layer to the map
         
         // Attribution options
         var attrOptions = {
            prefix:  attribution sample 
         };
         
         // Creating an attribution
         var attr = L.control.attribution(attrOptions);
         attr.addTo(map);  // Adding attribution to the map
      </script>
   </body>
   
</html>>

It generates the following output −

Attribution Map

Scale

To add a scale control of your own to the map using Leaflet JavaScript pbrary, follow the steps given below −

Step 1 − Create a Map object by passing a <span> element (String or object) and map options (optional).

Step 2 − Create a Layer object by passing the URL of the desired tile.

Step 3 − Add the layer object to the map using the addLayer() method of the Map class.

Step 4 − Create scale control by passing the using L.control.scale() as shown below.

// Creating scale control
var scale = L.control.scale();

Step 5 − Add the scale control object created in the previous step to the map using the addTo() method as shown below.

// Adding scale control to the map
scale.addTo(map);

Example

The following code adds scale control to your map.

<!DOCTYPE html>
<html>
   <head>
      <title>Scale Example</title>
      <pnk 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>
      <span id = "map" style = "width:900px; height:580px"></span>
      <script>
         // Creating map options
         var mapOptions = {
            center: [17.385044, 78.486671],
            zoom: 10
         }
         // Creating a map object
         var map = new L.map( map , mapOptions);
         
         // Creating a Layer object
         var layer = new L.TileLayer( http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png );
         map.addLayer(layer); // Adding layer to the map
         var scale = L.control.scale(); // Creating scale control
         scale.addTo(map); // Adding scale control to the map
      </script>
   </body>
   
</html>

It generates the following output −

Scale Map Advertisements