Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

styling KML files in c#

I have written webapp in asp.net(C#) which takes coordinates from database and create .KML for which I then put into Google maps and works fine i.e drawing line string but I want to put styles into it i.e. changing place mark styles, colors, size etc. There is no help regarding it on web.

Code:

using SharpKml.Base;
using SharpKml.Dom;
using SharpKml.Engine;


    protected void Button1_Click(object sender, EventArgs e)
    {
        var document = new Document();
        document.Id = "null";
        document.Name = "null";
        LineString linestring = new LineString();
         CoordinateCollection coordinates = new CoordinateCollection();

        SqlConnection sqlcon = new SqlConnection(conStr);
       // String com = "select Latitude, Longitude from Coordinates where IMEI=@txtIMEI";
        SqlCommand sqlcom = new SqlCommand("GetLatLon", sqlcon);
        sqlcom.CommandType = CommandType.StoredProcedure;
        sqlcom.Parameters.Add("@IMEI", SqlDbType.VarChar).Value= TextBox1.Text;

        DataTable dt = new DataTable();
        SqlDataAdapter sda = new SqlDataAdapter(sqlcom);
        sda.Fill(dt);

        try
        {
            sqlcon.Open();
            sqlcom.ExecuteNonQuery();

            foreach (DataRow dr in dt.Rows) 
            {
                double lon = double.Parse(dr["Longitude"].ToString());
                double lat = double.Parse(dr["Latitude"].ToString());
                coordinates.Add(new Vector(lat, lon));
            }

            linestring.Coordinates = coordinates;
            Placemark placemark = new Placemark();
            placemark.Name = "ryan";
            placemark.Geometry = linestring;
            document.AddFeature(placemark);
            var kml = new Kml();
            kml.Feature = document;
            kml.Feature = placemark;
            KmlFile kmlFile = KmlFile.Create(kml, true);
            using (var stream = System.IO.File.OpenWrite("C:/"+"IMEI-"+TextBox1.Text+".kml"))
            {
                kmlFile.Save(stream);
                Response.Write("KML Created");
            }

        }
        catch (Exception exc)
        {
            Response.Write(exc.Message);
        }
        finally 
        {
            sqlcon.Close();
        }
    }
}

output kml:

<?xml version="1.0" encoding="utf-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
  <Placemark>
    <name>ryan</name>
    <LineString>
      <coordinates>9000,11
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</coordinates>
    </LineString>
  </Placemark>
</kml>
like image 928
user3518032 Avatar asked Apr 11 '14 07:04

user3518032


3 Answers

Change like this works for me

  linestring.Coordinates = coordinates;
  Placemark placemark = new Placemark();
  placemark.Name = "ryan";
  placemark.Geometry = linestring;

  // Create Style with id
  SharpKml.Dom.LineStyle lineStyle = new SharpKml.Dom.LineStyle();
  lineStyle.Color = Color32.Parse("ff0000ff");
  lineStyle.Width = 2;

  Style roadStyle = new Style();
  roadStyle.Id = "RoadStyle";
  roadStyle.Line = lineStyle;

  // Add style to document
  document.AddStyle(roadStyle);

  // Specify style for your placemark by url
  placemark.StyleUrl = new Uri("#RoadStyle", UriKind.Relative);

  document.AddFeature(placemark);
like image 174
Bùi Đức Khánh Avatar answered Nov 12 '22 09:11

Bùi Đức Khánh


Modified same by adding altitude to generate yellowLineGreenPoly style as described in KML-Tutorial sample example, here is the code snippet

        var document = new Document();
        document.Id = "null";
        document.Open = true;
        document.Name = "MyDoc";
        LineString linestring = new LineString();
        linestring.AltitudeMode = AltitudeMode.Absolute;
        linestring.Extrude = true;
        linestring.Tessellate = true;
        CoordinateCollection coordinates = new CoordinateCollection();
        foreach (DataRow dr in dt.Rows) 
        {
            double lon = double.Parse(dr["Longitude"].ToString());
            double lat = double.Parse(dr["Latitude"].ToString());
            double alt = pt.alt.Parse(dr["Altitude"].ToString());;
            coordinates.Add(new Vector(lat, lon, alt));
        }

        linestring.Coordinates = coordinates;
        Placemark placemark = new Placemark();
        placemark.Name = filename;
        placemark.Visibility = false;
        placemark.Geometry = linestring;

        SharpKml.Dom.LineStyle lineStyle = new SharpKml.Dom.LineStyle();
        lineStyle.Color = Color32.Parse("7f00ffff");
        lineStyle.Width = 4;

        SharpKml.Dom.PolygonStyle PolyStyle = new SharpKml.Dom.PolygonStyle();
        PolyStyle.Color = Color32.Parse("7f00ff00");

        Style SimpleStyle = new Style();
        SimpleStyle.Id = "yellowLineGreenPoly";
        SimpleStyle.Line = lineStyle;
        SimpleStyle.Polygon = PolyStyle;
        document.AddStyle(SimpleStyle);
        placemark.StyleUrl = new Uri("#yellowLineGreenPoly", UriKind.Relative);

        document.AddFeature(placemark);
        var kml = new Kml();
        kml.Feature = document;
        KmlFile kmlFile = KmlFile.Create(kml, true);
like image 25
Krishna Prasad S Avatar answered Nov 12 '22 10:11

Krishna Prasad S


Based on the previous examples i created a quick working sample with multiple shapes and styles.

enter image description here

var document = new Document();
document.Id = "null";
document.Open = true;
document.Name = "MyDoc";

