如何返回一个KML内容
本文关键字:一个 KML 内容 返回 何返回 | 更新日期: 2023-09-27 18:05:30
我正在尝试烹饪一个连接到我的DB的web api,获取一些地理数据,然后返回一个将由网页消费的KML内容(在google maps iframe/div上显示信息)。
我正在使用sharpKML(我不知道它是否是正确的选择):
public class KmlController : ApiController
{
public HttpResponseMessage Get()
{
Point point = new Point();
point.Coordinate = new Vector(37.42052549, -122.0816695);
Placemark placemark = new Placemark();
placemark.Name = "Somewhere";
placemark.Geometry = point;
Kml kml = new Kml();
kml.Feature = placemark;
return Request.CreateResponse(HttpStatusCode.OK, kml, new XmlMediaTypeFormatter(), "application/vnd.google-earth.kml+xml");
}
}
但是当我调用http://something.on.my.lan/api/kml时,我得到了这个异常:
系统。InvalidOperationException:'ObjectContent ' 1'类型未能序列化内容类型'application/vnd.google-earth.kml+xml '的响应体;charset = utf - 8"。
我错过了什么?
<解决方案/strong>
不幸的是,正如这个答案中所说,即使我设法动态地创建了一个KML内容,它也不会显示在地图上,因为URL必须由Google公开访问(出于缓存目的)。我必须改变方法
先试试这个,我想知道是否有任何对象的序列化问题:
private string SerializeObject<T>(this T toSerialize)
{
XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());
StringWriter textWriter = new StringWriter();
xmlSerializer.Serialize(textWriter, toSerialize);
return textWriter.ToString();
}
public class KmlController : ApiController
{
public string Get()
{
Point point = new Point();
point.Coordinate = new Vector(37.42052549, -122.0816695);
Placemark placemark = new Placemark();
placemark.Name = "Somewhere";
placemark.Geometry = point;
Kml kml = new Kml();
kml.Feature = placemark;
return SerializeObject<Kml>(kml);;
}
}
如果失败,我建议您参考序列化文档,以便您可以找到哪个对象没有正确序列化。
http://msdn.microsoft.com/en-us/library/system.serializableattribute.aspx这是为我工作…
public static byte[] SerializeKml(this KmlFile kml)
{
var serializer = new Serializer();
serializer.Serialize(kml.Root);
var str = serializer.Xml;
var bytes = new byte[str.Length * sizeof(char)];
Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
public ActionResult GetKml()
{
Placemark placemark = new Placemark
{
Geometry = new Point { Coordinate = new Vector(-13.163959, -72.545992) },
Name = "Machu Picchu",
};
var kml = KmlFile.Create(placemark, false);
var fcResult = new FileContentResult(kml.SerializeKml(), "application/vnd.google-earth.kml+xml") { FileDownloadName = "MachuPicchu.kml" };
return fcResult;
}