Friday 12 June 2015

How to create a KML file in C#

KML:

KML is a file format used to display geographic data in an Earth browser such as Google Earth, Google Maps, and Google Maps for mobile. KML uses a tag-based structure with nested elements and attributes and is based on the XML standard. All tags are case-sensitive and must appear exactly as they are listed in the KML Reference. The Reference indicates which tags are optional. Within a given element, tags must appear in the order shown in the Reference.

Sample code to create KML file in C#:

Sample cordinate values:
{
"71.5460372,34.0000941",
"71.5460327,34.00009426",
"71.54603299,34.000094272"
"71.5460329,34.000094277",
"71.54603299,34.000094277",
"71.5460329,34.000094279",
"71.54603299,34.000094279",
"71.5460371,34.0000943",
"71.5460372,34.0000943",
"71.5460372,34.00009477",
"71.5460372,34.00009486",
"71.5460371,34.0000956",
"71.5460371,34.0000959",
"71.546037,34.000096",
"71.546037,34.0000969",
"71.5460375,34.0000981",
"71.5460376,34.0000982",
"71.5460378,34.0000986".
"71.546038,34.000099"
}

using System;
using System.Text;
using System.Net;
using System.Xml;
// POST
// Parameters , featureType, cordinateValues
// featureType(either Point OR Polyline)
// cordinateValues(longitude and latitude)
// FileDownload(To dowload a file)

[FileDownload]
        public ActionResult CreateKMLFile(string featureType, string cordinateValues)
        {
            var kml = new XmlTextWriter(HttpContext.Response.OutputStream, Encoding.UTF8);

            //Use indentation for readability
            kml.Formatting = Formatting.Indented;
            kml.Indentation = 3;

            kml.WriteStartDocument();

            kml.WriteStartElement("kml", "http://www.opengis.net/kml/2.2");
            kml.WriteStartElement("Placemark");
            kml.WriteElementString("name", "Title here");
            kml.WriteElementString("description", "Description here");

            kml.WriteStartElement("Style");
            kml.WriteStartElement("LineStyle");
            kml.WriteElementString("color", "ff00ff00");
            kml.WriteElementString("width", "3");
            kml.WriteEndElement(); // <Style>
            kml.WriteEndElement(); // <LineStyle>

            if (featureType == "polyline")
            {
                kml.WriteStartElement("LineString");
            }

            if (featureType == "point")
            {
                kml.WriteStartElement("Point");
            }

            kml.WriteElementString("coordinates", cordinateValues);

            kml.WriteEndElement(); // <polyline>
            kml.WriteEndElement(); // <Placemark>
            kml.WriteEndElement(); // <kml>
            kml.WriteEndDocument();

            kml.Flush();
            kml.Close();

            return File(new UTF8Encoding().GetBytes(kml.ToString()), "application/vnd.google-earth.kml+xml",
                "fileName.kml");
        }

No comments:

Post a Comment