Web Programming TutorialsGet Started With Leaflet JS

Get Started With Leaflet JS

Leaflet js is a light weight JavaScript library which is used for deploying maps on a web page. It consists of a JavaScript library with absolutely no dependencies, making it unique than other libraries.

It provides access to a range of functions which will allow you to present a map.

Features: –
1. It supports most desktops and mobile platforms.
2. It consists of 34KB of JavaScript which is mapped with a HTML file.
3. It is an open source library and has a vibrant and active community.
4. It is equally popular to OpenLayers and Google Maps API
5. Leaflet is used mostly by GIS developers as it is known for its accuracy in determining location.

Example: –
Map

Getting Started with Leaflet:
Let’s start by creating a simple map with the help of Leaflet with just few lines of code.
As it is a web map, it is mandatory that it will be hosted with the help of a web page. Hence, pre-requisite for a leaflet map is knowing how to create an HTML file.

Create a file named “map.html”

<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
-->
<html>
    <head>
        <title>Leaflet.js Map</</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        
    </body>
</html>

Steps to Create a Map
Step 1: – Reference the Leaflet.js library and the CSS file
Referencing the Leaflet library can be done in two ways.
First, by using the hosted version or CDN (Content Delivery Network) and second one is to download the leaflet.js library and host it on your own web server.

Accessing Leaflet.js via CDN:

<head> <title>My Leaflet.js Map</title> 
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.3/leaflet.css" />
<script src="http://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.3/leaflet.js"> 
</script> 
</head>

Downloading the Leaflet.js library
For that, the user needs to download the appropriate package from the official website.
After downloading the pre-built package, it is linked to the appropriate path (link and script tags).
Step 2: – Creating a div element for the map
Create a div element of map with id attribute which provides styling features with appropriate height and width.

<html>
    <head>
        <title>Leaflet.js Map</</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <style>
            #mapid {
                width: 600px; 
                height: 400px
            } 
        </style>
    </head>
    <body>
        <div id="mapid"></div>
    </body>
</html>

Step 3: – Creating a map object
It is important to create a map object with the help of which it will be easier to display the view of map or add overlays to the same.

<!DOCTYPE html>
<html>
  <head>
    <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
    <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" />
    <link rel="stylesheet" type="text/css" href="leaflet/leaflet.css" />
    <!--[if lte IE 8]>
    <link rel="stylesheet" type="text/css" href=" leaflet/
      leaflet.ie.css" />
    <![endif]-->
    <script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
    <script type="text/javascript" src="http://maps.stamen.com/js/tile.stamen.js?v1.2.4"></script>
    <script src="leaflet/leaflet.js"></script>
    <style>
      html, body, #mapid {
      width: 600px; 
      height: 400px
      }
    </style>
    <title>Leaflet</title>
  </head>
  <body>
    <div id="mapid"></div>
    <script type="text/javascript">
      var mymap = L.map('mapid').setView([51.73, -1.28],5);
       L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png').addTo(mymap);
    </script>
  </body>
</html>

The variable mymap is a map object created by using setView function which accepts 3 parameters latitude, longitude and zoom level.
Later, a new layer is being added to the map named tileLayer.
The TileLayer object’s constructor takes as its first parameter a URL which specifies the application where to get the data from.
• The {s}, {z}, {x}, and {y} in the URL represent the following:
• {s} allows one of the subdomains of the primary domain to serve tile requests, enabling our application to make multiple requests simultaneously, and thereby download tiles much faster.
• {x} and {y} define the tile coordinates.
• {z} represents the zoom level.
Finally, Tilelayer.addTo() method is called which includes the map object where we want the layer to appear.
Output: –
Map-2
GeoJSON:
It is an extension of JSON (JavaScript Object Notation) which gives the complete geometrical details of all geographical area which we want to cover and display on the map.
With the help of these geometries and figures, a developer can create an overlay with polylines and polygons. GeoJson is like a boon to all developers who associate maps and their data in programming.
It is considered as a highly convenient way of displaying geospatial features i.e. their attributes and other data in a portable way.
Example: –

