Search code examples
javascriptopenlayerskml

How to get a list of all features/polygons from a KML file?


I use this code to load a KML file into OpenLayers:

var kmlLayer =  new OpenLayers.Layer.Vector("KML", {
    projection: map.displayProjection,
    isBaseLayer: false,
    strategies: [new OpenLayers.Strategy.Fixed()],
    protocol: new OpenLayers.Protocol.HTTP({
        url: "mykml.kml",
        format: new OpenLayers.Format.KML({
            extractStyles: true,
            extractAttributes: true,
            maxDepth: 2
        })
    })
});

Now I have to list all names of the polygons included in this file.

Trying console.log(kmlLayer.features) I can see the features but I have no idea how to access them. Please see http://s14.directupload.net/file/d/3148/2et4d7wf_png.htm because I'm not allowed to upload images yet.

How can I get name and description of those features?

Thanks in advance.


Solution

  • I think your problem is that the HTTP call happens asynchronously from your call to

    kmlLayer.features[0]
    

    So it seems empty. The solution would be to access the feature array only after the KML is loaded completely like so:

    kmlLayer.events.register("loadend", kmlLayer, function (e) {
        console.log(kmlLayer.features[0].attributes.name)
        });
    

    wether you use Firefox or Chrome just type into your developer web console kmlLayer.features[0] after you loaded the map and it will tell you that it is in fact not undefined.

    Let me know if this helped!