能否从OpenLayers编写和保存KML文件?有没有导出的示例?
能否从OpenLayers编写和保存KML文件?有没有导出的示例?
你只能将矢量要素导出到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);
}
为了让浏览器将KML字符串作为KML文件下载,您需要将该字符串发送回服务器端,以便返回给浏览器作为要下载的文件。
您没有说明服务器端使用什么语言/平台等信息,但这是我在C#中所做的。
我创建了一个处理程序,从查询字符串中获取文件名,并从文本区域表单中获取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;
}
}
}
然后从我的 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();
$('#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>');
});
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;
}