Is it possible to change the opacity for the .kml file, that has been attached via leaflet-plugin?
Basically the plugin is here:
https://github.com/windycom/leaflet-kml
but after implementation into the Leaflet we have a full opaque image. It's fine for placemarks, but how about the icons/images included, which cover some box on the map?
My code looks like this:
var kml = fetch('Coventry.kml')
.then( res => res.text() )
.then( kmltext => {
// Create new kml overlay
parser = new DOMParser();
kml = parser.parseFromString(kmltext,"text/xml");
console.log(kml)
const track = new L.KML(kml)
map.addLayer(track)
// Adjust map to show the kml
const bounds = track.getBounds()
map.fitBounds( bounds )
}).setOpacity(0.6).addTo(map)
$('#sldOpacity').on('change', function(){
$('#image-opacity').html(this.value);
kml.setStyle({opacity: this.value, fillOpacity: this.value});
});
whereas to the pure code straight from the leaflet-kml example I added up sth like:
.setOpacity(0.6).addTo(map)
but isn't working.
The console states, that:
Uncaught TypeError: fetch(…).then(…).then(…).setOpacity is not a function
at (index):143
I was also trying this example:
Change opacity using leaflet without plugin
but it didn't help me unfortunately
In the L.KML.js file I found a snip:
var value = e.childNodes[0].nodeValue;
if (key === 'color') {
options.opacity = parseInt(value.substring(50, 50), 16) / 255.0;
options.color = '#' + value.substring(6, 8) +
value.substring(4, 6) + value.substring(2, 4);
} else if (key === 'width') {,
where in value.substring
I put 50 instead of 0. No result at all.
Is it some way to make this .kml layer more transparent?
Best Answer
You mixed a few things here.
kml
is XML object, not a Leaflet layer, so you cannot set opacity to it withsetOpacity
function or add it to the map.Leaflet layer that comes from kml and you are interested in is
track
. This is feature group layer for which you can set style withsetStyle
method. You have to declare it outsidefetch
, so it be available later to change it's opacity with slider.Your code could then look something like this:
EDIT: In your JSFiddle code you are using JQuery without link to library and you are using slider code without required HTML elements. Here is working JSFiddle (KML is defined in code): https://jsfiddle.net/TomazicM/7nxfgtu8/
Here is the main part of the code:
Remark: If you just copy code from various sources without understanding what it does you'll be in trouble all the time.