[GIS] Feature geometry attributes to KML

kmlopenlayers-2

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.

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

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

Best Answer

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;
    placemarkName.appendChild(this.createTextNode(name));

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

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

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

    // 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.

Related Question