///Style 1
SharpKml.Dom.LineStyle lineStyle = new SharpKml.Dom.LineStyle();
lineStyle.Color = Color32.Parse("FFE67800");
lineStyle.Width = 12;

SharpKml.Dom.PolygonStyle PolyStyle = new SharpKml.Dom.PolygonStyle();
PolyStyle.Color = Color32.Parse("FFE67800");

SharpKml.Dom.Style SimpleStyle = new SharpKml.Dom.Style();
SimpleStyle.Id = "Style1";
SimpleStyle.Line = lineStyle;
SimpleStyle.Polygon = PolyStyle;
document.AddStyle(SimpleStyle);


//Style 2
SharpKml.Dom.LineStyle lineStyle2 = new SharpKml.Dom.LineStyle();
lineStyle2.Color = Color32.Parse("FF1478F0");
lineStyle2.Width = 12;

SharpKml.Dom.PolygonStyle PolyStyle2 = new SharpKml.Dom.PolygonStyle();
PolyStyle2.Color = Color32.Parse("FF1478F0");

SharpKml.Dom.Style SimpleStyle2 = new SharpKml.Dom.Style();
SimpleStyle2.Id = "Style2";
SimpleStyle2.Line = lineStyle2;
SimpleStyle2.Polygon = PolyStyle2;
document.AddStyle(SimpleStyle2);

///
//Drawing shapes
//
List<di_vector> list = new List<di_vector>();
list.Add(new di_vector { longitude = 49.5993894, latitude = 6.1064789 });
list.Add(new di_vector { longitude = 49.5995181, latitude = 6.1064977 });
list.Add(new di_vector { longitude = 49.5994511, latitude = 6.106491 });
list.Add(new di_vector { longitude = 49.5994398, latitude = 6.1066076 });
list.Add(new di_vector { longitude = 49.5995128, latitude = 6.106617 });
list.Add(new di_vector { longitude = 49.599372, latitude = 6.1065969 });

Placemark placemark = new Placemark();
placemark = CreateLineString(list);
placemark.StyleUrl= new Uri("#Style1", UriKind.Relative);
document.AddFeature(placemark);

list.Clear();
list.Add(new di_vector { longitude = 49.5993645, latitude = 6.1066354 });
list.Add(new di_vector { longitude = 49.5995079, latitude = 6.1067373 });
list.Add(new di_vector { longitude = 49.5993523, latitude = 6.1067722 });
list.Add(new di_vector { longitude = 49.5994314, latitude = 6.1067561 });
list.Add(new di_vector { longitude = 49.5994366, latitude = 6.1066877 });

//Placemark placemark = new Placemark();
placemark = CreateLineString(list);
placemark.StyleUrl = new Uri("#Style2", UriKind.Relative);
document.AddFeature(placemark);

var kml = new Kml();
kml.Feature = document;
KmlFile kmlFile = KmlFile.Create(kml, true);

var serializer = new Serializer();
serializer.Serialize(document);
Console.WriteLine(serializer.Xml);

string output = serializer.Xml.Replace("Document", "kml");

Creation of the LineStrings

/// <summary>
/// Creation of a LineString
/// </summary>
/// <param name="vectors"></param>
/// <param name="_style"></param>
/// <returns></returns>
private Placemark CreateLineString(List<di_vector> vectors)
{
    LineString linestring1 = new LineString();
    linestring1.AltitudeMode = AltitudeMode.Absolute;
    linestring1.Extrude = true;
    linestring1.Tessellate = true;

    CoordinateCollection coordinates = new CoordinateCollection();
    foreach (var item in vectors)
    {
        coordinates.Add(new SharpKml.Base.Vector(item.longitude,item.latitude));
    }

    linestring1.Coordinates = coordinates;

    Placemark placemark = new Placemark();
    placemark.Geometry = linestring1;

    return placemark;
}

The Vector class

/// <summary>
/// vector class
/// </summary>
public class di_vector
{
    public double longitude { get; set; }

    public double latitude { get; set; }
}

The generated output KML

<? xml version="1.0" encoding="utf-8"?>
<kml id = "null" xmlns="http://www.opengis.net/kml/2.2">
    <name>MyDoc</name>
    <open>true</open>
    <Style id = "Style1" >
        < LineStyle >
            < color > 501400dc</color>
            <width>12</width>
        </LineStyle>
        <PolyStyle>
            <color>501400dc</color>
        </PolyStyle>
    </Style>
    <Style id = "Style2" >
        < LineStyle >
            < color > 5014f01e</color>
            <width>12</width>
        </LineStyle>
        <PolyStyle>
            <color>501400dc</color>
        </PolyStyle>
    </Style>
    <Placemark>
        <styleUrl>#Style1</styleUrl>
        <LineString>
            <extrude>true</extrude>
            <tessellate>true</tessellate>
            <altitudeMode>absolute</altitudeMode>
            <coordinates>6.1064788999999999,49.5993894
6.1064977000000003,49.599518099999997
6.1064910000000001,49.599451100000003
6.1066076000000002,49.599439799999999
6.106617,49.599512799999999
6.1065969000000004,49.599372000000002</coordinates>
        </LineString>
    </Placemark>
    <Placemark>
        <styleUrl>#Style2</styleUrl>
        <LineString>
            <extrude>true</extrude>
            <tessellate>true</tessellate>
            <altitudeMode>absolute</altitudeMode>
            <coordinates>6.1066354,49.5993645
6.1067372999999998,49.599507899999999
6.1067722,49.5993523
6.1067561000000001,49.5994314
6.1066877000000002,49.599436599999997</coordinates>
        </LineString>
    </Placemark>
</kml>
like image 1
Yannick Turbang Avatar answered Nov 12 '22 10:11

Yannick Turbang