C# KML文件生成

KML(Keyhole Markup Language,Keyhole 标记语言)最初是由Google 旗下的Keyhole 公司开发和维护的一种基于XML 的标记语言,利用XML 语法格式描述地理空间数据(如点、线、面、多边形和模型等),适合网络环境下的地理信息协作与共享。2008 年4月,KML的最新版本2.2 被OGC 宣布为开放地理信息编码标准,并改由OGC 维护和发展。

KML文件可以让你将任意图片,三维模型,柱状图加载到GoogleEarth中。

动态生成KML文件的c#代码如下:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace GBQ.Lidar.AMS.KMLPro
{
    public class kml
    {
        public object lockObj = new object();
        public static Utils.Logger logger = new Utils.Logger("NLog.config");

        [XmlElement("Document")]
        public KmlDocument Document { get; set; }

        public kml()
        {

        }

        public kml(KmlDocument doc)
        {
            this.Document = doc;
        }

        public void GenerateKmlFile(string path, string fileName)
        {
            try
            {

                if (path == null)
                {
                    logger.Info("路径为空,无法创建kml文件");
                    return;
                }
                //判断文件夹是否存在
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                using (var fs = new FileStream(path + "\\" + fileName, FileMode.Create, FileAccess.ReadWrite))
                {
                    using (var sw = new StreamWriter(fs, System.Text.Encoding.UTF8))
                    {
                        XmlSerializer serializer = new XmlSerializer(GetType());
                        serializer.Serialize(sw, this);
                    }
                }
            }
            catch(Exception ex)
            {
                logger.Error("存储KML文件时发生异常.", ex);
            }

        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace GBQ.Lidar.AMS.KMLPro
{
    public class KmlDocument
    {

        [XmlElement("Placemark")]
        public List<KmlPlacemark> PlaceMarkers { get; set; }

        public KmlDocument()
        {
        }

        public KmlDocument( List<KmlPlacemark> folderList)
        {
            PlaceMarkers = folderList;
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GBQ.Lidar.AMS.KMLPro
{
    public class KmlLine
    {
        private List<KmlPoint> _pointList;
        public KmlLine()
        {
            _pointList = new List<KmlPoint>();
        }
        public void Add(KmlPoint point)
        {
            _pointList.Add(point);
        }
        public override string ToString()
        {
            return _pointList.Aggregate(string.Empty, (current, point) => current + (point + " "));
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace GBQ.Lidar.AMS.KMLPro
{
     public class KmlLineString
    {
        [XmlElement("extrude")]
        public string Extrude { get; set; }

        [XmlElement("tessellate")]
        public string Tessellate { get; set; }

        [XmlElement("altitudeMode")]
        public string AltitudeMode { get; set; }

        [XmlElement("coordinates")]
        public string Coordinates { get; set; }

        public KmlLineString()
        {
        }

        public KmlLineString(KmlLine line)
        {
            AltitudeMode = "relativeToGround";
            Coordinates = line.ToString();
            this.Extrude = "1";
            this.Tessellate = "1";
        }

        public KmlLineString(string tessel, KmlLine line)
        {
            AltitudeMode = "relativeToGround";

            Coordinates = line.ToString();

            this.Extrude = "1";
            this.Tessellate = "1";
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace GBQ.Lidar.AMS.KMLPro
{
    public class KmlPlacemark
    {
        [XmlElement("name")]
        public string Name { get; set; }
        [XmlElement("Style")]
        public KmlStyle kmlStyle { get; set; }
        [XmlElement("Polygon")]
        public Polygon polygon { get; set; }
        public KmlPlacemark()
        {

        }
        public KmlPlacemark(string name, KmlStyle kmlStyle,Polygon polygon)
        {
            this.Name = name;
            this.kmlStyle = kmlStyle;
            this.polygon = polygon;
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GBQ.Lidar.AMS.KMLPro
{
    public class KmlPoint
    {
        public double B;
        public double L;
        public double H;
        public DateTime time;

        public KmlPoint()
        {
        }

        public KmlPoint(double b, double l, double h)
        {
            B = l;
            L = b;
            H = h;
            time = DateTime.Now;
        }
        public KmlPoint(double b, double l, double h, DateTime time)
        {
            B = l;
            L = b;
            H = h;
            this.time = time;
        }

        public override string ToString()
        {
            return L.ToString("F6") + "," + B.ToString("F6") + "," + H.ToString("F2");
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace GBQ.Lidar.AMS.KMLPro
{
    public class KmlStyle
    {

        [XmlElement("LineStyle")]
        public KmlLineStyle lineStyle { get; set; }

        [XmlElement("PolyStyle")]
        public KmlPolyStyle polyStyle { get; set; }

        public KmlStyle()
        {
        }

        public KmlStyle( string lineColor, string  lineWidth,string polyColor)
        {
            lineStyle = new KmlLineStyle(lineColor, lineWidth);
            polyStyle = new KmlPolyStyle(polyColor);
        }

        public class KmlLineStyle
        {
            [XmlElement("color")]
            public string Color { get; set; }

            [XmlElement("width")]
            public string Width { get; set; }

            public KmlLineStyle()
            {
            }

            public KmlLineStyle(string color, string width)
            {
                Color = color;
                Width = width;
            }
        }
        public class KmlPolyStyle
        {
            [XmlElement("color")]
            public string Color { get; set; }

            public KmlPolyStyle() { }

            public KmlPolyStyle(string color)
            {
                this.Color = color;
            }

        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace GBQ.Lidar.AMS.KMLPro
{
    public  class KmlStyleMap
    {
        private static readonly string[,] styleTable =
        {
            {"normal", "#green"},
            {"highlight", "#red"}
        };

        [XmlAttribute("id")]
        public string ID { get; set; }
        [XmlElement("Pair")]
        public List<Pair> pairs { get; set; }

        public KmlStyleMap()
        {
        }

        public KmlStyleMap(string id)
        {
            ID = id;
            pairs = GetPairList();
        }

        public static List<Pair> GetPairList()
        {
            List<Pair> rtn = new List<Pair>();
            for (int i = 0; i < styleTable.GetLength(0); i++)
            {
                Pair pair = new Pair(styleTable[i, 0], styleTable[i, 1]);
                rtn.Add(pair);
            }
            return rtn;
        }

        public class Pair
        {
            [XmlElement("key")]
            public string Key { get; set; }

            [XmlElement("styleUrl")]
            public string StyleUrl { get; set; }

            public Pair()
            {
            }

            public Pair(string key, string url)
            {
                Key = key;
                StyleUrl = url;
            }
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace GBQ.Lidar.AMS.KMLPro
{
    public class Polygon
    {
        [XmlElement("extrude")]
        public string extrude { get; set; }
        [XmlElement("altitudeMode")]
        public string altitudeMode { get; set; }
        [XmlElement("outerBoundaryIs")]
        public OuterBoundaryIs outerBoundaryIs { get; set; }
        public Polygon()
        {

        }
        public Polygon(string extrude,string altitudeMode,OuterBoundaryIs outerBoundaryIs)
        {
            this.extrude = extrude;
            this.altitudeMode = altitudeMode;
            this.outerBoundaryIs = outerBoundaryIs;
        }
    }

    public class OuterBoundaryIs
    {
        [XmlElement("LinearRing")]
        public LinearRing linearRing { get; set; }

        public OuterBoundaryIs()
        {

        }
        public OuterBoundaryIs(LinearRing linearRing)
        {
            this.linearRing = linearRing;
        }
    }
    public class LinearRing
    {
        [XmlElement("coordinates")]
        public string coordinates { get; set; }
        public LinearRing()
        {

        }
        public LinearRing(string coordinates)
        {
            this.coordinates = coordinates;
        }
    }
}

调用:
调用是直接复制的项目里的方法,没有用的信息可以自动过滤。

        /// <summary>
        /// 生成kml文件
        /// </summary>
        /// <param name="kmlPonts"></param>
        /// <param name="path"></param>
        /// <param name="fileName"></param>
        /// <param name="docName"></param>
        /// <param name="placeMarkName"></param>
        /// <param name="placeMarkDes"></param>
        private void GeneratorKML(List<KmlPoint> kmlPonts, string path, string fileName, string docName, string placeMarkName, string placeMarkDes,double zoom )
        {
            try
            {
                if (kmlPonts.Count <= 0) return;
                List<GBQ.Lidar.AMS.KML3D.KmlPlacemark> kmlPlacemarks = new List<KML3D.KmlPlacemark>();
                for (int i = 0; i < kmlPonts.Count; i++)
                {

                    GBQ.Lidar.AMS.KML3D.KmlLine kmlLine = new KML3D.KmlLine();
                    GBQ.Lidar.AMS.KML3D.KmlPoint kmlPoint = new GBQ.Lidar.AMS.KML3D.KmlPoint(kmlPonts[i].L, kmlPonts[i].B, kmlPonts[i].H * zoom);
                    kmlLine.Add(kmlPoint);
                    GBQ.Lidar.AMS.KML3D.KmlStyle kmlStyle = new KML3D.KmlStyle(GetColor(alpha, maxColorValue, kmlPoint.H, zoom), width);
                    GBQ.Lidar.AMS.KML3D.KmlLineString kmlLineString = new GBQ.Lidar.AMS.KML3D.KmlLineString(kmlLine);
                    GBQ.Lidar.AMS.KML3D.KmlPlacemark kmlPlacemark = new GBQ.Lidar.AMS.KML3D.KmlPlacemark(placeMarkName, placeMarkDes, "#yellowLineGreenPoly", kmlStyle, kmlLineString);
                    kmlPlacemarks.Add(kmlPlacemark);
                }
                List<KML3D.KmlScreenOverlay> screenOverlays = new List<KML3D.KmlScreenOverlay>();
                GBQ.Lidar.AMS.KML3D.KmlDocument kmlDocument = new GBQ.Lidar.AMS.KML3D.KmlDocument(docName, kmlPlacemarks);

                GBQ.Lidar.AMS.KML3D.kml kmlRoot = new GBQ.Lidar.AMS.KML3D.kml(kmlDocument);
                DateTime currentTime = DateTime.Now;
                kmlRoot.GenerateKmlFile(path, fileName);
            }
            catch(Exception ex)
            {
                logger.Error("写入kml文件时发生异常,请注意!");
            }
        }

 生成后的KML文件:

<?xml version="1.0" encoding="utf-8"?>
<kml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <lockObj />
  <Document>
    <Placemark>
      <name>NO2</name>
      <Style>
        <LineStyle>
          <color>ef000000</color>
          <width>0</width>
        </LineStyle>
        <PolyStyle>
          <color>ef000000</color>
        </PolyStyle>
      </Style>
      <Polygon>
        <extrude>1</extrude>
        <altitudeMode>relativeToGround</altitudeMode>
        <outerBoundaryIs>
          <LinearRing>
            <coordinates>117.00189,31.00191,556
117.00295,31.00262,556
</coordinates>
          </LinearRing>
        </outerBoundaryIs>
      </Polygon>
    </Placemark>
    <Placemark>
      <name>NO2</name>
      <Style>
        <LineStyle>
          <color>ef000000</color>
          <width>0</width>
        </LineStyle>
        <PolyStyle>
          <color>ef000000</color>
        </PolyStyle>
      </Style>
      <Polygon>
        <extrude>1</extrude>
        <altitudeMode>relativeToGround</altitudeMode>
        <outerBoundaryIs>
          <LinearRing>
            <coordinates>117.00295,31.00262,556
117.00346,31.004,556
</coordinates>
          </LinearRing>
        </outerBoundaryIs>
      </Polygon>
    </Placemark>
    <Placemark>
      <name>NO2</name>
      <Style>
        <LineStyle>
          <color>ef000000</color>
          <width>0</width>
        </LineStyle>
        <PolyStyle>
          <color>ef000000</color>
        </PolyStyle>
      </Style>
      <Polygon>
        <extrude>1</extrude>
        <altitudeMode>relativeToGround</altitudeMode>
        <outerBoundaryIs>
          <LinearRing>
            <coordinates>117.00346,31.004,556
117.00424,31.00529,556
</coordinates>
          </LinearRing>
        </outerBoundaryIs>
      </Polygon>
    </Placemark>
    <Placemark>
      <name>NO2</name>
      <Style>
        <LineStyle>
          <color>ef000000</color>
          <width>0</width>
        </LineStyle>
        <PolyStyle>
          <color>ef000000</color>
        </PolyStyle>
      </Style>
      <Polygon>
        <extrude>1</extrude>
        <altitudeMode>relativeToGround</altitudeMode>
        <outerBoundaryIs>
          <LinearRing>
            <coordinates>117.00424,31.00529,556
117.00533,31.00576,556
</coordinates>
          </LinearRing>
        </outerBoundaryIs>
      </Polygon>
    </Placemark>
  </Document>
</kml>

使用此方法生成的kml加载到googleEarth中的样式。

原文地址:https://www.cnblogs.com/engyue/p/11159176.html

时间: 2024-11-05 03:11:29

C# KML文件生成的相关文章

C# 程序自动批量生成 google maps 的KML文件

原文:C# 程序自动批量生成 google maps 的KML文件 google maps 的 KML 文件可以用于静态的地图标注,在某些应用中,我们手上往往有成百上千个地址,我们需要把这些地址和描述批量标注到 google maps 上去,如果手工来做,太耗时间,在这里我写了一个程序批量来生成这个 KML 文件. 首先看一下 KML 文件的格式: <?xml version="1.0" encoding="UTF-8"?> <kml xmlns=

过滤器为JSP文件生成静态页面

用过滤器为JSP文件生成静态页面,这只是一个简单的实例,客户端浏览器第一次请求JSP页面时,服务器将生成对应的HTML文件,以后访问同一JSP文件,将转为访问生成的HTML文件.一.过滤器 package com.kenfor.lyb.toHtmlfilter; import java.io.*; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import javax.s

通过ccb(CocosBuilder)文件生成cocos2dx代码

在C++下使用ccb,绑定调用,成员变量,让人头疼又容易犯错. 自己用pythong写了个小程序,通过ccb文件直接生成C++代码 python我用的不多,又是随性所做,代码质量就很差,大家多多包容吧. 一共包括三个文件,codeGen.py, myCommon.py ,genCpp.py 运行codeGen.py. myCommon.py中包括一些配置信息,根据具体项目自己修改 class projectinfo: def __init__(self): self.projectName='F

第三百七十五节,Django+Xadmin打造上线标准的在线教育平台—创建课程机构app,在models.py文件生成3张表,城市表、课程机构表、讲师表

第三百七十五节,Django+Xadmin打造上线标准的在线教育平台-创建课程机构app,在models.py文件生成3张表,城市表.课程机构表.讲师表 创建名称为app_organization的课程机构APP,写数据库操作文件models.py models.py文件 #!/usr/bin/env python # -*- coding:utf-8 -*- from __future__ import unicode_literals from datetime import datetim

第三百七十六节,Django+Xadmin打造上线标准的在线教育平台—创建用户操作app,在models.py文件生成5张表,用户咨询表、课程评论表、用户收藏表、用户消息表、用户学习表

第三百七十六节,Django+Xadmin打造上线标准的在线教育平台-创建用户操作app,在models.py文件生成5张表,用户咨询表.课程评论表.用户收藏表.用户消息表.用户学习表 创建名称为app_operation的用户操作APP,写数据库操作文件models.py models.py文件 #!/usr/bin/env python # -*- coding:utf-8 -*- from __future__ import unicode_literals from datetime i

virtualBox复制以前的虚拟硬盘文件生成新的虚拟机启动后找不到网卡

VirtualBox复制以前的虚拟硬盘文件生成新的虚拟机时重启后一般网卡不能正常使用 使用ifup eth0或service network restart时会报错(CentOS6.X) 原因: 新虚拟的硬件配置与旧虚拟硬盘文件中记录的硬件配置有一定差异,即使所有的硬件选择与之前一样也会出现配置信息不一致(如网卡的MAC地址)的问题 解决方法: 进入 /etc/udev/rules.d目录 修改70-persistent-net.rules文件即可 文件中记录有两个网卡,如果现有只有一个的话可以

Caffe将自己的文件生成lmdb

参考网站: http://www.cnblogs.com/darkknightzh/p/5909121.html (linux下) http://www.mamicode.com/info-detail-1338521.html (windows下) http://www.cnblogs.com/denny402/p/5082341.html (最简单明了的例子) http://www.2cto.com/kf/201607/527860.html (mnist数据格式与lmdb转换代码分析) h

Dump 文件生成与分析

近期两天因为项目的须要,研究了一下Dump文件相关的知识,今天做一个小节(因为研究不久而且第一次写blog,希望网友们看到不要见笑). Dump文件是进程的内存镜像.能够把程序的运行状态通过调试器保存到dump文件里.   Dump文件是用来给驱动程序编写人员调试驱动程序用的,这样的文件必须用专用工具软件打开,比方使用WinDbg打开. 当我们的程序公布出去之后,在客户机上是无法跟踪自己代码的bug的,所以Dump(扩展名是 .dmp)文件对于我们来说特别实用.我们能够通过.dmp文件把出现bu

《Nodejs开发加密货币》之二十六:轻松从Js文件生成UML类图

前言 上一篇<函数式编程入门经典>,罗嗦了很长,很多小伙伴看得云里雾里.这里提供一个实例,让大家切身感受函数式编程的奥妙和趣味.当然,仅仅为了举例而写代码就没有什么意义了,本书提供的例子都是承担了某项任务的具体项目或工具,这个例子自然也不能例外. 本书用到了大量的Uml类图,经常有小伙伴问我用什么工具画的.说实话,前几篇是我个人一点点手工整理的,但后来就感觉在浪费生命,作为程序员,怎么可能容忍这样的事情反复发生.所以,就有了 js2uml(见参考)这个小工具.只不过,当初目的单一,仅仅使用正则