Giter Site home page Giter Site logo

leaflet-kml's People

Contributors

aviklai avatar gpsfl avatar gustavo-crt avatar ilblog avatar kant avatar ladis82 avatar mdorda avatar sam152 avatar skydiablo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

leaflet-kml's Issues

KML layer doesn't show

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>

KML Instance requires DOM Element

Hello!

Problem

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.

Suggested Solutions

  • Easy option: update the documentation to demonstrate the required retrieval of the DOM object before creating the KML layer. For example:
         jQuery.get( 'assets/example1.kml' )
           .then( ( kmlDocument ) => {
             var track = new L.KML( kmlDocument, { async: true } )
             this.map.addLayer( track )
           } )
  • Less easy option: update the source code to accept a string, and perform the retrieval on the user's behalf (as in original plugin) to make the documentation valid

Any questions, let me know. Thanks for providing this plugin! :)

Regards,
-- Dan

Overriding Marker Icon

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?

Style empty

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 {

How about search engine?

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

Fillopacity

Hi,

I wanted to see how I can change the fillOpacity, I need to only see the perimeter without filling.

Thanks
Regards

help

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.

Not working at all

I have got a blank map, even when stick to this solution:

#3

Could you roughly show how the code should look?
It would be useful for newbies.

Thanks,

points limit?

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?

Example code not working

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 ?

Balloon does not expand to fit image, placemark shown.

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'>
					
					&apos;Los Tres Miles&apos; rank: 4<BR><BR>
					Mulhacén II lies in Mulhacén's south ridge. It&apos;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...

image

This is what it looks like in Google Earth....

image

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

KML file download all image and not acting as per minLodPixels values

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>

Wrong icon loading

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

Icon Size

#1
Icons are now always [32,32], it could be great if we can set it as option.

kmlLayer = new L.KML( xml , { iconSize : [37,32] } );

#2

For bind popup it could be great if we can add a dedicate css class and not only the "kml-popup"

Thanks for your work on this usefull plugin.

Resolve issues with disappear polygons

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.

TypeError: L.KML is not a constructor

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: '&copy; <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);

getting iconUrl not set in Icon options error when using L.kml

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.

help

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>



<script type="text/javascript">
// Make basemap
const map = new L.Map('map', { center: new L.LatLng(58.4, 43.0), zoom: 11 });
const osm = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');

        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>
`

KML layer doesn't seem to work on IE11

QUESTION:

I'm working with Angular 7 and leaflet, and I'm trying to display KML layers.
Plugin works fine everywhere but IE11:

  • Chrome 76
    Screenshot 2019-08-26 at 11 45 12

  • Safari 12.1
    Screenshot 2019-08-26 at 11 58 01

  • IE11
    Screenshot 2019-08-26 at 11 45 23

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?

Icon size and Marker position are hardcoded

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.

help

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>

Image assets larger than 'iconSize' offset pop-up windows incorrectly when loaded from a warm cache.

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?

Unable to Customize the KML Layer

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);

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.