[GIS] Openlayers create, edit and save/export to kml

kmlopenlayers-2

I'm trying to create, edit and save a point vector as kml file in an Openlayers app. I have managed the create and edit by adding and empty vector layer and then adding the control

OpenLayers.Control.EditingToolbar("name of the layer")

But how could I save/export this afterwards in kml format? I just need this on the browser side a popup to let me save the file locally not on the server side.

Thanks
Aris

Best Answer

OpenLayers.Format.KML will allow you to get all your features as a KML string.

like so:

Save as string:

function GetKMLFromFeatures(features) {
    var format = new OpenLayers.Format.KML({
        'maxDepth':10,
        'extractStyles':true,
        'internalProjection': map.baseLayer.projection,
        'externalProjection': new OpenLayers.Projection("EPSG:4326")
    });

    return format.write(features);
}

Download the string:

But if what you actually want is to download a KML file of the string, you will face the issue that the KML string already resides on the client's browser so you can't download it because it's already there. To Download it you'll have to send it back to a handler on the server side to return a response with the proper file extension and content type application/kml;

This will initiate a browser download.

Check my more indepth answer on StackOverflow.

Update:

A comment on SO pointed me to a new way of doing this. Though, make sure browser compatibility is appropriate.