Openlayers根据您的地图编写并保存KML

use*_*603 7 javascript kml openlayers

是否可以从OpenLayers编写和保存KML?有人知道出口一个例子吗?

cap*_*gon 9

您只能将矢量要素导出到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);
}
Run Code Online (Sandbox Code Playgroud)

UPDATE

为了强制浏览器将KML字符串作为KML文件下载,您需要将该字符串发送回服务器端,以便将其作为要下载的文件返回到浏览器.

你还没有在服务器端指定你正在使用的语言/平台/等等.但这就是我在C#中所做的.

我创建了一个处理程序,它从查询字符串中获取文件名,从textarea表单中获取KML.

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

}
Run Code Online (Sandbox Code Playgroud)

然后从我的JavaScript方面我只是调用它来启动下载:

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();
Run Code Online (Sandbox Code Playgroud)

  • http://stackoverflow.com/questions/3665115/create-a-file-in-memory-for-user-to-download-not-through-server (2认同)