是否可以从OpenLayers编写和保存KML?有人知道出口一个的例子吗?
答案 0 :(得分: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);
}
为了强制浏览器将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;
}
}
}
然后从我的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();
答案 1 :(得分:3)
以下是一些要保存的JQuery操作:
$('#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>');
});
答案 2 :(得分:0)
如果您使用Openlayers 3或4,您会发现之前(2012)答案的语法不再有效。
这样做:
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;
}