TransWikia.com

Display .kml file in Leaflet

Geographic Information Systems Asked on July 31, 2020

I would like to show my .kml file in my leaflet map.~

There is a plugin:
https://github.com/windycom/leaflet-kml
whixh unfortunately doesn’t work. It show only a blank map in the coordinates provided.
This issue has been risen here:
https://github.com/windycom/leaflet-kml/issues/3
where the basic explanation refers to the:

.then( res => response.text() )

and

const track = new L.KML(kml)

provided in the example:

https://github.com/genomexyz/sigmet-map

I have already uploaded my L.KML.js file alongside with the code, which now looks like this:

 // Load kml file
        fetch('LotA.kml')
            .then(res => response.text())
            .then(kmltext => {
                // Create new kml overlay
                const parser = new DOMParser();
                const kml = parser.parseFromString(kmltext, 'text/xml');
                const track = new L.KML(kmltext, 'text/xml');
                map.addLayer(track);

                // Adjust map to show the kml
                const bounds = track.getBounds();
                map.fitBounds(bounds);
            });

But the blank map comes again. I believe, that the change is minor, although I don’t know certainly where.
Is anyone able to clarify?

2 Answers

You are calling a variable response that does not exist

Replace line .then(res => response.text()) with .then(res => res.text())

If you had a catch statement before doing my recommended change, you will see the error (see below sample code). You current code had an error but silently fails as you didn't catch it...

// Load kml file
fetch('LotA.kml')
  .then(res => response.text())
  .then(kmltext => {
    // Create new kml overlay
    const parser = new DOMParser();
    const kml = parser.parseFromString(kmltext, 'text/xml');
    const track = new L.KML(kmltext, 'text/xml');
    map.addLayer(track);

    // Adjust map to show the kml
    const bounds = track.getBounds();
    map.fitBounds(bounds);
}).catch((e) => {
  console.log(e);
});

I've made a working demo but using "leaflet-omnivore" library

Correct answer by ThomasG77 on July 31, 2020

First thing if I would suggest is - run the code on localhost.

Keeping editor offline only leads to misleading conclusions, that code isn't working.

I tried this stuff on localhost and everything works fine.

Answered by MKR on July 31, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP