Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to load KML layers on Leaflet?

Tags:

leaflet

kml

I have to load a KML layer on a Leaflet app. After some browsing I found a library called leaflet-kml that does this. There are two ways that I can load the KML layer: either by the KML layer's URI or a KML string. The KML is stored in a server and I have backend code that retrieves both the URI and string representation.

Here is the approach using the URI.

function LoadKML(containerName, name)
{
     let kmlURL = GetKmlURI(containerName, name);  
     let kmlLayer = new L.KML(kmlURL);
     map.addLayer(kmlLayer);
}

Here is the approach using the kml string.

function LoadKML(containerName, name)
{
     let kmlString = GetKmlString(containerName, name);  
     let kmlLayer = new L.KML.parseKML(kmlString);
     map.addLayer(kmlLayer);
}

I could not get a URL with the first method due to the CORS restriction. The second method returns a string, but could not be parsed correctly.

KML.js:77 Uncaught TypeError: this.parseStyles is not a function
    at new parseKML (KML.js:77)
    at LoadKML (Account:470)
    at Account:461

How should I call the function in leaflet-kml? Are there any libraries that can easily load KML into leaflet?

like image 359
disguisedtoast Avatar asked Oct 19 '25 14:10

disguisedtoast


1 Answers

You can use leaflet-omnivore. It is the best plugin for loading KML files (https://github.com/mapbox/leaflet-omnivore)

var kmlData = omnivore.kml('data/kmlData.kml', null, customLayer);
like image 86
geocadder Avatar answered Oct 21 '25 07:10

geocadder