Sunday, October 31, 2021

LeafletJS - 3 ways to plot lines and add to layer control

 In this post, I will share three ways to plot lines and add it to layer control. The general concept is that you need to have at least two pairs of coordinates (line starting point and line ending point) to draw a line with the L.polyline() function.

Lets get started...

1) Plot line from given point coordinates

Here we will plot line between two point by simply providing the starting and ending point coordinates of the line. 

<!DOCTYPE html>
	<title>Leaflet Map...</title>

	<meta charset="utf-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<!-- <link rel="shortcut icon" type="image/x-icon" href="docs/images/favicon.ico" /> -->

    <link rel="stylesheet" href="" integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A==" crossorigin=""/>

    <script src="" integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA==" crossorigin=""></script>


<!-- Several ways to plot lines and add to layer control: From set of corrdinates and from geoJSON file -->

<div id="mapid" style="width: 100%; height: 600px;"></div>

	// Create the map obj...
	var mymap ='mapid', {minZoom: 2, maxZoom: 20})
				 .setView([0, 0], 2);

	// Restrict panning to this bounds
	var southWest = L.latLng(-90, -180),
		northEast = L.latLng(90, 180);
	var bounds = L.latLngBounds(southWest, northEast);


// Google Street Map - Set basemap...
        // minZoom: 0,
     	maxZoom: 18,

// ------------------------------
// 1) Plot line from given point coordinates...
var pointA = new L.LatLng(40.71560515,-74.03714387);
var pointB = new L.LatLng(9.72406588,10.99793816);
var pointC = new L.LatLng(51.51778519,-0.09678893);

var pointList1 = [pointA, pointC];
var pointList2 = [pointB, pointC];

var line_network = L.polyline([pointList1, pointList2], {
	color: 'red',
	weight: 3,
	opacity: 0.5,
	smoothFactor: 1

}); //.addTo(mymap)

line_network.bindPopup('This line was drawn from given point coordinates')

// Add to layerGroup and layer control...
var lines = L.layerGroup([line_network]);

var overlayMaps = {
    'Line Method 1': lines,

var baseLayers = {
	// basemaps goes here...

L.control.layers(baseLayers, overlayMaps, {collapsed: false}).addTo(mymap);



2) Plot line from geoJSON file

Here you need to prepare the line GeoJSON file, then use L.geoJSON() function to draw it on the map. So, create a JS file and save the GeoJSON code in it with a variable name you will refer to in the main HTML/JS code (depending on how you structure you code files).

In this case I had a Lines.js file as seen below which holds the GeoJSON code in a variable named "line_data", then I referenced it in index.html file as seen below.