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.
 
Pre-requistive
 
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"
    integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
  crossorigin=""/>

<script src="https://unpkg.com/leaflet@1.5.1/dist/leaflet.js"
    integrity="sha512-GffPMF3RvMeYyc1LWMHtK8EbPv0iNZ8/oTtHPx9/cc2ILxQ+u905qIwdpULaqDkyBKgOaB57QTMg7ztg8Jm2Og=="
  crossorigin=""></script>

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',
 }).addTo(mymap);
 

 
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"]
          }).addTo(mymap);

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.createPane('labels');
                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'
                }).addTo(mymap);
 
 

 
We can position zoom control on any position. Below we can position it is in topright and add it to map.
 
                L.control.zoom({
                    position: "topright"
                }).addTo(mymap);
 
 
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.
 
   fetch('./assets/sample.kml')
                    .then(res=>res.text())
                    .then(kmltext => {
                        const parser = new DOMParser();
                        const kmlnodes = parser.parseFromString(kmltext, 'text/xml');   
                        const layers =  new L.KML(kmlnodes);
                        mymap.addLayer(layers);

                        const bounds = layers.getBounds();
                        console.log(bounds);
                        mymap.fitBounds(bounds);
                    });
 
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">
<Document>
    <name>Sample</name>
    <Placemark>
        <name>Zürich</name>
        <Style>
            <IconStyle>
                <Icon><href>http://maps.google.com/mapfiles/kml/pushpin/ylw-pushpin.png</href></Icon>
            </IconStyle>
        </Style>
        <Point>
            <coordinates>8.543240928407617,47.36695287673603,0</coordinates>
        </Point>
    </Placemark>
</Document>

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">
        <IconStyle>
        <Icon>
            <href>https://maps.google.com/mapfiles/kml/paddle/wht-blank.png</href>
        </Icon>
        </IconStyle>
    </Style>
    <Placemark>
        <name>Roll over this icon</name>
        <visibility>0</visibility>
        <styleUrl>#normalPlacemark</styleUrl>
        <Point>
            <coordinates>-122.0856545755255,37.42243077405461,0</coordinates>
        </Point>
    </Placemark>
 
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">
      <LineStyle>
        <color>87000000</color>
        <width>10</width>
      </LineStyle>
    </Style> 
    <Placemark>
        <name>Relative</name>
        <visibility>0</visibility>
        <description>Black line (10 pixels wide), height tracks terrain</description>
        <LookAt>
          <longitude>-112.2580438551384</longitude>
          <latitude>36.1072674824385</latitude>
          <altitude>0</altitude>
          <heading>4.947421249553717</heading>
          <tilt>44.61324882043339</tilt>
          <range>2927.61105910266</range>
        </LookAt>
        <styleUrl>#thickBlackLine</styleUrl>
        <LineString>
          <tessellate>1</tessellate>
          <altitudeMode>relativeToGround</altitudeMode>
          <coordinates> -112.2532845153347,36.09886943729116,645
            -112.2540466121145,36.09919570465255,645
            -112.254734666947,36.09984998366178,645
            -112.255493345654,36.10051310621746,645
            -112.2563157098468,36.10108441943419,645
            -112.2568033076439,36.10159722088088,645
            -112.257494011321,36.10204323542867,645
            -112.2584106072308,36.10229131995655,645
            -112.2596588987972,36.10240001286358,645
            -112.2610581199487,36.10213176873407,645
            -112.2626285262793,36.10157011437219,645 </coordinates>
        </LineString>
      </Placemark>
 

 
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.
 
Reference:
 
 

Sponsored:
To find embedded technology information about MCU, IoT, AI etc Check out embedkari.com.


   

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