Leaflet and Keyhole Markup Language (KML)

  •        0

We aggregate and tag open source projects. We have collections of more than one million projects. Check out the projects section.

Leaflet, a open-source JavaScript library for interactive maps. It is a well-documented API and extended with lot of plugins. It is also designed with simplicity, performance and usability. 
Keyhole Markup Language is XML notation for expressing geographic annotation and visualization. It was developed by GoogleEarth initially and used now as open standard for map geolocation by the Open Geospatial Consortium, Inc. (OGC). KML schema has the details and representation of the layers.
There are many examples about how to use leaflet. In this article, we will go through create a map and adding KML with abilities to different notation.
Leaflet css and js file has to be imported either through CDN or download to have it part of the project.
 <link rel="stylesheet" href="https://unpkg.com/leaflet@1.5.1/dist/leaflet.css"

<script src="https://unpkg.com/leaflet@1.5.1/dist/leaflet.js"

Create map:
Create a map using the L.map constructor by passing the html element id and the options for creating the map.
   var mymap = L.map("mapdiv", {
                    center: new L.LatLng(12.9716, 77.5946),
                    zoomControl : false,
                    zoom: 7,
Map tiles can be streetview, it is done by passing passing the dynamic tile layer URL which changes based on the zoom level.
 L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
     attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',

Satellite view can be placed by changing the tile layer as below, each tile details can also be specified by the sub domains to it.  We can also specify the zoom level till which we want it to zoom in.
   L.tileLayer("http://{s}.google.com/vt/lyrs=s&x={x}&y={y}&z={z}", {
              attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap
</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>',
              maxZoom: 30,
              subdomains: ["mt0", "mt1", "mt2", "mt3"]

Overlay any labels on top of the map so that it can be made more readable. It can be done by creating panes on the map and setting style parameter. Then add the label tiles to top of the overlay and display it.
                mymap.getPane('labels').style.zIndex = 650;
                mymap.getPane('labels').style.pointerEvents = 'none';
                var positronLabels = L.tileLayer('
               https://{s}.basemaps.cartocdn.com/light_only_labels/{z}/{x}/{y}.png', {
                        attribution: '©OpenStreetMap, ©CartoDB',
                        pane: 'labels'

We can position zoom control on any position. Below we can position it is in topright and add it to map.
                    position: "topright"
Leaflet KML Plugin:
KML can be layered on map using leaflet KML Plugin[https://github.com/windycom/leaflet-kml]. KML file can be fetched and parsed using DOM Parser. Then KML nodes passed to L.KML constructor which provides the layers, then layers can be added to leaflet map.
                    .then(kmltext => {
                        const parser = new DOMParser();
                        const kmlnodes = parser.parseFromString(kmltext, 'text/xml');   
                        const layers =  new L.KML(kmlnodes);

                        const bounds = layers.getBounds();
How to create Points?
KML is XML format of representing the map notation. It has root tag of Document. Inside which placemark is for marking of the geo location with Point coordinates and to represent it can be done by IconStyle with Icon tag.
Below placemark snippet will mark the Zurich location with pin icon.
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">

Placemark can be mapped external style url. The style tag id can be marked as as styleurl within the placemark. On click of the tooltip, the tooltip is automatically bind up by leaflet KML Plugin with tooltip content with text mentioned in the name tag.
   <Style id="normalPlacemark">
        <name>Roll over this icon</name>
How to create Polylines?
Placemark can be made polylines by using linestring which comprises of co-ordinates from one location to another location. This location can be marked as thick black line by style tag. When we click on the line string, the description tag content will be shown in the tooltip. Placemark has been done by relative positioning with lookat displacement from the longitude and latitude.
   <Style id="thickBlackLine">
        <description>Black line (10 pixels wide), height tracks terrain</description>
          <coordinates> -112.2532845153347,36.09886943729116,645
            -112.2626285262793,36.10157011437219,645 </coordinates>

We can add more options like showing heat maps, screen overlay and ground overlay to show natural calamities like cyclone, earthquakes and so on. It also provides map projections. A map projection is a systematic transformation of the latitudes and longitudes of locations from the surface of a sphere or an ellipsoid into locations on a plane.


Nagappan is a techie-geek and a full-stack senior developer having 10+ years of experience in both front-end and back-end. He has experience on front-end web technologies like HTML, CSS, JAVASCRIPT, Angular and expert in Java and related frameworks like Spring, Struts, EJB and RESTEasy framework. He hold bachelors degree in computer science and he is very passionate in learning new technologies.

Subscribe to our newsletter.

We will send mail once in a week about latest updates on open source tools and technologies. subscribe our newsletter

Related Articles

Getting Started With Django Python Web Framework

  • django python web-framework

Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. It is pre-loaded with user authentication, content administration, site maps, RSS feeds and many more tasks. Security features provided are cross site scripting (XSS) protection, cross site request forgery protection, SQL injection protection, click-jacking protection, host header validation, session security and so on. It also provides in built caching framework.

Read More

We have large collection of open source products. Follow the tags from Tag Cloud >>

Open source products are scattered around the web. Please provide information about the open source projects you own / you use. Add Projects.