Friday, 24 November 2017

javascript - How to create folders when exporting OL to KML


I have this function that export all plotted features on my OpenLayers (2.6) map, by using the OpenLayers.Format.KML as follows:


var featuresToExport = [];

for (var i = 0; i < MAP.__layers.length; i++) {
if (MAP.__layers[i].getVisibility() && MAP.__layers[i].features != null) {
for(var j = 0; j < MAP.__layers[i].features.length; j++){
featuresToExport.push(MAP.__layers[i].features[j]);
}
}
}

var format = new OpenLayers.Format.KML({
'maxDepth':10,

'extractStyles': true,
'extractAttributes': true,
'extractTracks': false,
'internalProjection': MAP.__map.baseLayer.projection,
'externalProjection': new OpenLayers.Projection("EPSG:4326")
});

var kml = format.write(featuresToExport);

That way, all features are put at the same level on the KML. I would like to be able to arrange them in folders, for example for each layer.



How can I do that? The write function always write the complete KML structure, otherwise I could do something like this:


for (var i = 0; i < MAP.__layers.length; i++) {
if (MAP.__layers[i].getVisibility() && MAP.__layers[i].features != null) {
featuresToExport = [];

kml += "Layer " + i + "";

for(var j = 0; j < MAP.__layers[i].features.length; j++){
featuresToExport.push(MAP.__layers[i].features[j]);
}

// write this features
kml += format.write(featuresToExport);
kml += "
";
}
}

Answer



Ok, so in the absence of a better solution, I'll just cut the parts I want and rearrange the hierarchy.


var kml = "";
kml += "My exportSome description";
var layerString = "";


// Write features into a KML string
for (var i = 0; i < MAP.__layers.length; i++) {
if (MAP.__layers[i].getVisibility() && MAP.__layers[i].features != null) {
featuresToExport = [];

kml += "Layer " + i + "";

for(var j = 0; j < MAP.__layers[i].features.length; j++){
featuresToExport.push(MAP.__layers[i].features[j]);

}
// write this features
layerString = format.write(featuresToExport);
kml += layerString.match("<\/description>(.*)<\/Folder>")[1];
kml += "
";
}
}
kml += "
";

Edit: Better than that is to use jQuery.parseXML and work with the DOM objects instead of string.



layerString = format.write(featuresToExport);
layerDOM = $.parseXML(layerString);
layerDOM = $(layerDOM).find("Folder")[0];

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...