Try to place all the code inside the Process Request.
Initially we retrieve the p_cd
from Query String.
And then will connect to database and get the required gps points.
And then we would be writing kml using XMLTextWriter
.
public void ProcessRequest(HttpContext context)
{
//context.Response.ContentType = "text/plain";
context.Response.ContentType = "application/vnd.google-earth.kml+xml";
string id = context.Request.QueryString["ID"].ToString();
FileName = "KML File";
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ".kml");
Query = "select * from pmis_hh_gpspoints where p_cd='" + id + "' order by p_gps_cd ";
SqlConnection conn = new SqlConnection(conStr);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(Query, conn);
DataSet ds = new DataSet();
da.Fill(ds);
XmlTextWriter kml = new XmlTextWriter(context.Response.OutputStream, System.Text.Encoding.UTF8);
kml.Formatting = Formatting.Indented;
kml.Indentation = 3;
kml.WriteStartDocument();
kml.WriteStartElement("kml", "http://www.opengis.net/kml/2.2"); /*1*/
kml.WriteStartElement("Document"); /*2*/
kml.WriteStartElement("Style"); /*3*/
kml.WriteAttributeString("id", "bsr");
kml.WriteStartElement("LineStyle"); /*4*/
kml.WriteElementString("width", "4");
kml.WriteElementString("color", "ff0000ff");
kml.WriteEndElement(); /*-4-*/
kml.WriteStartElement("PolyStyle"); /*5*/
kml.WriteElementString("color", "51400FF");
kml.WriteEndElement(); /*-5-*/
kml.WriteEndElement(); /*-3-*/
kml.WriteStartElement("Placemark"); /*6*/
kml.WriteElementString("styleUrl", "#bsr");
kml.WriteStartElement("Polygon"); /*7*/
kml.WriteElementString("extrude", "1");
kml.WriteElementString("tessellate", "1");
kml.WriteElementString("altitudeMode", "ALTITUDE_CLAMP_TO_GROUND");
kml.WriteStartElement("outerBoundaryIs"); /*8*/
kml.WriteStartElement("LinearRing"); /*9*/
kml.WriteStartElement("coordinates"); /*10*/
for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
kml.WriteValue("" + ds.Tables[0].Rows[i]["p_longitude"].ToString() + "," + ds.Tables[0].Rows[i]["p_latitude"].ToString() + ",0 ");
}
kml.WriteValue("" + ds.Tables[0].Rows[0]["p_longitude"].ToString() + "," + ds.Tables[0].Rows[0]["p_latitude"].ToString() + ",0 ");
kml.WriteEndElement(); /*-10-*/
kml.WriteEndElement(); /*-9-*/
kml.WriteEndElement(); /*-8-*/
kml.WriteEndElement(); /*-7-*/
kml.WriteEndElement(); /*-6-*/
kml.WriteEndElement(); /*-2-*/
kml.WriteEndElement(); /*-1-*/
kml.WriteEndDocument();
kml.Close();
conn.Close();
}
Refer the handler file with the right parameter, where ever you are trying to show whether it is in grid or any other place...the kml files gets downloaded with the filename mentioned in the code.