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>
<html>
<head>
	
	<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="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>

	
</head>
<body>

<!-- 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>



<script>
	// Create the map obj...
	var mymap = L.map('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);

	mymap.setMaxBounds(bounds);


// Google Street Map - Set basemap...
    L.tileLayer('http://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}',{
        // minZoom: 0,
     	maxZoom: 18,
        subdomains:['mt0','mt1','mt2','mt3']
    }).addTo(mymap);




// ------------------------------
// 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);


</script>



</body>
</html>




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.

var line_data = {
"type": "FeatureCollection",
"name": "Lines",
"features": [
{ "type": "Feature", "properties": { "id": null }, "geometry": { "type": "MultiLineString", "coordinates": [ [ [ -0.09678893, 51.51778519 ], [ -73.99793816, 40.72406588 ] ] ] } },
{ "type": "Feature", "properties": { "id": null }, "geometry": { "type": "MultiLineString", "coordinates": [ [ [ -74.03714387, 40.71560515 ], [ 4.37661054070514, 50.836889849958787 ] ] ] } },
{ "type": "Feature", "properties": { "id": null }, "geometry": { "type": "MultiLineString", "coordinates": [ [ [ 2.234208343870105, 53.466492837093192 ], [ 6.128004498337659, 49.61223242721907 ] ] ] } },
{ "type": "Feature", "properties": { "id": null }, "geometry": { "type": "MultiLineString", "coordinates": [ [ [ -58.518430844169956, -34.728850506424891 ], [ -3.692084186370896, 40.413977829100794 ] ] ] } },
{ "type": "Feature", "properties": { "id": null }, "geometry": { "type": "MultiLineString", "coordinates": [ [ [ 174.727142569369647, -36.867290796295435 ], [ 115.858031455773698, -31.956123305704303 ] ] ] } }
]
}


<!DOCTYPE html>
<html>
<head>
	
	<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="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>

    <!-- GeoJSON OR JSON Data -->
    <script src="Lines.js"></script>
	
</head>
<body>

<!-- 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>



<script>
	// Create the map obj...
	var mymap = L.map('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);

	mymap.setMaxBounds(bounds);


// Google Street Map - Set basemap...
    L.tileLayer('http://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}',{
        // minZoom: 0,
     	maxZoom: 18,
        subdomains:['mt0','mt1','mt2','mt3']
    }).addTo(mymap);




// ------------------------------
// 2) Plot line from geoJSON file...
var geojsonline = L.geoJSON(line_data, {
	color: 'red',
	weight: 3,
	opacity: 0.5,
	smoothFactor: 1
}); //.addTo(mymap);


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

var baseLayers = {
	// basemaps will go here
};

var overlayMaps = {
    'Line Method 2: GeoJSON Line': geoJsonlines,
};


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

</script>



</body>
</html>


3) Plot line from point arrays in JS or other file

Compared to the two methods above, this is more dynamic in the sense that we will create an array object to hold the point data for drawing the lines.

The point data can come from anywhere including js file, csv file, database etc. Here I will use a js file as we saw above.



var line_data2 = [
 {
   "LocationDate": "2019-01-12T00:00:00",
   "LocationTime": "15:08:21",
   "Latitude": 51.51778519,
   "Longitude": -0.09678893,
   "imageURL": "https://i.pinimg.com/564x/50/91/3e/50913eeb04768a5b1fa9985c16704d96.jpg"
 },
 {
   "LocationDate": "2020-04-04T00:00:00",
   "LocationTime": "12:05:21",
   "Latitude": 9.72406588,
   "Longitude": 10.99793816,
   "imageURL": "https://i.pinimg.com/236x/ba/14/dc/ba14dca9b7d5cbbde95bcb93beb465cd.jpg"
 },
 {
   "LocationDate": "2020-02-14T00:00:00",
   "LocationTime": "9:08:21",
   "Latitude": 40.71560515,
   "Longitude": -74.03714387,
   "imageURL": "https://i.pinimg.com/236x/ca/c8/90/cac890b5f5b818c7fc97f9012551ba0b.jpg"
 }
]


<!DOCTYPE html>
<html>
<head>
	
	<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="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>

    <!-- GeoJSON Data -->
    <script src="Lines.js"></script>

	
</head>
<body>

<!-- 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>



<script>
	// Create the map obj...
	var mymap = L.map('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);

	mymap.setMaxBounds(bounds);


// Google Street Map - Set basemap...
    L.tileLayer('http://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}',{
        // minZoom: 0,
     	maxZoom: 18,
        subdomains:['mt0','mt1','mt2','mt3']
    }).addTo(mymap);




// ------------------------------
// 3) Plot line from point arrays in JS or other file...

let polylinePoints = new Array()

for (let i = 0; i < line_data2.length; i++) {
	let lat = line_data2[i].Latitude;
	let long = line_data2[i].Longitude;

	polylinePoints.push([lat, long]);

}

console.log(polylinePoints)

var polyline = L.polyline(polylinePoints); // .addTo(mymap)


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

var baseLayers = {
	// basemaps will go here
};

var overlayMaps = {
    'Line Method 3: Point arrays': looplines,
};


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


</script>



</body>
</html>

Note that all we have done above, are also applicable to points and polygons.

That is it. Enjoy!

No comments:

Post a Comment