Is it possible to write and save a KML from OpenLayers? Anyone know of an example of exporting one?
            Asked
            
        
        
            Active
            
        
            Viewed 6,683 times
        
    8
            
            
        - 
                    2Here's a similar solution: might help? http://gis.stackexchange.com/questions/17031/openlayers-format-kml-write-style – user1040259 Feb 20 '12 at 16:00
3 Answers
10
            You can export only the vector features to KML.
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);
}
UPDATE
In order to force the browser to download the KML string as a KML file you need to send that string back to the server-side so it can be returned to the browser as a file to download.
You haven't specified what language/platform/etc you are using on the server-side But this is what i did in C#.
I created a handler which takes in a the filename from the querystring and the KML from a textarea form.
KMLDownload.ashx:
<%@ WebHandler Language="C#" Class="KMLDownload" %>
using System;
using System.Web;
public class KMLDownload : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        HttpResponse response = context.Response;
        string kml = context.Request["kml"];
        string filename = context.Request.QueryString["filename"];
        if (String.IsNullOrEmpty(kml))
        {
            context.Response.ContentType = "text/plain";
            context.Response.Write("{\"error\":\"No files recevied\"}");
        }
        else
        {
            if (String.IsNullOrEmpty(filename)){
                filename = "Features_KML.kml";
            }
            // force a download of the kml file.
            response.Clear();
            response.ContentType = "application/kml";
            response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
            response.AddHeader("content-legth", kml.Length.ToString());
            response.Write(kml.ToString());
            response.End();
        }
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}
Then from my javascript side i simply call this to initiate the download:
var filename = "NameofKMLfileI_WANT.kml";
var url = "secure/KMLDownload.ashx";
if (filename) {
    url += "?filename=" + filename;
}
var input = '<TEXTAREA name="kml">' + kml + '</TEXTAREA>';
//send request
jQuery('<form action="' + url + '" method="post">' + input + '</form>').appendTo('body').submit().remove();
 
    
    
        capdragon
        
- 14,565
- 24
- 107
- 153
- 
                    
- 
                    Be specific. Do you want to save to Database, Write to file, or force the browser to initiate a Download of a KML file from the KML string the above function returns? – capdragon Feb 20 '12 at 16:33
- 
                    Thanks for your help. Force the browser to initiate a download of the KML. – user1040259 Feb 20 '12 at 16:36
- 
                    I don't know what you use on your back-end but i've posted the way i do it in .NET. – capdragon Feb 20 '12 at 17:13
- 
                    for some reason I couldn't get this to work.. any chance you have the time to provide a full working example? .net is fine. – user1040259 Mar 01 '12 at 21:40
- 
                    I'm getting ready to go home. I'll see if i can get one for you tomorrow. – capdragon Mar 01 '12 at 21:42
- 
                    I'd love to give you all 220 reputation points of mine for this help. I hope I'm not coming across too pushy – user1040259 Mar 02 '12 at 16:32
- 
                    @user1040259 : [HERE](https://www.cstars.miami.edu/edge/services/downloadkml.html) is a working example. This URL will be taken down on Monday. – capdragon Mar 02 '12 at 18:42
- 
                    1Some code to save without server interaction, for some browsers: http://hackworthy.blogspot.co.nz/2012/05/savedownload-data-generated-in.html – ZiglioUK Nov 29 '12 at 04:22
- 
                    2http://stackoverflow.com/questions/3665115/create-a-file-in-memory-for-user-to-download-not-through-server – Christophe Roussy Aug 07 '13 at 16:01
- 
                    
3
            
            
        Here's some JQuery action to save:
$('#saveKML').click(function() {
 var kmlFormat = new OpenLayers.Format.KML();
 var newWindow = window.open('', 
  'KML Export ' + (new Date()).getTime(), "width=300,height=300");
   newWindow.document.write('<textarea id="kml" style="width: 100%; height: 100%">' + 
   kmlFormat.write(features) + '</textarea>');
});
 
    
    
        user1040259
        
- 6,369
- 13
- 44
- 62
0
            
            
        IF you are using Openlayers 3 or 4, you will find that the syntax of previous (2012) answers does not work anymore.
This does:
        function GetKMLFromFeatures(features) {
            var format = new ol.format.KML();
            var kml = format.writeFeatures(features, {featureProjection: 'EPSG:3857'});
            return kml;
        }
        function GetGeoJSONFromFeatures(features) {
            var format = new ol.format.GeoJSON();
            var geoJSON = format.writeFeatures(features, {featureProjection: 'EPSG:3857'});
            return geoJSON;
        }
        function GetFeaturesFromLayer(layer) {
            var source = layer.getSource();
            var features = source.getFeatures();
            return features;
        }
 
    
    
        tony gil
        
- 9,424
- 6
- 76
- 100
