Leaflet Js Plugin Basics Tutorial



Leaflet Js Plugin Basics Tutorial

In this blog post we are going to provide you the Leaflet Js Plugin Basics Tutorial. Leaflet Js has stated the main aim of its use is to provide JavaScript libraries for drawing maps, with good performance and usability. Leaflet has many features yet to be included for getting excel in performance and usability but the idea being that not everyone is going to use those features, therefore there is no benefit to increasing the size of leaflet and impacting performance. Instead the awesomeness of Leaflet is increased by encouraging third party contributors to craft their own plugins that can leverage the core library capabilities to expand functionality on a feature by feature basis. So, here is the article Leaflet Js Plugin Basics Tutorial.

Leaflet Js Plugin Basics Tutorial

This Leaflet Js Plugin Basics Tutorial contains the basics of using the leaflet plugin and advantages we can have with all of its functionalities. Leaflet Js plugins are the third party plugins which are used to extend the functionality of leaflet map. Now lets just talk about leaflet map and plugins.

Leaflet Js Plugin

There are hundreds of plugins available for Leaflet Js maps. The Leaflet Js plugins provides functionalities in various area of mapping like Tile and image layer, Basemap provider and brass map, Vector file and overlay map extends.

Leaflet Js Plugin Basics Tutorial is all about to show you that anyone can maintain and create Leaflet plugin with deep knowledge and understanding of leaflet and javascript.

You can attach the Leaflet plugin to your map with the help of Github or any other repository via adding the additional .js and .css file into the leaflet html file in the header section. The leaflet plugins really improves the performance and usability of Leaflet Js.

The most amazing thing about leaflet is Its powerful plugin ecosystem. Anyone with some coding skills can create the plugin for leaflet but there are some standards you need to follow before writing the code to create the plugin.

Some of the following standards are as follows:

  • Leaflet follows pretty much the same conventions except for using smart tabs (hard tabs for indentation, spaces for alignment) and putting a space after the function keyword.
  • Never expose global variables in your plugin.
  • If you have a new class, put it directly in the L namespace (L.MyPlugin).
  • And if you inherit one of the existing classes, make it a sub-property (L.TileLayer.Banana).
  • Even if you want to add new methods to existing Leaflet classes, you can do it like this: L.Marker.include({myPlugin: …}).
  • Function, method and property names should be in camelCase.
  • Class names should be in CapitalizedCamelCase.

Leaflet.draw

Leaflet Js has this amazing plugin which helps in adding the drawing and editing support for markers and vectors overlaid onto leaflet maps. It is one of the main heading under the topic of Leaflet Js Plugin Basics Tutorial. It is a comprehensive plugin that can add polylines, polygons, rectangle, circle, and markers to a map and then edit or delete those objects as desired without using the GeoJSON code.
Leaflet Js has a variety of options for configuring the look and feel of the drawing objects. Leaflet.draw is more used for its ability to enable additional functionality, than an endpoint. It also provides the framework to take those drawn objects and push them to a database.

Leaflet.draw code description

Leaflet.draw is designed to not only be easy for end users to use, but also for developers to integrate. The following is really only suitable for demonstrating that you have it running correctly. Leaflet.draw is very simple to drop into you Leaflet application. The following example will add both the draw and edit tool bars to a map:

<html> 
<head>
<title>new map</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7/leaflet.css"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/0.2.3/leaflet.draw.css"/>
</head>
<body>

< div id="map" style="width: 600px; height: 400px;">
< /div >

< script src="http://cdn.leafletjs.com/leaflet-0.7/leaflet.js" >
 < / script > 
< script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/0.2.3/leaflet.draw.js" > < / script >
< script >
//Creating map and setting zoom
var map = L.map('map').setView([45.8650, -75.2094], 3);

// Set up the OSM layer
mapLink = '<a href="http://openstreetmap.org">OpenStreetMap</a>';
L.tileLayer( 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '&copy; ' + mapLink + ' Contributors',
maxZoom: 18,
}).addTo(map);

// Initialise the FeatureGroup to store editable layers
var drawnItems = new L.FeatureGroup();
map.addLayer(drawnItems);

// Initialise the draw control and pass it the FeatureGroup of editable layers
var drawControl = new L.Control.Draw({
edit: {
featureGroup: drawnItems
}
});
map.addControl(drawControl);
map.on('draw:created', function (e) {
var type = e.layerType,
layer = e.layer;
if (type === 'marker') {
layer.bindPopup('A popup!');
}
drawnItems.addLayer(layer);
});

< / script >
</body>
</html>
Result:
This code visualize both the draw and edit tool bars to a map:
Leaflet Js Plugin Basics Tutorial
Now let’s understand the above code in parts, The first part is an additional link to load more CSS code;
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/0.2.3/leaflet.draw.css"/>

This loads the file directly from the Leaflet.draw repository. And if you are loading from a local file you will need to adjust the path appropriately.

The second is the block that loads the leaflet.draw.js script.

< script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/0.2.3/leaflet.draw.js" > < / script > 

Leaflet.draw exists as a separate block of JavaScript code and again, here we are loading the file directly from the Leaflet.draw repository.

The last change to the file is the block of code that runs and configures Leaflet.draw.

      // Initialise the FeatureGroup to store editable layers
        var drawnItems = new L.FeatureGroup();
        map.addLayer(drawnItems);
      // Initialise the draw control and pass it the FeatureGroup of editable layers
         
        map.addControl(drawControl);
        map.on('draw:created', function (e) {
            var type = e.layerType,
                layer = e.layer;

       // Shows popup on marker when user’s action triggers

                  if (type === 'marker') {
                    layer.bindPopup('A popup!');
                  }
            drawnItems.addLayer(layer);
        });

layer group to the map called drawnItems. We store elements in this layer.

Then the map.addLayer(drawnItems); line adds the layer with our drawn items to the map.
Next we get to the first of the true Leaflet.draw commands when we initialize the draw control and pass it the feature group of editable layers;

var drawControl = new L.Control.Draw({
edit: {
featureGroup: drawnItems
}
});
map.addControl(drawControl);

For adding the edit toolbar and confirming which (drawnItems) should be editable. These controls are added to the map i.e. map.addControl(drawControl); .

Finally when we add a new vector or marker we need prompt a trigger that captures the type of item we have created (polyline, rectangle etc).

And adds it to the drawn items layer on the map.

map.on('draw:created', function (e) {
var type = e.layerType,
layer = e.layer;
// Show popup on marker when user’s action triggers
if (type === 'marker') {
layer.bindPopup('A popup!');
}
drawnItems.addLayer(layer);
});

In this code part you can store the information that described the element in a database or similar.

If you  are novice then check Leaflet js – Getting Started – Create Map Application

Furthermore, Try your hands on:

If you have any queries please comment in the comment box below.

Author: Akshay Upadhyay

Owner and Director of a Private Limited company which serves individual to large scale industries in the field of Maps and GIS. He is a Gold Medalist in M.Tech(Spatial Information Technology) and owns some famous Technology blogs and website... Know more

2 thoughts on “Leaflet Js Plugin Basics Tutorial”

  1. Hey thanks for this post.
    I really appreciate it.
    Can you please provide some resources about standards we should follow while creating plugin.
    Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.