{ "type": "FeatureCollection",
    "features": [
      { "type": "Feature",
        "geometry": {"type": "Point", "coordinates": [102.0, 0.5]},
        "properties": {"prop0": "value0"}
        },
      { "type": "Feature",
        "geometry": {
          "type": "LineString",
          "coordinates": [
            [102.0, 0.0], [103.0, 1.0], [104.0, 0.0], [105.0, 1.0]
            ]
          },
        "properties": {
          "prop0": "value0",
          "prop1": 0.0
          }
        },
      { "type": "Feature",
         "geometry": {
           "type": "Polygon",
           "coordinates": [
             [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0],
               [100.0, 1.0], [100.0, 0.0] ]
             ]
         },
         "properties": {
           "prop0": "value0",
           "prop1": {"this": "that"}
           }
         }
       ] }

Importing External Data
Step 1: Create a database namely “homedb”.

create DATABASE homedb;

Step 2: Create a table “worlddata”. The structure of the table is represented as below:
World Data
Step 3: Insert the records in this specified table. These records will be fetched to display map

INSERT INTO `worlddata` (`name`, `latitude`, `longitude`) VALUES
(‘New York’, ‘41’, ‘-74’),
(‘Boston’, ‘42’, ‘-71’),
(‘Atlanta’, ‘35’, ‘-79’),
(‘Miami’, ‘26’, ‘-80’),
(‘Houston, ‘30’, ‘-95’),

The result of search query:
Select * from worlddata;
Output: –
World Data 1
Step 4: Connect with database with PHP script and fetch the records

<?php
$username   = "homedbuser";
$password   = "";
$host       = "localhost";
$database   = "homedb";
$server     = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$myquery    = "
SELECT * FROM `worlddata`";
$query      = mysql_query($myquery);
if (!$query)
                {
                echo mysql_error();
                die;
                }
/*else
{
echo 'Success!';
}*/
$data = array();
echo "var planelatlong = [";
for ($x = 0; $x < mysql_num_rows($query); $x++)
                {
                $data[] = mysql_fetch_assoc($query);
                echo "[", $data[$x]['latitude'], ",", $data[$x]['longitude'], "]";
                
                //echo "[",$data[$x]['name'],",",$data[$x]['latitude'],",",$data[$x]['longitude'],"]";
                //echo"<br>";
                if ($x <= (mysql_num_rows($query) - 2))
                                {
                                echo ",";
                                }
                }
echo "];";
$dataname = array();
echo "var dataNames = [";
for ($x = 0; $x < mysql_num_rows($query); $x++)
                {
                $dataname[] = mysql_fetch_assoc($query);
                //echo "",$data[$x]["name"],"";
                
                //echo "[",$data[$x]['name'],",",$data[$x]['latitude'],",",$data[$x]['longitude'],"]";
                //echo"<br>";
                if ($x <= (mysql_num_rows($query) - 2))
                                {
                                echo ",";
                                }
                
                }
echo "];";

mysql_close($server);
?>
Output: -
Connect PHP
Step 5: HTML page which will display the map
<!DOCTYPE html>

<html>
  <head>
    <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
    <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" />
    <link rel="stylesheet" type="text/css" href="leaflet/leaflet.css" />
    <!--[if lte IE 8]>
    <link rel="stylesheet" type="text/css" href=" leaflet/
      leaflet.ie.css" />
    <![endif]-->
    <script src="http://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.3/leaflet.js"></script>
    <script type="text/javascript" src="http://maps.stamen.com/js/tile.stamen.js?v1.2.4"></script>
    <script src="leaflet/leaflet.js"></script>
    <style>
      html, body, #map {
      width: 100%;
      height: 100%;
      }
    </style>
    <title>Leaflet</title>
  </head>
    <body>
        <div id="map"></div>
        <script type="text/javascript">
        <?php include 'connectPHP.php'; ?>
      var map = L.map('map').setView([35.9908385, -78.9005222], 5);
        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);
    var polyline = L.polyline(planelatlong).addTo(map);
     var marker = L.marker(planelatlong).addTo(map);
   // console.log(dataNames);
   // var marker=L.marker(planelatlong).bindPopup(dataNames.toString());
    </script>
  </body>
</html>

Output: –
SQL Map

// ]]>

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -