windycom / leaflet-kml Goto Github PK
View Code? Open in Web Editor NEW🌎Leaflet KML layer plugin
🌎Leaflet KML layer plugin
Hello,
I am new to leaflet, and trying to use the code below to add an online kml file to leaflet. The background map shows, but the kml layer is not added. I am new to leaflet, please help:
<script src="http://unpkg.com/[email protected]/dist/leaflet.js"></script> <script src="./L.KML.js"></script> <script type="text/javascript"> // Make basemap const map = new L.Map('map', { center: new L.LatLng(10, 0.0), zoom: 3}); const osm = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'); map.addLayer(osm);
// Load kml file
fetch('https://www.cpc.ncep.noaa.gov/products/international/gefs/gefs_week1_af_precip_obs.kml')
.then(res => res.text())
.then(kmltext => {
// Create new kml overlay
const parser = new DOMParser();
const kml = parser.parseFromString(kmltext, 'text/xml');
const track = new L.KML(kml);
map.addLayer(track);
// Adjust map to show the kml
const bounds = track.getBounds();
map.fitBounds(bounds);
});
</script>
</body>
Hello!
The sample code provided in the readme file indicates that you can load a KML file by providing the file path:
var track = new L.KML("assets/example1.kml", {async: true});
Running this code throws DOM parsing errors. Looking into the source code, it appears that the KML plugin expects to receive a DOM object rather than a file path. The original KML plugin had a loadXML
function which retrieved the DOM object, but this plugin does not seem to have that functionality.
jQuery.get( 'assets/example1.kml' )
.then( ( kmlDocument ) => {
var track = new L.KML( kmlDocument, { async: true } )
this.map.addLayer( track )
} )
Any questions, let me know. Thanks for providing this plugin! :)
Regards,
-- Dan
I have loaded a kml file with Icon hrefs.
Example Snippet:
<Style id="icon-1899-0288D1-nodesc-normal"> <IconStyle> <color>ffd18802</color> <scale>1</scale> <Icon> <href>https://www.gstatic.com/mapspro/images/stock/503-wht-blank_maps.png</href> </Icon> <hotSpot x="32" xunits="pixels" y="64" yunits="insetPixels"/> </IconStyle> <LabelStyle> <scale>0</scale> </LabelStyle> <BalloonStyle> <text><![CDATA[<h3>$[name]</h3>]]></text> </BalloonStyle> </Style>
Is it possible to override these Icons afterwards?
Hi, I got a error with a KML. Bug comes from threre:
<Style id="LineLabels">
<IconStyle>
<scale>0.8</scale>
<Icon />
</IconStyle>
<LabelStyle>
<scale>0.7</scale>
</LabelStyle>
</Style>
I've corrected you're code to prevent the bug: Line 99
} else if (e.childNodes.length !== 0) {
instead of
} else {
I have loaded the layer in the leaflet. but the I want to add click event in the layer.
I didn't find any documentation for this.
Thank you
Could be possible to have a search query for the following KML files attached (search within KML name and the description content) as well as leaflet-plugin or control geocoder?
Thanks
Hi,
I wanted to see how I can change the fillOpacity, I need to only see the perimeter without filling.
Thanks
Regards
I think the plugin will be helpful if the upload button is added to the frontend. If the user can manually add the required data format, it will be helpful for user.
I have got a blank map, even when stick to this solution:
Could you roughly show how the code should look?
It would be useful for newbies.
Thanks,
I need to add to a map many points (placemarks).
When i try to load the kml, this error occours:
Uncaught (in promise) RangeError: Maximum call stack size exceeded
at a (utils.js:127)
at i._parseKML (KMZLayer.js:56)
at i._parse (KMZLayer.js:36)
at KMZLayer.js:32
Promise.then (async)
load @ KMZLayer.js:28
(anonymous) @ (index):88
there is exist a way to bypass the limit of points?
I'm trying to integrate this into a project so far without success so as a test I thought that I'd impliment the example code shown in the read me file but it doesn't appear to work.
I get a map but no KML is plotted on it (I'm using example2.kml). I'm not getting any console errors in my browser either.
Can someone confirm that the example in the read me file works ?
I tried to use Leaflet KML layer plugin but it doesn't show the layer. I first thought it was a problem with my code or my kml, but even when I just copied the code en de example1.kml from https://github.com/windycom/leaflet-kml and used that in an example html, I published it on www.thebestofgeocaching.nl/testmap/testmap.html. But even now only the map showed and not the overlay. What am I doing wrong?
Hi
Nice plug in.
I have a kml file that uses html for the contents of the balloon when a place icon is clicked on. Here is an example.
<Placemark>
<name>Mulhacén II (3362m)</name>
<description>
<![CDATA[
<DIV style='max-width:400px; margin-right:10px; margin-bottom:10px; color:#674A32; font-family:Arial'>
<DIV style='font-size:11pt; font-weight:bold; text-align:left'>
Mulhacén II (3362m)<BR>
</DIV>
<DIV style='font-size:10pt; text-align:justify'>
<BR>
<IMG SRC='Info_MulhacenII.jpg' width='96px' height='120px' align='left' title='Summit of Mulhacén II' style='margin-right:10px'>
'Los Tres Miles' rank: 4<BR><BR>
Mulhacén II lies in Mulhacén's south ridge. It's summit is marked geodetic column.
</DIV>
</DIV>
]]>
</description>
<styleUrl>#Summit_Target</styleUrl>
<Point><coordinates>-3.3120817235360001,37.0442429896920018,0</coordinates></Point>
</Placemark>
When used with Google maps or Google Earth the balloon expands to fit the text and graphic.
Unfortunately the with this plug in, unless the text is long enough to wrap around the image, the image will extend beyond the balloon. Like this...
This is what it looks like in Google Earth....
You'll also notice that Google Earth is not showing the placemark name. It has been deliberately disabled so that I could have more control over it. Here's the KML that defines styling on the placemark and balloon.
<Style id='Summit_Target'>
<IconStyle>
<Icon>
<href>https://www.virtualmountains.co.uk/shared/Summit_Target.png</href>
</Icon>
</IconStyle>
<BalloonStyle>
<text>$[description]</text>
<bgColor>white</bgColor>
<text><![CDATA[
<font color='#674A32' face='arial' align='justify'>$[description]</font>
]]></text>
</BalloonStyle>
<LabelStyle>
<color>FF14B450</color>
<scale>0.8</scale>
</LabelStyle>
</Style>
Any useful suggestions as to how I can reproduce this with the leaflet plugin. I'm wanting to use the same KML file for both Google Maps and Leaflet.
Many thanks
Derek
An Image should be downloaded when zooming reaches <minLodPixels>200</minLodPixels>
value but this is not happening.
All images are downloaded when map rendering starts. If there are thousands of images then this is not going to work.
In ideal condition images should be loaded w.r.t map center and zooming level. As it happens in Google Maps.
<Folder> <Region> <LatLonAltBox> <west>174.96510016880586</west> <east>174.99828859706068</east> <south>-37.147368506798173</south> <north>-37.12079474453428</north> </LatLonAltBox> <Lod> <minLodPixels>200</minLodPixels> <maxLodPixels>-1</maxLodPixels> </Lod> </Region> <GroundOverlay> <LatLonBox> <west>174.96510016880586</west> <east>174.99828859706068</east> <south>-37.147368506798173</south> <north>-37.12079474453428</north> </LatLonBox> <drawOrder>1</drawOrder> <Icon> <href>a.png</href> </Icon> </GroundOverlay> <name>a.png</name></Folder>
If a element is encountered, the 'parsePlacemark' function recurses into itself and passes the element in as the 'place' root node for the purposes of parsing.
However, in a placemark, the name and description aren't children of 'MultiGeometry', so the context is lost when binding the popup.
Hi there!
Currently trying to use the library to show a point on leaflet map.
I'm using Leaflet 1.7.1 with L.KML plugin.
In my kml file I have an icon from network:
<Style id="icon-62-normal">
<IconStyle>
<Icon>
<href>https://maps.google.com/mapfiles/kml/shapes/triangle.png</href>
</Icon>
</IconStyle>
</Style>
Here is the way I'm loading KML file:
var track = new L.KML('../UserData/test3.kml', { async: true })
.on('loaded', function (e) {
//map.fitBounds(e.target.getBounds());
})
.addTo(map);
But formaly it trying to load another icon called marker-icon.png from local path.
I have doublechecked the kml file there is no call of that icon in any place.
Could you help please?
Thanks
There is an issue reported in the leaflet bug tracker about disappearing polygons: Leaflet/Leaflet#6075.
Ultimately, the maintainer has recommended to always use an integer value for "weight" when creating a layer style. I'm not sure why this is the case, but following this advice seems to completely fix the problem for me as well.
A simple fix for the KML library is to cast the style weight to an integer.
Hi,
I'm getting this error TypeError: L.KML is not a constructor
The base map is loaded correctly in fact I've uploaded a geojson file in my map and there isn't error with this file.
The only one issue I have is with the kml file.
These area my leaflet url and my L.KML.js file in my HTML.
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css"
integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
crossorigin=""/>
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"
integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew=="
crossorigin=""></script>
<script src="{{ url_for('static', filename='js/leaflet-kml-master/L.KML.js') }}"></script>
My js file looks like:
var basemap = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
});
var overlay_Google_Satellite_0 = L.tileLayer('https://mt1.google.com/vt/lyrs=s&x={x}&y={y}&z={z}', {
opacity: 1.0
});
var map = L.map('map', {zoomControl:true, maxZoom:28, minZoom:1, layers: [basemap]});
basemap.addTo(map);
map.addLayer(basemap);
var baseMaps_baseMaps = {
"<span style='color: gray'>OpenStreetMap</span>": mapbox_street,
"<span style='color: gray'>Google_Satellite</span>": overlay_Google_Satellite_0
`};
fetch('static/data/index/CiC_2.kml')
.then(res => res.text())
.then(kmltext => {
const parser = new DOMParser();
const kml = parser.parseFromString(kmltext, 'text/xml');
const cic = new L.KML(kml);
map.addLayer(cic);
const bounds = track.getBounds();
map.fitBounds(bounds);
});
L.control.layers(baseMaps_baseMaps, clust_layers,{collapsed:true, position: 'topleft'}).addTo(map);
import { useEffect } from 'react'
import L from 'leaflet'
import { useLeafletContext } from '@react-leaflet/core'
import 'leaflet-kml'
const KMLayer = () => {
const context = useLeafletContext()
const container = context.layerContainer || context.map
useEffect(() => {
let track = null
fetch('./beam.kml')
.then((res) => res.text())
.then((kmltext) => {
const parser = new DOMParser()
const kml = parser.parseFromString(kmltext, 'text/xml')
const icon = L.icon({
iconUrl: '../image_san/hub_green.png',
iconSize: [20, 70],
})
track = new L.KML(kml, {
iconOptions: icon,
})
container.addLayer(track)
})
return () => {
container.removeLayer(track)
}
}, [container])
return null
}
export default KMLayer
This gives the following error:
Icon.js:109 Uncaught Error: iconUrl not set in Icon options (see the docs).
at NewClass._createIcon (Icon.js:109:1)
at NewClass.createIcon (Icon.js:95:1)
at NewClass._initIcon (Marker.js:215:1)
at NewClass.onAdd (Marker.js:122:1)
at NewClass._layerAdd (Layer.js:114:1)
at NewClass.whenReady (Map.js:1477:1)
at NewClass.addLayer (Layer.js:172:1)
at NewClass.eachLayer (LayerGroup.js:122:1)
at NewClass.onAdd (LayerGroup.js:106:1)
at NewClass._layerAdd (Layer.js:114:1)
The beam.kml is in public folder.
1.html:17 GET http://localhost/example1.kml 404 (Not Found)
(anonymous) @ 1.html:17
leaflet.js:5 Uncaught (in promise) Error: Bounds are not valid.
at e.fitBounds (leaflet.js:5)
at 1.html:28
my code:
`
<script src="http://unpkg.com/[email protected]/dist/leaflet.js"></script>
<script src="/L.KML.js"></script>
map.addLayer(osm);
// Load kml file
fetch('./example1.kml')
.then(res => res.text())
.then(kmltext => {
// Create new kml overlay
const parser = new DOMParser();
const kml = parser.parseFromString(kmltext, 'text/xml');
const track = new L.KML(kml);
map.addLayer(track);
// Adjust map to show the kml
const bounds = track.getBounds();
map.fitBounds(bounds);
});
</script>
</body>
I want to fetch the code for leaflet-kml#1.0.1.
and actually can find it here: https://www.npmjs.com/package/leaflet-kml/v/1.0.1 .
But can not find the download URL for leaflet-kml#1.0.1, could you help this???
I'm working with Angular 7 and leaflet, and I'm trying to display KML layers.
Plugin works fine everywhere but IE11:
The code i'm using is pretty standard, i fetch a kml file, decode it and then I add a layer to the map:
this.mapService.getFileContents(response.data.kml_url).subscribe( contents => {
const baseXml = contents;
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(baseXml, 'text/xml');
const track = new L.KML(xmlDoc, {async: true});
const bounds = track.getBounds();
this.map.fitBounds(bounds);
this.map.addLayer(track);
}
Oddly enough, IE11's console shows nothing at all, so I don't really know where to start looking for errors / issues.
Anyone faced the same behaviour?
Hi,
I got an issue with my marker custom icons being 32px by 37px in size and the anchor being at coordinates : 15,35
Those values are hardcoded in L.KML.js in the definition of L.KMLIcon at values :
iconSize: [32, 32],
iconAnchor: [16, 16],
I made some changes so I can put the size and anchor location in the .kml file and have them changed dynamically to support different markers options.
I don't know if it's the best way to do it, but it works...
Here is what I did :
Line 129 :
var iconOptions = {
iconUrl: ioptions.href,
shadowUrl: null,
anchorRef: {x: ioptions.x, y: ioptions.y},
anchorType: {x: ioptions.xunits, y: ioptions.yunits}
};
Modify like this :
let arrayIconAnchor = [16,16];
let arrayIconSize = [32,32];
if (xml.getAttribute('anchorX')){
arrayIconAnchor[0] = Number(xml.getAttribute('anchorX'));
}
if (xml.getAttribute('anchorY')){
arrayIconAnchor[1] = Number(xml.getAttribute('anchorY'));
if (xml.getAttribute('sizeX')){
arrayIconSize[0] = Number(xml.getAttribute('sizeX'));
}
if (xml.getAttribute('sizeY')){
arrayIconSize[1] = Number(xml.getAttribute('sizeY'));
}
var iconOptions = {
iconUrl: ioptions.href,
shadowUrl: null,
anchorRef: {x: ioptions.x, y: ioptions.y},
anchorType: {x: ioptions.xunits, y: ioptions.yunits},
iconAnchor: arrayIconAnchor,
iconSize: arrayIconSize,
};
Then line 415 :
L.KMLIcon = L.Icon.extend({
options: {
iconSize: [32, 32],
iconAnchor: [16, 16],
},
_setIconStyles: function (img, name) {
L.Icon.prototype._setIconStyles.apply(this, [img, name]);
},
...
Delete the "options" definition so it becomes :
L.KMLIcon = L.Icon.extend({
_setIconStyles: function (img, name) {
L.Icon.prototype._setIconStyles.apply(this, [img, name]);
},
...
In your KML just add the parameters like this :
<Style id='bus.png' anchorX='15' anchorY='35' sizeX='32' sizeY='37'>
<IconStyle>
<Icon>
<href>"+webappUrl+"plugins/images/bus.png</href>
</Icon>
</IconStyle>
</Style>
Hope it helps anyone.
Uncaught TypeError TypeError: Failed to fetch
at (c:\Users*\Desktop*\index.html:17:13)
--- Promise.then ---
at (c:\Users*\Desktop*\kml\index.html:19:18)
@ c:\Users*\Desktop**\kml\index.html:17:13
here is my code
// Load kml file
fetch('https://github.com/fullfocusbtw1/123123123.git')
.then(res => res.text())
.then(kmltext => {
// Create new kml overlay
const parser = new DOMParser();
const kml = parser.parseFromString(kmltext, 'text/xml');
const track = new L.KML(kml);
map.addLayer(track);
// Adjust map to show the kml
const bounds = track.getBounds();
map.fitBounds(bounds);
});
</script>
</body>
There is some control flow like the following:
L.Icon.prototype._setIconStyles.apply(this, [img, name]);
if( img.complete ) {
this.applyCustomStyles( img )
} else {
img.onload = this.applyCustomStyles.bind(this,img)
}
If the img.complete
evaluates to true (the cache is warm) the 'img.height' and 'img.width' are accessed immediately, before the icon is inserted into the DOM with the icon width/height styles applied. So when the cache is warm, the size of the underlying asset is used, instead of the size the icon is resized to.
Potential fix might be to use the 'iconSize' values instead of loading these from the image?
There appears to be no way to edit or include additional options in the layer, such as to add minZoom or maxZoom options for the KML layer. I'm trying to create an option to turn on and off this KML layer, but i'm receiving this error "Control.Layers.js:401 Uncaught TypeError: Cannot read property 'minZoom' of undefined" How do you define the minZoom and maxZoom in the KML?
var map = L.map('map', {
center: [32.66995747013945, -105.59179687498357],
maxZoom: 18,
minZoom: 0,
zoom: 18,
layers: [streets,markers]
});
map.setView([32.66995747013945, -105.59179687498357], 3);
var weather= fetch('weather.kml').then(res => res.text()).then(kmltext => {
// Create new kml overlay
const parser = new DOMParser();
const kml = parser.parseFromString(kmltext, 'text/xml');
kml.minZoom = 1;
const track = new L.KML(kml);
track.minZoom = 1;
map.addLayer(track);
// Adjust map to show the kml
const bounds = track.getBounds();
map.fitBounds(bounds);
});
weather.minZoom = 1;
var baseLayers = {
"Grayscale": darkmap,
"Normal": streets
};
var overlays = {
"Weather": weather,
"Markers":markers,
};
console.log(weather);
console.log(markers);
L.control.layers(baseLayers, overlays).addTo(map);
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.