I'm using the OpenLayers.Format.KML class to export the features in MyLayer to KML. However my features have attributes attached to the geometry object i would also like to have exported to the KML file. Does anyone know how to do this?

For example below is an excerpt from my exported KML. I want to be able to fill in the Placemark name and description with values from my feature.geometry.attributes object.

 <name>Orders Export</name>
 <description>This KML is a representation of the features that have been exported from your cart.</description>
 <description>No description available</description>
 <coordinates>-87.905322927997,31.501496850947 -87.103099728388,31.3860815117 -87.130858407835,31.283001227822 -87.932252685086,31.398209088023 -87.905322927997,31.501496850947</coordinates>

My code:

var format = new OpenLayers.Format.KML({
    'internalProjection': map.baseLayer.projection,
    'externalProjection': map.Projections.Geographic
format.foldersName = "Orders Export";
format.foldersDesc = "This KML is a representation of the features that have been exported from your cart.";
var kml = format.write(MyLayer.features);
  • look for kml.name – Brad Nesom Jul 18 '11 at 21:45

From the OL source and the format.KML.js createPlacemarkXML() function, here's where the KML name is generated -

 createPlacemarkXML: function(feature) {        
    // Placemark name
    var placemarkName = this.createElementNS(this.kmlns, "name");
    var name = feature.style && feature.style.label ? feature.style.label :
               feature.attributes.name || feature.id;

    // Placemark description
    var placemarkDesc = this.createElementNS(this.kmlns, "description");
    var desc = feature.attributes.description || this.placemarksDesc;

    // Placemark
    var placemarkNode = this.createElementNS(this.kmlns, "Placemark");
    if(feature.fid != null) {
        placemarkNode.setAttribute("id", feature.fid);

    // Geometry node (Point, LineString, etc. nodes)
    var geometryNode = this.buildGeometryNode(feature.geometry);

    // TBD - deal with remaining (non name/description) attributes.
    return placemarkNode;

So make sure you set the feature's feature.style.label or feature.attributes.name depending on feature's style.

Same idea for the description field.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.