Пример #1
1
        private void writeKML(string filename)
        {
            Color[] colours = { Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Blue, Color.Indigo, Color.Violet, Color.Pink };

            Document kml = new Document();

            Tour tour = new Tour();
            tour.Name = "First Person View";
            Playlist tourplaylist = new Playlist();

            AddNamespace(kml, "gx", "http://www.google.com/kml/ext/2.2");

            Style style = new Style();
            style.Id = "yellowLineGreenPoly";
            style.Line = new LineStyle(new Color32(HexStringToColor("7f00ffff")), 4);

            PolygonStyle pstyle = new PolygonStyle();
            pstyle.Color = new Color32(HexStringToColor("7f00ff00"));
            style.Polygon = pstyle;

            kml.AddStyle(style);

            // create sub folders
            Folder planes = new Folder();
            planes.Name = "Planes";
            kml.AddFeature(planes);

            // coords for line string
            CoordinateCollection coords = new CoordinateCollection();

            int a = 1;
            int c = -1;
            DateTime lasttime = DateTime.MaxValue;
            DateTime starttime = DateTime.MinValue;
            Color stylecolor = Color.AliceBlue;
            string mode = "";
            if (flightdata.Count > 0)
            {
                mode = flightdata[0].mode;
            }
            foreach (CurrentState cs in flightdata)
            {
                progressBar1.Value = 50 + (int)((float)a / (float)flightdata.Count * 100.0f / 2.0f);
                progressBar1.Refresh();

                if (starttime == DateTime.MinValue)
                {
                    starttime = cs.datetime;
                    lasttime = cs.datetime;
                }

                if (mode != cs.mode || flightdata.Count == a)
                {
                    c++;

                    LineString ls = new LineString();
                    ls.AltitudeMode = SharpKml.Dom.AltitudeMode.Absolute;
                    ls.Extrude = true;

                    ls.Coordinates = coords;

                    Placemark pm = new Placemark();

                    pm.Name = c + " Flight Path " + mode;
                    pm.StyleUrl = new Uri("#yellowLineGreenPoly", UriKind.Relative);
                    pm.Geometry = ls;

                    SharpKml.Dom.TimeSpan ts = new SharpKml.Dom.TimeSpan();
                    ts.Begin = starttime;
                    ts.End = cs.datetime;

                    pm.Time = ts;

                    // setup for next line
                    mode = cs.mode;
                    starttime = cs.datetime;

                    stylecolor = colours[c % (colours.Length - 1)];

                    Style style2 = new Style();
                    style2.Line = new LineStyle(new Color32(stylecolor), 4);

                    pm.StyleSelector = style2;

                    kml.AddFeature(pm);

                    coords = new CoordinateCollection();
                }

                coords.Add(new Vector(cs.lat, cs.lng, cs.alt));

                SharpKml.Dom.Timestamp tstamp = new SharpKml.Dom.Timestamp();
                tstamp.When = cs.datetime;

                FlyTo flyto = new FlyTo();

                flyto.Duration = (cs.datetime - lasttime).TotalMilliseconds / 1000.0;

                flyto.Mode = FlyToMode.Smooth;
                SharpKml.Dom.Camera cam = new SharpKml.Dom.Camera();
                cam.AltitudeMode = SharpKml.Dom.AltitudeMode.Absolute;
                cam.Latitude = cs.lat;
                cam.Longitude = cs.lng;
                cam.Altitude = cs.alt;
                cam.Heading = cs.yaw;
                cam.Roll = -cs.roll;
                cam.Tilt = (90 - (cs.pitch * -1));

                cam.GXTimePrimitive = tstamp;

                flyto.View = cam;
                //if (Math.Abs(flyto.Duration.Value) > 0.1)
                {
                    tourplaylist.AddTourPrimitive(flyto);
                    lasttime = cs.datetime;
                }

                Placemark pmplane = new Placemark();
                pmplane.Name = "Plane " + a;

                pmplane.Time = tstamp;

                pmplane.Visibility = false;

                SharpKml.Dom.Location loc = new SharpKml.Dom.Location();
                loc.Latitude = cs.lat;
                loc.Longitude = cs.lng;
                loc.Altitude = cs.alt;

                SharpKml.Dom.Orientation ori = new SharpKml.Dom.Orientation();
                ori.Heading = cs.yaw;
                ori.Roll = -cs.roll;
                ori.Tilt = -cs.pitch;

                SharpKml.Dom.Scale sca = new SharpKml.Dom.Scale();

                sca.X = 2;
                sca.Y = 2;
                sca.Z = 2;

                Model model = new Model();
                model.Location = loc;
                model.Orientation = ori;
                model.AltitudeMode = SharpKml.Dom.AltitudeMode.Absolute;
                model.Scale = sca;

                try
                {
                    Description desc = new Description();
                    desc.Text = @"<![CDATA[
              <table>
                <tr><td>Roll: " + model.Orientation.Roll + @" </td></tr>
                <tr><td>Pitch: " + model.Orientation.Tilt + @" </td></tr>
                <tr><td>Yaw: " + model.Orientation.Heading + @" </td></tr>

              </table>
            ]]>";

                    pmplane.Description = desc;
                }
                catch { }

                Link link = new Link();
                link.Href = new Uri("block_plane_0.dae", UriKind.Relative);

                model.Link = link;

                pmplane.Geometry = model;

                planes.AddFeature(pmplane);

                a++;
            }

            tour.Playlist = tourplaylist;

            kml.AddFeature(tour);

            Serializer serializer = new Serializer();
            serializer.Serialize(kml);

            //Console.WriteLine(serializer.Xml);

            StreamWriter sw = new StreamWriter(filename);
            sw.Write(serializer.Xml);
            sw.Close();

            // create kmz - aka zip file

            FileStream fs = File.Open(filename.Replace(Path.GetExtension(filename), ".kmz"), FileMode.Create);
            ZipOutputStream zipStream = new ZipOutputStream(fs);
            zipStream.SetLevel(9); //0-9, 9 being the highest level of compression
            zipStream.UseZip64 = UseZip64.Off; // older zipfile

            // entry 1
            string entryName = ZipEntry.CleanName(Path.GetFileName(filename)); // Removes drive from name and fixes slash direction
            ZipEntry newEntry = new ZipEntry(entryName);
            newEntry.DateTime = DateTime.Now;

            zipStream.PutNextEntry(newEntry);

            // Zip the file in buffered chunks
            // the "using" will close the stream even if an exception occurs
            byte[] buffer = new byte[4096];
            using (FileStream streamReader = File.Open(filename,FileMode.Open,FileAccess.Read,FileShare.ReadWrite))
            {
                StreamUtils.Copy(streamReader, zipStream, buffer);
            }
            zipStream.CloseEntry();

            filename = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + "block_plane_0.dae";

            // entry 2
            entryName = ZipEntry.CleanName(Path.GetFileName(filename)); // Removes drive from name and fixes slash direction
            newEntry = new ZipEntry(entryName);
            newEntry.DateTime = DateTime.Now;

            zipStream.PutNextEntry(newEntry);

            // Zip the file in buffered chunks
            // the "using" will close the stream even if an exception occurs
            buffer = new byte[4096];
            using (FileStream streamReader = File.OpenRead(filename))
            {
                StreamUtils.Copy(streamReader, zipStream, buffer);
            }
            zipStream.CloseEntry();

            zipStream.IsStreamOwner = true;	// Makes the Close also Close the underlying stream
            zipStream.Close();

            File.Delete(filename);

            flightdata.Clear();
        }
Пример #2
0
        public void AddLine(Line lineIn, Dictionary <string, string> dicData)
        {
            var colorLine = sb.Color32.Parse(ConvertColor(sb.Color32.Parse(lineIn.Color), lineIn.Opacity));
            var style     = new sd.Style
            {
                Line = new sd.LineStyle
                {
                    Color = colorLine,
                    Width = lineIn.Width,
                }
            };
            var line = new sd.LineString
            {
                Extrude     = true,
                Tessellate  = true,
                Coordinates = lineIn.Vectors
            };

            var placemark = new sd.Placemark
            {
                Name         = lineIn.Name,
                Geometry     = line,
                ExtendedData = ExtendedData(dicData)
            };

            placemark.AddStyle(style);

            Document.AddFeature(placemark);
        }
Пример #3
0
        public static void Run()
        {
            // Create the style first
            var style = new Style();
            style.Id = "randomColorIcon";
            style.Icon = new IconStyle();
            style.Icon.Color = new Color32(255, 0, 255, 0);
            style.Icon.ColorMode = ColorMode.Random;
            style.Icon.Icon = new IconStyle.IconLink(new Uri("http://maps.google.com/mapfiles/kml/pal3/icon21.png"));
            style.Icon.Scale = 1.1;

            // Now create the object to apply the style to
            var placemark = new Placemark();
            placemark.Name = "IconStyle.kml";
            placemark.StyleUrl = new Uri("#randomColorIcon", UriKind.Relative);
            placemark.Geometry = new Point
            {
                Coordinate = new Vector(37.831145, -122.36868)
            };

            // Package it all together...
            var document = new Document();
            document.AddFeature(placemark);
            document.AddStyle(style);

            // And display the result
            var serializer = new Serializer();
            serializer.Serialize(document);
            Console.WriteLine(serializer.Xml);
        }
Пример #4
0
 void StylesInDoc(List <StyleDoc> styleDocs)
 {
     foreach (var style in styleDocs)
     {
         var styleDoc = new sd.Style();
         styleDoc.Id        = style.Id;
         styleDoc.Icon      = new sd.IconStyle();
         styleDoc.Icon.Icon = new sd.IconStyle.IconLink(new Uri(style.HrefPoint));
         Document.AddStyle(styleDoc);
     }
 }
Пример #5
0
 void StylesInDoc(List <StyleDoc> styleDocs)
 {
     foreach (var style in styleDocs)
     {
         var styleDoc = new sd.Style();
         styleDoc.Id        = style.Id;
         styleDoc.Icon      = new sd.IconStyle();
         styleDoc.Icon.Icon = new sd.IconStyle.IconLink(new Uri(style.HrefPoint, UriKind.Relative));
         styleDoc.Label     = new sd.LabelStyle
         {
             Scale = 0
         };
         Document.AddStyle(styleDoc);
     }
 }
Пример #6
0
        public void AddMarkerToContainer(Coord.Vector place, Container container, int number)
        {
            SharpKml.Dom.Style style = new SharpKml.Dom.Style();
            style.Id        = "MarkerStyle" + number.ToString();
            style.Icon      = new IconStyle();
            style.Icon.Icon = new IconStyle.IconLink(new Uri("http://maps.google.com/mapfiles/kml/paddle/red-circle.png"));

            Placemark placemark = new Placemark();

            placemark.StyleUrl = new Uri("MarkerStyle" + number.ToString(), UriKind.Relative);
            placemark.Geometry = new SharpKml.Dom.Point()
            {
                Coordinate = place
            };

            container.AddFeature(placemark);
            container.AddStyle(style);
        }
Пример #7
0
        public void AddPoligon(Polygon poly, Dictionary <string, string> dicData)
        {
            var colorPoly = sb.Color32.Parse(ConvertColor(sb.Color32.Parse(poly.ColorPoly), poly.OpacityPoly));
            var colorLine = sb.Color32.Parse(ConvertColor(sb.Color32.Parse(poly.ColorLine), poly.OpacityLine));
            var style     = new sd.Style
            {
                Polygon = new sd.PolygonStyle
                {
                    Fill    = true,
                    Color   = colorPoly,
                    Outline = true
                },
                Line = new sd.LineStyle
                {
                    Color = colorLine,
                    Width = poly.WidthLine,
                }
            };
            var polygon = new sd.Polygon
            {
                Extrude       = true,
                Tessellate    = true,
                OuterBoundary = new sd.OuterBoundary
                {
                    LinearRing = new sd.LinearRing
                    {
                        Coordinates = poly.OuterBoundaryIs
                    }
                }
            };

            var placemark = new sd.Placemark
            {
                Name         = poly.Name,
                Geometry     = polygon,
                ExtendedData = ExtendedData(dicData)
            };

            placemark.AddStyle(style);

            Document.AddFeature(placemark);
        }
Пример #8
0
        public static Style FindStyleByStyleURL(KmlFile kmlFile, string styleUrl)
        {
            SharpKml.Dom.Style style = null;
            if (!String.IsNullOrEmpty(styleUrl))
            {
                if (styleUrl.StartsWith("#"))
                {
                    styleUrl = styleUrl.Substring(1);
                }

                SharpKml.Dom.StyleSelector styleSelector = kmlFile.Styles.FirstOrDefault(s => s.Id == styleUrl);
                if (styleSelector != null && styleSelector is StyleMapCollection)
                {
                    StyleMapCollection styleMapCollection = styleSelector as StyleMapCollection;
                    styleMapCollection.ToList().ForEach(element =>
                    {
                        if (element is Pair)
                        {
                            Pair pair = element as Pair;
                            if (pair.State != null && pair.State == StyleState.Highlight)
                            {
                                string styleUrl2 = pair.StyleUrl.OriginalString;
                                if (!String.IsNullOrEmpty(styleUrl2))
                                {
                                    if (styleUrl2.StartsWith("#"))
                                    {
                                        styleUrl2 = styleUrl2.Substring(1);
                                    }
                                    SharpKml.Dom.StyleSelector styleSelector2 = kmlFile.Styles.FirstOrDefault(s => s.Id == styleUrl2);
                                    if (styleSelector2 != null && styleSelector2 is SharpKml.Dom.Style)
                                    {
                                        style = styleSelector2 as SharpKml.Dom.Style;
                                    }
                                }
                            }
                        }
                    });
                }
            }
            return(style);
        }
Пример #9
0
        public void AddSingleLineToContainer(Coord.Vector start, Coord.Vector end, byte color, Container container, int number)
        {
            SharpKml.Dom.Style style = new SharpKml.Dom.Style();

            style.Id         = "LineStyle" + number.ToString();
            style.Line       = new LineStyle();
            style.Line.Color = new Coord.Color32(255, 0, (byte)(255 - color), color);
            style.Line.Width = 3;

            Placemark placemark = new Placemark();

            placemark.StyleUrl = new Uri("LineStyle" + number.ToString(), UriKind.Relative);

            LineString lineString = new LineString();

            lineString.Coordinates = new CoordinateCollection();
            lineString.Coordinates.Add(start);
            lineString.Coordinates.Add(end);

            placemark.Geometry = lineString;
            container.AddFeature(placemark);
            container.AddStyle(style);
        }
Пример #10
0
        public ActionResult Refresh()
        {
            IEnumerable<Prospect> prospectList = _prospectSerivce.getList();
            int counter = 0;
            Document document = new Document();

            // get lat and long for each prospect
            foreach (Prospect prospect in prospectList)
            {
                // some api's will only allow x calls per second this sleeper helps to space out the calls made to the web service
                counter = counter + 1;
                if (counter % 10 == 0)
                {
                    System.Diagnostics.Debug.WriteLine("Sleeping" + counter);
                    System.Threading.Thread.Sleep(5000);
                }

                String responseFromServer = _prospectSerivce.makePrepData(prospect);
                KmlPrepData kmlPrepData = new KmlPrepData();
                //System.Diagnostics.Debug.WriteLine(responseFromServer);
                kmlPrepData = _kmlPrepDataService.convertAddress(responseFromServer);

                // update lat long to the database
                _prospectSerivce.updateProspect(prospect);
            }

            //run stored procedure to update db
            IEnumerable<JoinedProspect> joinedPospects = _joinedProspectService.getList();

            // get results
            //create styles for placemarkers
            var doNotContactStyle = new Style();
            doNotContactStyle.Id = "doNoContact";
            doNotContactStyle.Icon = new IconStyle();
            doNotContactStyle.Icon.Color = new Color32(255, 0, 255, 0);
            doNotContactStyle.Icon.ColorMode = ColorMode.Normal;
            doNotContactStyle.Icon.Icon = new IconStyle.IconLink(new Uri("http://maps.google.com/mapfiles/kml/pal3/icon47.png"));
            doNotContactStyle.Icon.Scale = 1.1;

            var currentCustomerStyle = new Style();
            currentCustomerStyle.Id = "currentCustomer";
            currentCustomerStyle.Icon = new IconStyle();
            currentCustomerStyle.Icon.Color = new Color32(255, 0, 255, 0);
            currentCustomerStyle.Icon.ColorMode = ColorMode.Normal;
            currentCustomerStyle.Icon.Icon = new IconStyle.IconLink(new Uri("http://maps.google.com/mapfiles/kml/pal3/icon23.png"));
            currentCustomerStyle.Icon.Scale = 1.1;

            var cancelledCustomerStyle = new Style();
            cancelledCustomerStyle.Id = "cancelledCustomer";
            cancelledCustomerStyle.Icon = new IconStyle();
            cancelledCustomerStyle.Icon.Color = new Color32(255, 0, 255, 0);
            cancelledCustomerStyle.Icon.ColorMode = ColorMode.Normal;
            cancelledCustomerStyle.Icon.Icon = new IconStyle.IconLink(new Uri("http://maps.google.com/mapfiles/kml/pal3/icon51.png"));
            cancelledCustomerStyle.Icon.Scale = 1.1;
            //add results to document
            foreach (JoinedProspect jp in joinedPospects)
            {
                // loop through and add information to kmldocument
                KmlPrepData kmlPrepData = new KmlPrepData();
                _kmlDocumentService.addElementToKmlDocument(jp, document);

            }

            document.AddStyle(doNotContactStyle);
            document.AddStyle(currentCustomerStyle);
            document.AddStyle(cancelledCustomerStyle);

            //var serializer = new Serializer();
            //serializer.Serialize(document);
            //System.Diagnostics.Debug.WriteLine(serializer.Xml);

            _kmlDocumentService.saveKmlDocument(document);
            return View();
        }
Пример #11
0
        protected void GenerateKml()
        {
            var id = Convert.ToInt32(Server.HtmlEncode(Request.QueryString["Code"]));
            var document = new Document();
            document.Id = "Document";
            document.Name = "Document";

            Description dsc = new Description();
            dsc.Text = @"<h1>Car's Tracking</h1> ";

            CoordinateCollection coordinates = new CoordinateCollection();

            DataTable dt = new DataTable();

            try
            {
                DataSet ds = FieldAreaViewMethof.getfieldAreaValue(id);
                dt = ds.Tables[0];

                string isreference = ds.Tables[0].Rows[0]["isReferencePoint"].ToString();
                if (isreference == "True")
                {
                    dt.Rows[0].Delete();
                }

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

                OuterBoundary outerBoundary = new OuterBoundary();
                outerBoundary.LinearRing = new LinearRing();
                outerBoundary.LinearRing.Coordinates = coordinates;

                // Polygon Setting:
                Polygon polygon = new Polygon();
                polygon.Extrude = true;
                polygon.AltitudeMode = AltitudeMode.ClampToGround;
                polygon.OuterBoundary = outerBoundary;

                //Color Style Setting:
                byte byte_Color_R = 150, byte_Color_G = 150, byte_Color_B = 150, byte_Color_A = 100; //you may get your own color by other method
                var style = new SharpKml.Dom.Style();

                style.Polygon = new PolygonStyle();
                style.Polygon.ColorMode = SharpKml.Dom.ColorMode.Normal;
                style.Polygon.Color = new Color32(byte_Color_A, byte_Color_B, byte_Color_G, byte_Color_R);

                //Set the polygon and style to the Placemark:
                Placemark placemark = new Placemark();
                placemark.Name = "Kukrail";
                placemark.Geometry = polygon;
                placemark.AddStyle(style);

                //Finally to the document and save it
                document.AddFeature(placemark);

                var kml = new Kml();
                kml.Feature = document;

                KmlFile kmlFile = KmlFile.Create(kml, true);
                if (File.Exists(Server.MapPath("~") + "MAP.kml"))
                {
                    File.Delete(Server.MapPath("~") + "MAP.kml");
                }
                using (var stream = System.IO.File.OpenWrite(Server.MapPath("~") + "MAP.kml"))
                {
                    kmlFile.Save(stream);
                }

            }
            catch (Exception exc)
            {
                Response.Write(exc.Message);
            }
            finally
            {
            }
        }
Пример #12
0
        public void DoAcceptTcpClientCallback(IAsyncResult ar)
        {
            // Get the listener that handles the client request.
            TcpListener listener = (TcpListener) ar.AsyncState;

            // End the operation and display the received data on  
            // the console.
            using (
                TcpClient client = listener.EndAcceptTcpClient(ar))
            {
                // Signal the calling thread to continue.
                tcpClientConnected.Set();


                try
                {
                    // Get a stream object for reading and writing          
                    log.Info("Accepted Client " + client.Client.RemoteEndPoint.ToString());
                    //client.SendBufferSize = 100 * 1024; // 100kb
                    //client.LingerState.Enabled = true;
                    //client.NoDelay = true;

                    // makesure we have valid image
                    GCSViews.FlightData.myhud.streamjpgenable = true;

                    NetworkStream stream = client.GetStream();

                    // 5 seconds - default for httpd 2.2+
                    stream.ReadTimeout = 5000;

                    goto skipagain;

                    again:
                    log.Info("doing Again");

                    skipagain:

                    var asciiEncoding = new ASCIIEncoding();

                    var request = new byte[1024*4];
                    int len = 0;

                    // handle header
                    try
                    {
                        len = stream.Read(request, 0, request.Length);
                    }
                    catch
                    {
                        return;
                    }

                    string head = System.Text.Encoding.ASCII.GetString(request, 0, len);
                    log.Info(head);

                    int index = head.IndexOf('\n');

                    string url = head.Substring(0, index - 1);
                    //url = url.Replace("\r", "");
                    //url = url.Replace("GET ","");
                    //url = url.Replace(" HTTP/1.0", "");
                    //url = url.Replace(" HTTP/1.1", "");

                    Tracking.AddEvent("HTTPServer", "Get", url, "");
/////////////////////////////////////////////////////////////////
                    if (url.Contains("websocket"))
                    {
                        using (var writer = new StreamWriter(stream, Encoding.Default))
                        {
                            writer.WriteLine("HTTP/1.1 101 WebSocket Protocol Handshake");
                            writer.WriteLine("Upgrade: WebSocket");
                            writer.WriteLine("Connection: Upgrade");
                            writer.WriteLine("WebSocket-Location: ws://localhost:56781/websocket/server");

                            int start = head.IndexOf("Sec-WebSocket-Key:") + 19;
                            int end = head.IndexOf('\r', start);
                            if (end == -1)
                                end = head.IndexOf('\n', start);
                            string accept = ComputeWebSocketHandshakeSecurityHash09(head.Substring(start, end - start));

                            writer.WriteLine("Sec-WebSocket-Accept: " + accept);

                            writer.WriteLine("Server: Mission Planner");

                            writer.WriteLine("");

                            writer.Flush();

                            while (client.Connected)
                            {
                                Thread.Sleep(200);
                                log.Debug(stream.DataAvailable + " " + client.Available);

                                while (client.Available > 0)
                                {
                                    Console.Write(stream.ReadByte());
                                }

                                byte[] packet = new byte[1024];

                                string sendme = MainV2.comPort.MAV.cs.roll + "," + MainV2.comPort.MAV.cs.pitch + "," + MainV2.comPort.MAV.cs.yaw
                                                + "," + MainV2.comPort.MAV.cs.lat + "," + MainV2.comPort.MAV.cs.lng + "," + MainV2.comPort.MAV.cs.alt;

                                packet[0] = 0x81; // fin - binary
                                packet[1] = (byte) sendme.Length;

                                int i = 2;
                                foreach (char ch in sendme)
                                {
                                    packet[i++] = (byte) ch;
                                }

                                stream.Write(packet, 0, i);

                                //break;
                            }
                        }
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.Contains("georefnetwork.kml"))
                    {
                        byte[] buffer = Encoding.ASCII.GetBytes(georefkml);

                        string header =
                            "HTTP/1.1 200 OK\r\nServer: here\r\nKeep-Alive: timeout=15, max=100\r\nConnection: Keep-Alive\r\nCache-Control: no-cache\r\nContent-Type: application/vnd.google-earth.kml+xml\r\nX-Pad: avoid browser bug\r\nContent-Length: " +
                            buffer.Length + "\r\n\r\n";
                        byte[] temp = asciiEncoding.GetBytes(header);
                        stream.Write(temp, 0, temp.Length);

                        stream.Write(buffer, 0, buffer.Length);

                        goto again;

                        //stream.Close();
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.Contains("network.kml"))
                    {
                        SharpKml.Dom.Document kml = new SharpKml.Dom.Document();

                        SharpKml.Dom.Placemark pmplane = new SharpKml.Dom.Placemark();
                        pmplane.Name = "P/Q " + MainV2.comPort.MAV.cs.altasl;

                        pmplane.Visibility = true;

                        SharpKml.Dom.Location loc = new SharpKml.Dom.Location();
                        loc.Latitude = MainV2.comPort.MAV.cs.lat;
                        loc.Longitude = MainV2.comPort.MAV.cs.lng;
                        loc.Altitude = MainV2.comPort.MAV.cs.altasl;

                        if (loc.Altitude < 0)
                            loc.Altitude = 0.01;

                        SharpKml.Dom.Orientation ori = new SharpKml.Dom.Orientation();
                        ori.Heading = MainV2.comPort.MAV.cs.yaw;
                        ori.Roll = -MainV2.comPort.MAV.cs.roll;
                        ori.Tilt = -MainV2.comPort.MAV.cs.pitch;

                        SharpKml.Dom.Scale sca = new SharpKml.Dom.Scale();

                        sca.X = 2;
                        sca.Y = 2;
                        sca.Z = 2;

                        SharpKml.Dom.Model model = new SharpKml.Dom.Model();
                        model.Location = loc;
                        model.Orientation = ori;
                        model.AltitudeMode = SharpKml.Dom.AltitudeMode.Absolute;
                        model.Scale = sca;

                        SharpKml.Dom.Link link = new SharpKml.Dom.Link();
                        link.Href = new Uri("block_plane_0.dae", UriKind.Relative);

                        model.Link = link;

                        pmplane.Geometry = model;

                        SharpKml.Dom.LookAt la = new SharpKml.Dom.LookAt()
                        {
                            Altitude = loc.Altitude.Value,
                            Latitude = loc.Latitude.Value,
                            Longitude = loc.Longitude.Value,
                            Tilt = 80,
                            Heading = MainV2.comPort.MAV.cs.yaw,
                            AltitudeMode = SharpKml.Dom.AltitudeMode.Absolute,
                            Range = 50
                        };

                        if (loc.Latitude.Value != 0 && loc.Longitude.Value != 0)
                        {
                            kml.Viewpoint = la;
                            kml.AddFeature(pmplane);
                        }

                        SharpKml.Dom.CoordinateCollection coords = new SharpKml.Dom.CoordinateCollection();

                        //if (loc.Latitude.Value != 0 && loc.Longitude.Value != 0)
                        {
                            //foreach (var point in MainV2.comPort.MAV.wps.Values)
                            {
                                //    coords.Add(new SharpKml.Base.Vector(point.x, point.y, point.z));
                            }
                        }
                        //else
                        {
                            PointLatLngAlt home = null;
                            // draw track
                            try
                            {
                                foreach (var point in GCSViews.FlightPlanner.instance.fullpointlist)
                                {
                                    if (point.Tag.ToLower().Contains("home"))
                                        home = point;

                                    if (point != null)
                                        coords.Add(new SharpKml.Base.Vector(point.Lat, point.Lng, point.Alt));
                                }
                            }
                            catch
                            {
                            }

                            foreach (var point in GCSViews.FlightPlanner.instance.fullpointlist)
                            {
                                if (point == null)
                                    continue;

                                SharpKml.Dom.Placemark wp = new SharpKml.Dom.Placemark();
                                wp.Name = "WP " + point.Tag + " Alt: " + point.Alt;
                                SharpKml.Dom.Point wppoint = new SharpKml.Dom.Point();
                                var altmode = SharpKml.Dom.AltitudeMode.RelativeToGround;
                                wppoint.AltitudeMode = altmode;
                                wppoint.Coordinate = new Vector()
                                {
                                    Latitude = point.Lat,
                                    Longitude = point.Lng,
                                    Altitude = point.Alt
                                };
                                wp.Geometry = wppoint;
                                kml.AddFeature(wp);
                            }
                        }

                        SharpKml.Dom.LineString ls = new SharpKml.Dom.LineString();
                        ls.AltitudeMode = SharpKml.Dom.AltitudeMode.RelativeToGround;
                        ls.Coordinates = coords;
                        ls.Extrude = false;
                        ls.Tessellate = true;

                        Style style = new Style();
                        style.Id = "yellowLineGreenPoly";
                        style.Line = new LineStyle(new Color32(HexStringToColor("ff00ffff")), 4);

                        Style style2 = new Style();
                        style2.Id = "yellowLineGreenPoly";
                        style2.Line = new LineStyle(new Color32(HexStringToColor("7f00ffff")), 4);

                        // above ground
                        SharpKml.Dom.Placemark pm = new SharpKml.Dom.Placemark()
                        {
                            Geometry = ls,
                            Name = "WPs",
                            StyleSelector = style
                        };

                        kml.AddFeature(pm);

                        // on ground
                        SharpKml.Dom.LineString ls2 = new SharpKml.Dom.LineString();
                        ls2.Coordinates = coords;
                        ls2.Extrude = false;
                        ls2.Tessellate = true;
                        ls2.AltitudeMode = SharpKml.Dom.AltitudeMode.ClampToGround;

                        SharpKml.Dom.Placemark pm2 = new SharpKml.Dom.Placemark()
                        {
                            Geometry = ls2,
                            Name = "onground",
                            StyleSelector = style2
                        };

                        kml.AddFeature(pm2);

                        SharpKml.Base.Serializer serializer = new SharpKml.Base.Serializer();
                        serializer.Serialize(kml);

                        byte[] buffer = Encoding.ASCII.GetBytes(serializer.Xml);

                        string header =
                            "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.google-earth.kml+xml\r\nContent-Length: " +
                            buffer.Length + "\r\n\r\n";
                        byte[] temp = asciiEncoding.GetBytes(header);
                        stream.Write(temp, 0, temp.Length);

                        stream.Write(buffer, 0, buffer.Length);

                        goto again;

                        //stream.Close();
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.Contains("block_plane_0.dae"))
                    {
                        string header = "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\n";
                        byte[] temp = asciiEncoding.GetBytes(header);
                        stream.Write(temp, 0, temp.Length);

                        BinaryReader file =
                            new BinaryReader(File.Open("block_plane_0.dae", FileMode.Open, FileAccess.Read,
                                FileShare.Read));
                        byte[] buffer = new byte[1024];
                        while (file.PeekChar() != -1)
                        {
                            int leng = file.Read(buffer, 0, buffer.Length);

                            stream.Write(buffer, 0, leng);
                        }
                        file.Close();
                        stream.Close();
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.Contains("hud.html"))
                    {
                        string header = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n";
                        byte[] temp = asciiEncoding.GetBytes(header);
                        stream.Write(temp, 0, temp.Length);

                        BinaryReader file =
                            new BinaryReader(File.Open("hud.html", FileMode.Open, FileAccess.Read, FileShare.Read));
                        byte[] buffer = new byte[1024];
                        while (file.PeekChar() != -1)
                        {
                            int leng = file.Read(buffer, 0, buffer.Length);

                            stream.Write(buffer, 0, leng);
                        }
                        file.Close();
                        stream.Close();
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.ToLower().Contains("hud.jpg") || url.ToLower().Contains("map.jpg") ||
                             url.ToLower().Contains("both.jpg"))
                    {
                        refreshmap();

                        string header =
                            "HTTP/1.1 200 OK\r\nContent-Type: multipart/x-mixed-replace;boundary=PLANNER\r\n\r\n--PLANNER\r\n";
                        byte[] temp = asciiEncoding.GetBytes(header);
                        stream.Write(temp, 0, temp.Length);

                        while (client.Connected)
                        {
                            System.Threading.Thread.Sleep(200); // 5hz
                            byte[] data = null;

                            if (url.ToLower().Contains("hud"))
                            {
                                GCSViews.FlightData.myhud.streamjpgenable = true;
                                data = GCSViews.FlightData.myhud.streamjpg.ToArray();
                            }
                            else if (url.ToLower().Contains("map"))
                            {
                                data = GetControlJpegRaw(GCSViews.FlightData.mymap);
                            }
                            else
                            {
                                GCSViews.FlightData.myhud.streamjpgenable = true;
                                Image img1 = Image.FromStream(GCSViews.FlightData.myhud.streamjpg);
                                Image img2 = GetControlJpeg(GCSViews.FlightData.mymap);
                                int bigger = img1.Height > img2.Height ? img1.Height : img2.Height;
                                Image imgout = new Bitmap(img1.Width + img2.Width, bigger);

                                Graphics grap = Graphics.FromImage(imgout);

                                grap.DrawImageUnscaled(img1, 0, 0);
                                grap.DrawImageUnscaled(img2, img1.Width, 0);

                                MemoryStream streamjpg = new MemoryStream();
                                imgout.Save(streamjpg, System.Drawing.Imaging.ImageFormat.Jpeg);
                                data = streamjpg.ToArray();
                            }

                            header = "Content-Type: image/jpeg\r\nContent-Length: " + data.Length + "\r\n\r\n";
                            temp = asciiEncoding.GetBytes(header);
                            stream.Write(temp, 0, temp.Length);

                            stream.Write(data, 0, data.Length);

                            header = "\r\n--PLANNER\r\n";
                            temp = asciiEncoding.GetBytes(header);
                            stream.Write(temp, 0, temp.Length);
                        }
                        GCSViews.FlightData.myhud.streamjpgenable = false;
                        stream.Close();
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.Contains("/guided?"))
                    {
                        //http://127.0.0.1:56781/guided?lat=-34&lng=117.8&alt=30

                        Regex rex = new Regex(@"lat=([\-\.0-9]+)&lng=([\-\.0-9]+)&alt=([\.0-9]+)",
                            RegexOptions.IgnoreCase);

                        Match match = rex.Match(url);

                        if (match.Success)
                        {
                            Locationwp gwp = new Locationwp()
                            {
                                lat = double.Parse(match.Groups[1].Value),
                                lng = double.Parse(match.Groups[2].Value),
                                alt = float.Parse(match.Groups[3].Value)
                            };
                            try
                            {
                                MainV2.comPort.setGuidedModeWP(gwp);
                            }
                            catch
                            {
                            }

                            string header = "HTTP/1.1 200 OK\r\n\r\nSent Guide Mode Wp";
                            byte[] temp = asciiEncoding.GetBytes(header);
                            stream.Write(temp, 0, temp.Length);
                        }
                        else
                        {
                            string header = "HTTP/1.1 200 OK\r\n\r\nFailed Guide Mode Wp";
                            byte[] temp = asciiEncoding.GetBytes(header);
                            stream.Write(temp, 0, temp.Length);
                        }
                        stream.Close();
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.ToLower().Contains(".jpg"))
                    {
                        Regex rex = new Regex(@"([^\s]+)\s(.+)\sHTTP/1", RegexOptions.IgnoreCase);

                        Match match = rex.Match(url);

                        if (match.Success)
                        {
                            string fileurl = match.Groups[2].Value;

                            using (Image orig = Image.FromFile(georefimagepath + fileurl))
                            using (Image resi = ResizeImage(orig, new Size(640, 480)))
                            using (MemoryStream memstream = new MemoryStream())
                            {
                                resi.Save(memstream, System.Drawing.Imaging.ImageFormat.Jpeg);

                                memstream.Position = 0;
                                string header =
                                    "HTTP/1.1 200 OK\r\nServer: here\r\nKeep-Alive: timeout=15, max=100\r\nConnection: Keep-Alive\r\nContent-Type: image/jpg\r\nX-Pad: avoid browser bug\r\nContent-Length: " +
                                    memstream.Length + "\r\n\r\n";
                                byte[] temp = asciiEncoding.GetBytes(header);
                                stream.Write(temp, 0, temp.Length);

                                using (BinaryReader file = new BinaryReader(memstream))
                                {
                                    byte[] buffer = new byte[1024];
                                    while (file.BaseStream.Position < file.BaseStream.Length)
                                    {
                                        int leng = file.Read(buffer, 0, buffer.Length);

                                        stream.Write(buffer, 0, leng);
                                    }
                                }
                            }

                            goto again;

                            //stream.Close();
                        }
                        /////////////////////////////////////////////////////////////////
                        else
                        {
                            string header = "HTTP/1.1 404 not found\r\nContent-Type: image/jpg\r\n\r\n";
                            byte[] temp = asciiEncoding.GetBytes(header);
                            stream.Write(temp, 0, temp.Length);
                        }
                        stream.Close();
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.ToLower().Contains("post /guide"))
                    {
                        Regex rex = new Regex(@"lat"":([\-\.0-9]+),""lon"":([\-\.0-9]+),""alt"":([\.0-9]+)",
                            RegexOptions.IgnoreCase);

                        Match match = rex.Match(head);

                        if (match.Success)
                        {
                            Locationwp gwp = new Locationwp()
                            {
                                lat = double.Parse(match.Groups[1].Value),
                                lng = double.Parse(match.Groups[2].Value),
                                alt = float.Parse(match.Groups[3].Value)
                            };
                            try
                            {
                                MainV2.comPort.setGuidedModeWP(gwp);
                            }
                            catch
                            {
                            }

                            string header = "HTTP/1.1 200 OK\r\n\r\nSent Guide Mode Wp";
                            byte[] temp = asciiEncoding.GetBytes(header);
                            stream.Write(temp, 0, temp.Length);
                        }
                        else
                        {
                            string header = "HTTP/1.1 200 OK\r\n\r\nFailed Guide Mode Wp";
                            byte[] temp = asciiEncoding.GetBytes(header);
                            stream.Write(temp, 0, temp.Length);
                        }
                        stream.Close();
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.ToLower().Contains("/command_long"))
                    {
                        string header = "HTTP/1.1 404 not found\r\nContent-Type: image/jpg\r\n\r\n";
                        byte[] temp = asciiEncoding.GetBytes(header);
                        stream.Write(temp, 0, temp.Length);

                        stream.Close();
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.ToLower().Contains("/rcoverride"))
                    {
                        string header = "HTTP/1.1 404 not found\r\nContent-Type: image/jpg\r\n\r\n";
                        byte[] temp = asciiEncoding.GetBytes(header);
                        stream.Write(temp, 0, temp.Length);

                        stream.Close();
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.ToLower().Contains("/get_mission"))
                    {
                        string header = "HTTP/1.1 404 not found\r\nContent-Type: image/jpg\r\n\r\n";
                        byte[] temp = asciiEncoding.GetBytes(header);
                        stream.Write(temp, 0, temp.Length);

                        stream.Close();
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.ToLower().Contains("/mavlink/"))
                    {
                        /*
        GET /mavlink/ATTITUDE+VFR_HUD+NAV_CONTROLLER_OUTPUT+META_WAYPOINT+GPS_RAW_INT+HEARTBEAT+META_LINKQUALITY+GPS_STATUS+STATUSTEXT+SYS_STATUS?_=1355828718540 HTTP/1.1
        Host: ubuntu:9999
        Connection: keep-alive
        X-Requested-With: XMLHttpRequest
        User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11
        Accept: 
        Referer: http://ubuntu:9999/index.html
        Accept-Encoding: gzip,deflate,sdch
        Accept-Language: en-GB,en-US;q=0.8,en;q=0.6
        Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3

        HTTP/1.1 200 OK
        Content-Type: application/json
        Content-Length: 2121
        Date: Thu, 29 Nov 2012 12:13:38 GMT
        Server: ubuntu

        {
        "VFR_HUD": {"msg": {"throttle": 0, "groundspeed": 0.0, "airspeed": 0.0, "climb": 0.0, "mavpackettype": "VFR_HUD", "alt": -0.47999998927116394, "heading": 108}, "index": 687, "time_usec": 0},
        "STATUSTEXT": {"msg": {"mavpackettype": "STATUSTEXT", "severity": 1, "text": "Initialising APM..."}, "index": 2, "time_usec": 0}, 
        "SYS_STATUS": {"msg": {"onboard_control_sensors_present": 4294966287, "load": 0, "battery_remaining": -1, "errors_count4": 0, "drop_rate_comm": 0, "errors_count2": 0, "errors_count3": 0, "errors_comm": 0, "current_battery": -1, "errors_count1": 0, "onboard_control_sensors_health": 4294966287, "mavpackettype": "SYS_STATUS", "onboard_control_sensors_enabled": 4294945807, "voltage_battery": 10080}, "index": 693, "time_usec": 0}, 
        "META_LINKQUALITY": {"msg": {"master_in": 11110, "mav_loss": 0, "mavpackettype": "META_LINKQUALITY", "master_out": 194, "packet_loss": 0.0}, "index": 194, "time_usec": 0},
        "ATTITUDE": {"msg": {"pitchspeed": -0.000976863200776279, "yaw": 1.8878594636917114, "rollspeed": -0.0030046366155147552, "time_boot_ms": 194676, "pitch": -0.09986469894647598, "mavpackettype": "ATTITUDE", "yawspeed": -0.0015030358918011189, "roll": -0.029391441494226456}, "index": 687, "time_usec": 0}, 
        "GPS_RAW_INT": {"msg": {"fix_type": 1, "cog": 0, "epv": 65535, "lon": 0, "time_usec": 0, "eph": 9999, "satellites_visible": 0, "lat": 0, "mavpackettype": "GPS_RAW_INT", "alt": 137000, "vel": 0}, "index": 687, "time_usec": 0}, 
        "HEARTBEAT": {"msg": {"custom_mode": 0, "system_status": 4, "base_mode": 81, "autopilot": 3, "mavpackettype": "HEARTBEAT", "type": 2, "mavlink_version": 3}, "index": 190, "time_usec": 0},
        "GPS_STATUS": {"msg": {"satellite_snr": "", "satellite_azimuth": "", "satellite_prn": "", "satellite_elevation": "", "satellites_visible": 0, "satellite_used": "", "mavpackettype": "GPS_STATUS"}, "index": 2, "time_usec": 0}, 
        "NAV_CONTROLLER_OUTPUT": {"msg": {"wp_dist": 0, "nav_pitch": 0.0, "target_bearing": 0, "nav_roll": 0.0, "aspd_error": 0.0, "alt_error": 0.0, "mavpackettype": "NAV_CONTROLLER_OUTPUT", "xtrack_error": 0.0, "nav_bearing": 0}, "index": 687, "time_usec": 0}}
                      */

                        JavaScriptSerializer serializer = new JavaScriptSerializer();

                        object[] data = new object[20];


                        Messagejson message = new Messagejson();

                        if (MainV2.comPort.MAV.getPacket((byte) MAVLink.MAVLINK_MSG_ID.ATTITUDE) != null)
                            message.ATTITUDE = new Message2()
                            {
                                index = 1,
                                msg =
                                    MainV2.comPort.MAV.getPacket((byte)MAVLink.MAVLINK_MSG_ID.ATTITUDE)
                                        .ToStructure<MAVLink.mavlink_attitude_t>()
                            };
                        if (MainV2.comPort.MAV.getPacket((byte)MAVLink.MAVLINK_MSG_ID.VFR_HUD) != null)
                            message.VFR_HUD = new Message2()
                            {
                                index = 1,
                                msg =
                                    MainV2.comPort.MAV.getPacket((byte)MAVLink.MAVLINK_MSG_ID.VFR_HUD)
                                        .ToStructure<MAVLink.mavlink_vfr_hud_t>()
                            };
                        if (MainV2.comPort.MAV.getPacket((byte)MAVLink.MAVLINK_MSG_ID.NAV_CONTROLLER_OUTPUT) != null)
                            message.NAV_CONTROLLER_OUTPUT = new Message2()
                            {
                                index = 1,
                                msg =
                                    MainV2.comPort.MAV.getPacket((byte)MAVLink.MAVLINK_MSG_ID.NAV_CONTROLLER_OUTPUT)
                                        .ToStructure<MAVLink.mavlink_nav_controller_output_t>()
                            };
                        if (MainV2.comPort.MAV.getPacket((byte)MAVLink.MAVLINK_MSG_ID.GPS_RAW_INT) != null)
                            message.GPS_RAW_INT = new Message2()
                            {
                                index = 1,
                                msg =
                                    MainV2.comPort.MAV.getPacket((byte)MAVLink.MAVLINK_MSG_ID.GPS_RAW_INT)
                                        .ToStructure<MAVLink.mavlink_gps_raw_int_t>()
                            };
                        if (MainV2.comPort.MAV.getPacket((byte) MAVLink.MAVLINK_MSG_ID.HEARTBEAT) != null)
                            message.HEARTBEAT = new Message2()
                            {
                                index = 1,
                                msg =
                                    MainV2.comPort.MAV.getPacket((byte) MAVLink.MAVLINK_MSG_ID.HEARTBEAT)
                                        .ToStructure<MAVLink.mavlink_heartbeat_t>()
                            };
                        if (MainV2.comPort.MAV.getPacket((byte) MAVLink.MAVLINK_MSG_ID.GPS_STATUS) != null)
                            message.GPS_STATUS = new Message2()
                            {
                                index = 1,
                                msg =
                                    MainV2.comPort.MAV.getPacket((byte) MAVLink.MAVLINK_MSG_ID.GPS_STATUS)
                                        .ToStructure<MAVLink.mavlink_gps_status_t>()
                            };
                        if (MainV2.comPort.MAV.getPacket((byte) MAVLink.MAVLINK_MSG_ID.STATUSTEXT) != null)
                            message.STATUSTEXT = new Message2()
                            {
                                index = 1,
                                msg =
                                    MainV2.comPort.MAV.getPacket((byte) MAVLink.MAVLINK_MSG_ID.STATUSTEXT)
                                        .ToStructure<MAVLink.mavlink_statustext_t>()
                            };
                        if (MainV2.comPort.MAV.getPacket((byte) MAVLink.MAVLINK_MSG_ID.SYS_STATUS) != null)
                            message.SYS_STATUS = new Message2()
                            {
                                index = 1,
                                msg =
                                    MainV2.comPort.MAV.getPacket((byte)MAVLink.MAVLINK_MSG_ID.SYS_STATUS)
                                        .ToStructure<MAVLink.mavlink_sys_status_t>()
                            };

                        message.META_LINKQUALITY =
                            message.SYS_STATUS =
                                new Message2()
                                {
                                    index = packetindex,
                                    time_usec = 0,
                                    msg =
                                        new META_LINKQUALITY()
                                        {
                                            master_in = (int) MainV2.comPort.MAV.packetsnotlost,
                                            mavpackettype = "META_LINKQUALITY",
                                            master_out = MainV2.comPort.packetcount,
                                            packet_loss = 100 - MainV2.comPort.MAV.cs.linkqualitygcs,
                                            mav_loss = 0
                                        }
                                };

                        packetindex++;

                        string output = serializer.Serialize(message);

                        string header = "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: " +
                                        output.Length + "\r\n\r\n";
                        byte[] temp = asciiEncoding.GetBytes(header);
                        stream.Write(temp, 0, temp.Length);

                        temp = asciiEncoding.GetBytes(output);
                        stream.Write(temp, 0, temp.Length);

                        goto again;

                        //stream.Close();
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.ToLower().Contains("/mav/"))
                    {
                        //C:\Users\hog\Desktop\DIYDrones\mavelous\modules\lib\mavelous_web


                        Regex rex = new Regex(@"([^\s]+)\s(.+)\sHTTP/1", RegexOptions.IgnoreCase);

                        Match match = rex.Match(url);

                        if (match.Success)
                        {
                            string fileurl = match.Groups[2].Value;

                            fileurl = fileurl.Replace("/mav/", "");

                            if (fileurl == "" || fileurl == "/")
                                fileurl = "index.html";

                            string header = "HTTP/1.1 200 OK\r\n";
                            if (fileurl.Contains(".html"))
                                header += "Content-Type: text/html\r\n\r\n";
                            else if (fileurl.Contains(".js"))
                                header += "Content-Type: application/x-javascript\r\n\r\n";
                            else if (fileurl.Contains(".css"))
                                header += "Content-Type: text/css\r\n\r\n";
                            else
                                header += "Content-Type: text/plain\r\n\r\n";
                            byte[] temp = asciiEncoding.GetBytes(header);
                            stream.Write(temp, 0, temp.Length);


                            BinaryReader file =
                                new BinaryReader(File.Open(mavelous_web + fileurl, FileMode.Open, FileAccess.Read,
                                    FileShare.Read));
                            byte[] buffer = new byte[1024];
                            while (file.BaseStream.Position < file.BaseStream.Length)
                            {
                                int leng = file.Read(buffer, 0, buffer.Length);

                                stream.Write(buffer, 0, leng);
                            }
                            file.Close();
                            stream.Close();
                        }
                        /////////////////////////////////////////////////////////////////
                        else
                        {
                            string header = "HTTP/1.1 404 not found\r\nContent-Type: image/jpg\r\n\r\n";
                            byte[] temp = asciiEncoding.GetBytes(header);
                            stream.Write(temp, 0, temp.Length);

                            stream.Close();
                        }
                    }
                    /////////////////////////////////////////////////////////////////
                    else
                    {
                        Console.WriteLine(url);
                        string header = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n";
                        byte[] temp = asciiEncoding.GetBytes(header);
                        stream.Write(temp, 0, temp.Length);

                        string content = @"
                <a href=/mav/>Mavelous</a>
<a href=/mavlink/>Mavelous traffic</a>
<a href=/hud.jpg>Hud image</a>
<a href=/map.jpg>Map image </a>
<a href=/both.jpg>Map & hud image</a>
<a href=/hud.html>hud html5</a>
<a href=/network.kml>network kml</a>
<a href=/georefnetwork.kml>georef kml</a>

";
                        temp = asciiEncoding.GetBytes(content);
                        stream.Write(temp, 0, temp.Length);
                    }

                    stream.Close();
                    log.Info("Close http " + url);
                }
                catch (Exception ee)
                {
                    log.Error("Failed http ", ee);
                }
            }
        }
Пример #13
0
        /// <summary>
        /// Apply PolyStyle, LineStyle, and/or IconStyle elements of a KML Style to the given VectorStyle.
        /// </summary>
        /// <remarks>
        /// As per KML documentation, in cases where a style element is defined both in a
        /// shared style and in an inline style for a Feature (eg Placemark) the value of
        /// the Feature's inline style takes precedence over the value for the shared style
        /// </remarks>
        /// <param name="vectorStyle">cloned if kmlStyle is not null</param>
        /// <param name="kmlStyle">Style to apply to existing VectorStyle</param>
        private VectorStyle ApplyStyleOverrides(VectorStyle vectorStyle, Style kmlStyle)
        {
            if (kmlStyle == null)
            {
                return(vectorStyle);
            }

            if (kmlStyle.Polygon == null && kmlStyle.Line == null && kmlStyle.Icon == null)
            {
                return(vectorStyle);
            }

            vectorStyle = vectorStyle.Clone();

            if (kmlStyle.Polygon != null)
            {
                // fill
                var fill = kmlStyle.Polygon.Fill.GetValueOrDefault(((SolidBrush)vectorStyle.Fill).Color.A > 0);
                var argb = kmlStyle.Polygon.Color?.Argb ?? ((SolidBrush)vectorStyle.Fill).Color.ToArgb();

                vectorStyle.Fill =
                    fill
                        ? new SolidBrush(Color.FromArgb(argb))
                        : new SolidBrush(Color.Transparent);

                // outline
                vectorStyle.EnableOutline = kmlStyle.Polygon.Outline.GetValueOrDefault(vectorStyle.EnableOutline);

                var width = kmlStyle.Line?.Width ?? vectorStyle.Outline.Width;
                argb = kmlStyle.Line?.Color?.Argb ?? vectorStyle.Outline.Color.ToArgb();

                vectorStyle.Outline = vectorStyle.EnableOutline
                    ? new Pen(Color.FromArgb(argb), (float)width)
                    : new Pen(Color.Transparent);
            }

            if (kmlStyle.Line != null)
            {
                var width = kmlStyle.Line.Width.GetValueOrDefault(vectorStyle.Line.Width);
                var argb  = kmlStyle.Line.Color?.Argb ?? vectorStyle.Line.Color.ToArgb();
                vectorStyle.Line = new Pen(Color.FromArgb(argb), (float)width);
            }

            try
            {
                if (kmlStyle.Icon != null)
                {
                    RasterPointSymbolizer rps = null;

                    if (kmlStyle.Icon.Icon != null && kmlStyle.Icon.Icon.Href != null)
                    {
                        rps = new RasterPointSymbolizer();
                        if (_symbolDict.ContainsKey(kmlStyle.Icon.Icon.Href.ToString()))
                        {
                            rps.Symbol = _symbolDict[kmlStyle.Icon.Icon.Href.ToString()];
                        }
                        else
                        {
                            var newSymbol = GetImageFromUrl(kmlStyle.Icon.Icon.Href);
                            _symbolDict.Add(kmlStyle.Icon.Icon.Href.ToString(), newSymbol);
                            rps.Symbol = newSymbol;
                        }

                        vectorStyle.PointSymbolizer = rps;
                    }

                    if (vectorStyle.PointSymbolizer is RasterPointSymbolizer)
                    {
                        rps = (RasterPointSymbolizer)vectorStyle.PointSymbolizer;

                        var argb = kmlStyle.Icon.Color?.Argb ?? ((SolidBrush)vectorStyle.PointColor).Color.ToArgb();
                        rps.SymbolColor = Color.FromArgb(argb);
                        rps.RemapColor  = Color.White;
                        rps.Scale       = (float)kmlStyle.Icon.Scale.GetValueOrDefault(1);
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.Message);
            }

            return(vectorStyle);
        }
Пример #14
0
        // function that writes out KML file based on the flight chosen by the user
        private void CreateKMLButton_Click(object sender, EventArgs e)
        {
            int    nCount;
            int    nFlightID;
            string sfilename;
            long   lprevTimestamp;

            bLoggingEnabled = false;

            if (FlightPickerLV.SelectedItems.Count < 1)
            {
                MessageBox.Show("Please choose a flight before exporting.", "Export KML File");
                return;
            }

            if (KMLFilePathTBRO.Text.Length == 0)
            {
                MessageBox.Show("Please choose a folder location before exporting.", "Export KML File");
                return;
            }

            nFlightID = (int)FlightPickerLV.SelectedItems[0].Tag;

            // This is the root element of the file
            var    kml        = new Kml();
            Folder mainFolder = new Folder();

            mainFolder.Name        = String.Format("{0} {1}", FlightPickerLV.SelectedItems[0].SubItems[1].Text, FlightPickerLV.SelectedItems[0].SubItems[0].Text);
            mainFolder.Description = new Description
            {
                Text = "Overall Data for the flight"
            };

            kml.Feature = mainFolder;

            // start of Flight Path Line
            var placemarkLine = new Placemark();

            mainFolder.AddFeature(placemarkLine);
            placemarkLine.Name        = "Flight Path Line";
            placemarkLine.Description = new Description
            {
                Text = "Line of the flight"
            };
            var linestring           = new LineString();
            var coordinatecollection = new CoordinateCollection();

            linestring.Coordinates  = coordinatecollection;
            linestring.AltitudeMode = AltitudeMode.Absolute;

            SharpKml.Dom.LineStyle lineStyle = new SharpKml.Dom.LineStyle();
            lineStyle.Color = Color32.Parse("ff0000ff");
            lineStyle.Width = 5;
            Style flightStyle = new Style();

            flightStyle.Id     = "FlightStyle";
            flightStyle.Line   = lineStyle;
            linestring.Extrude = false;
            mainFolder.AddStyle(flightStyle);

            SharpKml.Dom.Style waypointStyle = new SharpKml.Dom.Style();
            waypointStyle.Id        = "WaypointStyle";
            waypointStyle.Icon      = new SharpKml.Dom.IconStyle();
            waypointStyle.Icon.Icon = new SharpKml.Dom.IconStyle.IconLink(new System.Uri("https://maps.google.com/mapfiles/kml/paddle/grn-square.png"));
            mainFolder.AddStyle(waypointStyle);

            SharpKml.Dom.Style pushpinblueStyle = new SharpKml.Dom.Style();
            pushpinblueStyle.Id        = "PushPinBlueStyle";
            pushpinblueStyle.Icon      = new SharpKml.Dom.IconStyle();
            pushpinblueStyle.Icon.Icon = new SharpKml.Dom.IconStyle.IconLink(new System.Uri("https://maps.google.com/mapfiles/kml/pushpin/blue-pushpin.png"));
            mainFolder.AddStyle(pushpinblueStyle);

            SharpKml.Dom.Style pushpingreenStyle = new SharpKml.Dom.Style();
            pushpingreenStyle.Id        = "PushPinGreenStyle";
            pushpingreenStyle.Icon      = new SharpKml.Dom.IconStyle();
            pushpingreenStyle.Icon.Icon = new SharpKml.Dom.IconStyle.IconLink(new System.Uri("https://maps.google.com/mapfiles/kml/pushpin/grn-pushpin.png"));
            mainFolder.AddStyle(pushpingreenStyle);

            placemarkLine.StyleUrl = new Uri("#FlightStyle", UriKind.Relative);

            List <FlightPathData> FlightPath = new List <FlightPathData>();

            FlightPath = FlightPathDB.GetFlightPathData(nFlightID);
            foreach (FlightPathData fpd in FlightPath)
            {
                coordinatecollection.Add(new Vector(fpd.latitude, fpd.longitude, fpd.altitude * 0.3048));
            }
            placemarkLine.Geometry = linestring;

            // start of Flight Plan Waypoints
            List <FlightWaypointData> FlightWaypoints = new List <FlightWaypointData>();

            FlightWaypoints = FlightPathDB.GetFlightWaypoints(nFlightID);
            if (FlightWaypoints.Count > 0)
            {
                Folder FlightPlanFolder = new Folder();

                FlightPlanFolder.Name        = "Flight Plan";
                FlightPlanFolder.Description = new Description
                {
                    Text = "Waypoints along the flight plan"
                };
                mainFolder.AddFeature(FlightPlanFolder);
                foreach (FlightWaypointData waypointData in FlightWaypoints)
                {
                    var placemarkPoint = new Placemark();

                    placemarkPoint.Name     = waypointData.gps_wp_name;
                    placemarkPoint.StyleUrl = new System.Uri("#WaypointStyle", UriKind.Relative);
                    placemarkPoint.Geometry = new SharpKml.Dom.Point
                    {
                        Coordinate   = new Vector(waypointData.gps_wp_latitude, waypointData.gps_wp_longitude, (double)waypointData.gps_wp_altitude * 0.3048),
                        AltitudeMode = AltitudeMode.Absolute
                    };
                    placemarkPoint.Description = new Description
                    {
                        Text = String.Concat(String.Format("Coordinates ({0:0.0000}, {1:0.0000}, {2} feet)", waypointData.gps_wp_longitude, waypointData.gps_wp_latitude, waypointData.gps_wp_altitude))
                    };
                    FlightPlanFolder.AddFeature(placemarkPoint);
                }
            }

            // start of Flight Data Points
            Folder DataPointsfolder = new Folder();

            DataPointsfolder.Name        = "Flight Path Data Points";
            DataPointsfolder.Visibility  = false;
            DataPointsfolder.Description = new Description
            {
                Text = "Data Points along the flight path"
            };
            mainFolder.AddFeature(DataPointsfolder);

            nCount = 0;
            foreach (FlightPathData fpd in FlightPath)
            {
                var    placemarkPoint = new Placemark();
                string descriptioncard;
                bool   bAnyLightsOn = false;

                nCount++;
                // if Google Earth App then you need to turn off visibility on each data point also
                if (GoogleEarthAppRB.Checked == true)
                {
                    placemarkPoint.Visibility = false;
                }
                placemarkPoint.Name = String.Concat("Flight Data Point ", nCount.ToString());
                placemarkPoint.Id   = nCount.ToString();
                descriptioncard     = String.Concat("<br>Timestamp = ", new DateTime(fpd.timestamp).ToString());

                descriptioncard += String.Concat(String.Format("<br><br>Coordinates ({0:0.0000}, {1:0.0000}, {2} feet)", fpd.latitude, fpd.longitude, fpd.altitude));
                descriptioncard += String.Format("<br>Temperature: {0:0.00}C / {1:0.00}F", fpd.ambient_temperature, fpd.ambient_temperature * 9 / 5 + 32);
                descriptioncard += String.Format("<br>Wind: {0:0.00} knts from {1:0.00} degrees", fpd.ambient_wind_velocity, fpd.ambient_wind_direction);
                descriptioncard += String.Format("<br>Altitude Above Ground: {0} feet", fpd.altitudeaboveground);
                if (fpd.sim_on_ground == 1)
                {
                    descriptioncard += String.Format("<br>Plane Is On The Ground");
                }

                descriptioncard += String.Format("<br><br>Heading Indicator: {0:0.00} degrees", fpd.heading_indicator);
                descriptioncard += String.Format("<br>True Heading: {0:0.00} degrees", fpd.plane_heading_true);
                descriptioncard += String.Format("<br>Magnetic Heading {0:0.00} degrees", fpd.plane_heading_magnetic);

                descriptioncard += string.Format("<br><br>Airspeed Indicated: {0:0.00 knts}", fpd.plane_airspeed_indicated);
                descriptioncard += string.Format("<br>Airspeed True: {0:0.00} knts", fpd.airspeed_true);
                descriptioncard += string.Format("<br>Ground Velocity: {0:0.00} knts", fpd.ground_velocity);
                descriptioncard += string.Format("<br>Engine 1: {0} RPM", fpd.Eng1Rpm);
                if (fpd.Eng2Rpm > 0)
                {
                    descriptioncard += string.Format("<br>Engine 2: {0} RPM", fpd.Eng2Rpm);
                }
                if (fpd.Eng3Rpm > 0)
                {
                    descriptioncard += string.Format("<br>Engine 3: {0} RPM", fpd.Eng3Rpm);
                }
                if (fpd.Eng4Rpm > 0)
                {
                    descriptioncard += string.Format("<br>Engine 4: {0} RPM", fpd.Eng4Rpm);
                }

                descriptioncard += string.Format("<br><br>Pitch: {0:0.00} degrees {1}", Math.Abs(fpd.plane_pitch), fpd.plane_pitch < 0 ? "Up" : "Down");
                descriptioncard += string.Format("<br>Bank: {0:0.00} degrees {1}", Math.Abs(fpd.plane_bank), fpd.plane_bank < 0 ? "Right" : "Left");
                descriptioncard += string.Format("<br>Vertical Speed: {0:0} feet per minute", fpd.vertical_speed);
                descriptioncard += string.Concat("<br>Flaps Position: ", fpd.flaps_handle_position);

                descriptioncard += string.Concat("<br><br>Lights On: ");

                // go thru mask and set lights that are on
                if ((fpd.LightsMask & (int)FlightPathData.LightStates.Nav) == (int)FlightPathData.LightStates.Nav)
                {
                    descriptioncard += string.Concat("Nav, ");
                    bAnyLightsOn     = true;
                }
                if ((fpd.LightsMask & (int)FlightPathData.LightStates.Beacon) == (int)FlightPathData.LightStates.Beacon)
                {
                    descriptioncard += string.Concat("Beacon, ");
                    bAnyLightsOn     = true;
                }
                if ((fpd.LightsMask & (int)FlightPathData.LightStates.Landing) == (int)FlightPathData.LightStates.Landing)
                {
                    descriptioncard += string.Concat("Landing, ");
                    bAnyLightsOn     = true;
                }
                if ((fpd.LightsMask & (int)FlightPathData.LightStates.Taxi) == (int)FlightPathData.LightStates.Taxi)
                {
                    descriptioncard += string.Concat("Taxi, ");
                    bAnyLightsOn     = true;
                }
                if ((fpd.LightsMask & (int)FlightPathData.LightStates.Strobe) == (int)FlightPathData.LightStates.Strobe)
                {
                    descriptioncard += string.Concat("Strobe, ");
                    bAnyLightsOn     = true;
                }
                if ((fpd.LightsMask & (int)FlightPathData.LightStates.Panel) == (int)FlightPathData.LightStates.Panel)
                {
                    descriptioncard += string.Concat("Panel, ");
                    bAnyLightsOn     = true;
                }
                // commented out the following lights because most planes don't use them and it messes up the GA aircraft

                /*                if ((fpd.LightsMask & (int)FlightPathData.LightStates.Recognition) == (int)FlightPathData.LightStates.Recognition)
                 *              {
                 *                  descriptioncard += string.Concat("Recognition, ");
                 *                  bAnyLightsOn = true;
                 *              }
                 *              if ((fpd.LightsMask & (int)FlightPathData.LightStates.Wing) == (int)FlightPathData.LightStates.Wing)
                 *              {
                 *                  descriptioncard += string.Concat("Wing, ");
                 *                  bAnyLightsOn = true;
                 *              }
                 *              if ((fpd.LightsMask & (int)FlightPathData.LightStates.Logo) == (int)FlightPathData.LightStates.Logo)
                 *              {
                 *                  descriptioncard += string.Concat("Logo, ");
                 *                  bAnyLightsOn = true;
                 *              }*/
                if ((fpd.LightsMask & (int)FlightPathData.LightStates.Cabin) == (int)FlightPathData.LightStates.Cabin)
                {
                    descriptioncard += string.Concat("Cabin, ");
                    bAnyLightsOn     = true;
                }

                // if there are no masks then put none else remove last two characters which are the comma and the space from above
                if (bAnyLightsOn == false)
                {
                    descriptioncard += string.Concat("None");
                }
                else
                {
                    descriptioncard = descriptioncard.Remove(descriptioncard.Length - 2, 2);
                }

                if (fpd.is_gear_retractable == 1)
                {
                    descriptioncard += String.Concat("<br>Gear Position: ", fpd.gear_handle_position == 1 ? "Down" : "Up");
                }
                if (fpd.spoiler_available == 1)
                {
                    descriptioncard += String.Concat("<br>Spoiler Position: ", fpd.spoilers_handle_position == 1 ? "On" : "Off");
                }
                if (fpd.stall_warning == 1)
                {
                    descriptioncard += "<br>Stall Warning";
                }
                if (fpd.overspeed_warning == 1)
                {
                    descriptioncard += "<br>Overspeed Warning";
                }

                placemarkPoint.Description = new Description
                {
                    Text = descriptioncard
                };

                // turned off showing time with data points as it caused issues of not showing in Google Earth
                // if user turned them off and then back on

                /*                placemarkPoint.Time = new SharpKml.Dom.Timestamp
                 *              {
                 *                  When = new DateTime(fpd.timestamp)
                 *              };*/
                if (fpd.sim_on_ground == 1)
                {
                    placemarkPoint.StyleUrl = new System.Uri("#PushPinGreenStyle", UriKind.Relative);
                }
                else
                {
                    placemarkPoint.StyleUrl = new System.Uri("#PushPinBlueStyle", UriKind.Relative);
                }

                placemarkPoint.Geometry = new SharpKml.Dom.Point
                {
                    Coordinate   = new Vector(fpd.latitude, fpd.longitude, (double)fpd.altitude * 0.3048),
                    AltitudeMode = AltitudeMode.Absolute
                };
                DataPointsfolder.AddFeature(placemarkPoint);
            }

            // add 1st person feature
            SharpKml.Dom.GX.Tour tour = new SharpKml.Dom.GX.Tour();
            tour.Name = "First Person View of Flight";
            kml.AddNamespacePrefix("gx", "http://www.google.com/kml/ext/2.2");
            SharpKml.Dom.GX.Playlist playlist = new SharpKml.Dom.GX.Playlist();
            tour.Playlist = playlist;
            mainFolder.AddFeature(tour);
            lprevTimestamp = 0;
            nCount         = 0;
            foreach (FlightPathData fpd in FlightPath)
            {
                nCount++;
                SharpKml.Dom.GX.FlyTo flyto = new SharpKml.Dom.GX.FlyTo();

                // assume duration will be based on difference between timestamps
                // if first time thru loop and don't have old time or user wants to speed up video playback above threshold
                // then set duration to 1 if it is greater than 1 else leave as-is
                flyto.Duration = (new DateTime(fpd.timestamp) - new DateTime(lprevTimestamp)).TotalMilliseconds / 1000;
                if ((lprevTimestamp == 0) ||
                    (SpeedUpVideoPlaybackCB.Checked == true))
                {
                    if (flyto.Duration > 1)
                    {
                        flyto.Duration = 1;
                    }
                }

                lprevTimestamp = fpd.timestamp;
                flyto.Mode     = SharpKml.Dom.GX.FlyToMode.Smooth;
                SharpKml.Dom.Camera cam = new SharpKml.Dom.Camera();
                cam.AltitudeMode = SharpKml.Dom.AltitudeMode.Absolute;
                cam.Latitude     = fpd.latitude;
                cam.Longitude    = fpd.longitude;
                cam.Altitude     = fpd.altitude * 0.3048;
                cam.Heading      = fpd.plane_heading_true;
                if (GoogleEarthAppRB.Checked == true)
                {
                    cam.Roll = fpd.plane_bank;
                }
                else
                {
                    cam.Roll = fpd.plane_bank * -1;
                }
                cam.Tilt = (90 - fpd.plane_pitch);

                SharpKml.Dom.Timestamp tstamp = new SharpKml.Dom.Timestamp();
                tstamp.When = new DateTime(fpd.timestamp);

                cam.GXTimePrimitive = tstamp;

                flyto.View = cam;
                playlist.AddTourPrimitive(flyto);

                // change it so balloons show during first person view (for potential future use)

                /*
                 * var placemarkPoint = new Placemark();
                 * placemarkPoint.TargetId = nCount.ToString();
                 * placemarkPoint.GXBalloonVisibility = true;
                 * SharpKml.Dom.Update update = new SharpKml.Dom.Update();
                 * update.AddUpdate(new ChangeCollection() { placemarkPoint });
                 * SharpKml.Dom.GX.AnimatedUpdate animatedUpdate = new SharpKml.Dom.GX.AnimatedUpdate();
                 * animatedUpdate.Update = update;
                 * playlist.AddTourPrimitive(animatedUpdate);*/
            }

            // write out KML file
            char[] invalidFileNameChars = Path.GetInvalidFileNameChars();
            sfilename = String.Format("{0}_{1}.kml", FlightPickerLV.SelectedItems[0].SubItems[1].Text, FlightPickerLV.SelectedItems[0].SubItems[0].Text);
            var validfilename = new string(sfilename.Select(ch => invalidFileNameChars.Contains(ch) ? '_' : ch).ToArray());

            sfilename  = string.Concat(KMLFilePathTBRO.Text, "\\");
            sfilename += validfilename;

            System.IO.File.Delete(sfilename);
            KmlFile kmlfile = KmlFile.Create(kml, true);

            using (var stream = System.IO.File.OpenWrite(sfilename))
            {
                kmlfile.Save(stream);
            }
            MessageBox.Show(String.Format("Flight successfully exported to {0}", sfilename), "Export KML File");
        }
Пример #15
0
        TreeViewItem ProcessPlacemark(Placemark placemark)
        {
            string     name = placemark.Name;
            StackPanel pan  = new StackPanel();

            pan.Orientation = System.Windows.Controls.Orientation.Horizontal;

            SharpKml.Dom.Style style = KmlFileHelper.FindStyleByStyleURL(_kmlFile, placemark.StyleUrl.OriginalString);

            if (placemark.Geometry is SharpKml.Dom.Point)
            {
                Uri uri = null;
                if (style != null && style.Icon != null && style.Icon.Icon != null && style.Icon.Icon.Href != null)
                {
                    uri = style.Icon.Icon.Href;
                }

                Image image = new Image();
                image.Height = 16;
                image.Source = _imagesFromUri.FindImageByUri(uri);
                pan.Children.Add(image);
            }
            else if (placemark.Geometry is LineString)
            {
                GeometryGroup Lines = new GeometryGroup();

                Color32 styleColor = new Color32();
                if (style != null && style.Line != null && style.Line.Color != null)
                {
                    styleColor = (Color32)style.Line.Color;
                }

                // Line
                LineGeometry line = new LineGeometry();
                line.StartPoint = new System.Windows.Point(0, 5);
                line.EndPoint   = new System.Windows.Point(10, 5);
                Lines.Children.Add(line);
                GeometryDrawing MyGeometryDrawing = new GeometryDrawing();
                MyGeometryDrawing.Geometry = Lines;
                MyGeometryDrawing.Brush    = new SolidColorBrush(Color.FromArgb(styleColor.Alpha, styleColor.Red, styleColor.Green, styleColor.Blue));
                MyGeometryDrawing.Pen      = new Pen(MyGeometryDrawing.Brush, 1);
                DrawingImage drawingImage = new DrawingImage(MyGeometryDrawing);
                drawingImage.Freeze();
                Image image = new Image();
                image.Height = 16;
                image.Width  = 16;
                image.Source = drawingImage;
                pan.Children.Add(image);
            }

            TextBlock textBlock = new TextBlock();

            textBlock.Text   = name;
            textBlock.Margin = new System.Windows.Thickness(4, 0, 0, 0);
            pan.Children.Add(textBlock);

            KMLFeatureTreeViewItem item = new KMLFeatureTreeViewItem()
            {
                Header  = pan,
                Feature = placemark
            };

            return(item);
        }
Пример #16
0
        public string GetKml()
        {
            var matchId = _currentMatchProvider.GetMatchId();

            SharpKml.Dom.Kml kml = new SharpKml.Dom.Kml();

            var document = new Document();
            kml.Feature = document;

            var c = System.Drawing.ColorTranslator.FromHtml("#33FF33");
            var postStyle = new Style();
            postStyle.Id = "post_vanlig";
            postStyle.Icon = new IconStyle
            {
                Color = new Color32(c.A, c.R, c.G, c.B),
                Icon = new IconStyle.IconLink(new Uri("http://maps.google.com/mapfiles/kml/paddle/wht-blank.png")),
                Scale = 0.5
            };

            document.AddStyle(postStyle);

            var lagFolder = new Folder { Name = "Lag" };
            var postFolder = new Folder { Name = "Poster" };

            document.AddFeature(lagFolder);
            document.AddFeature(postFolder);

            using (var context = _dataContextFactory.Create())
            {
                var match = context.Matcher.Single(x => x.MatchId == matchId);

                var maxLat = match.GeoboxNWLatitude.GetValueOrDefault();
                var minLat = match.GeoboxSELatitude.GetValueOrDefault();
                var minLon = match.GeoboxNWLongitude.GetValueOrDefault();
                var maxLon = match.GeoboxSELongitude.GetValueOrDefault();

                var poster = (from pim in context.PosterIMatch
                              where pim.Match.MatchId == matchId
                              select
                                  new
                                  {
                                      pim.SynligFraTid,
                                      pim.SynligTilTid,
                                      pim.Post.Navn,
                                      pim.Post.Latitude,
                                      pim.Post.Longitude
                                  }).ToList();

                foreach (var p in poster)
                {
                    var placemark = new Placemark();
                    placemark.StyleUrl = new Uri("#post_vanlig", UriKind.Relative);
                    placemark.Time = new TimeSpan { Begin = p.SynligFraTid, End = p.SynligTilTid };
                    placemark.Name = p.Navn;
                    placemark.Geometry = new Point { Coordinate = new Vector(p.Latitude, p.Longitude) };

                    postFolder.AddFeature(placemark);
                }

                var lag = context.Lag.ToList();

                var lagDictionary = new Dictionary<string, Folder>();

                foreach (var lag1 in lag)
                {
                    var color = System.Drawing.ColorTranslator.FromHtml("#" + lag1.Farge);
                    var style = new Style();
                    style.Id = LagStyleKey(lag1.LagId);
                    style.Icon = new IconStyle
                    {
                        Color = new Color32(color.A, color.R, color.G, color.B),
                        Icon = new IconStyle.IconLink(new Uri("http://maps.google.com/mapfiles/kml/paddle/wht-blank-lv.png")),
                        Scale = 0.3
                    };

                    document.AddStyle(style);
                    var folder = new Folder { Name = lag1.Navn };
                    lagDictionary.Add(lag1.LagId, folder);
                    lagFolder.AddFeature(folder);
                }

                var førsteRegistering = (from r in context.PostRegisteringer
                                         select r.RegistertTidspunkt).Min().AddMinutes(-5);

                var avsluttet = (from r in poster
                                    select r.SynligTilTid).Min().AddMinutes(5);

                var deltakerPosisjoner = (from p in context.DeltakerPosisjoner
                                          join d in context.Deltakere on p.DeltakerId equals d.DeltakerId
                                          where førsteRegistering < p.Tidspunkt && p.Tidspunkt < avsluttet
                                          select new
                                          {
                                              p.Latitude,
                                              p.Longitude,
                                              p.DeltakerId,
                                              d.Navn,
                                              d.Lag.Farge,
                                              d.Lag.LagId,
                                              p.Tidspunkt
                                          }).GroupBy(x => x.DeltakerId).ToDictionary(x => x.Key, y => y);

                foreach (var deltaker in deltakerPosisjoner)
                {
                    //if (deltaker.Key != "MS_3-2")

                    //    continue;
                    var førstePosisjon = deltaker.Value.FirstOrDefault();
                    var placemark = new Placemark();
                    placemark.StyleUrl = new Uri("#" + LagStyleKey(førstePosisjon.LagId), UriKind.Relative);
                    placemark.Name = førstePosisjon.Navn;

                    var posisjoner = deltaker.Value.OrderBy(x => x.Tidspunkt).ToList();

                    var track = new Track();

                    var forrigePosisjon = førstePosisjon;
                    foreach (var pos in posisjoner)
                    {
                        // Utafor boksen
                        if (pos.Latitude > maxLat || pos.Latitude < minLat || pos.Longitude > maxLon || pos.Longitude < minLon)
                        {
                            continue;
                        }

                        var meter = DistanseKalkulator.MeterMellom(forrigePosisjon.Latitude, forrigePosisjon.Longitude, pos.Latitude, pos.Longitude);
                        var sekunder = pos.Tidspunkt.Subtract(forrigePosisjon.Tidspunkt).TotalSeconds;

                        if (sekunder > 0)
                        {
                            var fart = meter / sekunder;
                            if (fart > 8.333) // raskere enn 12 blank på 100m
                            {
                                continue;
                            }
                        }

                        track.AddWhen(pos.Tidspunkt);
                        track.AddCoordinate(new Vector(pos.Latitude, pos.Longitude));
                        forrigePosisjon = pos;
                    }

                    placemark.Geometry = track;

                    lagDictionary[førstePosisjon.LagId].AddFeature(placemark);
                }

            }

            Serializer serializer = new Serializer();
            serializer.Serialize(kml);

            return serializer.Xml;
        }
Пример #17
0
        public static Func<ExportContext, SharpKml.Dom.Style> CreateFromSharpmapStyle(IStyle sharpmapStyle)
        {
            if (sharpmapStyle == null)
                throw new ArgumentNullException("sharpmapStyle");

            var vectorStyle = sharpmapStyle as VectorStyle;
            if (vectorStyle == null) return null;

            SharpKml.Dom.Style style = null;

            var install = new Action<ExportContext>(context =>
            {
                style = new SharpKml.Dom.Style
                {
                    Id = sharpmapStyle.GetHashCode().ToString(CultureInfo.InvariantCulture)
                };

                if (vectorStyle.Line != null)
                {
                    var lineStyle = new LineStyle();
                    style.Line = lineStyle;

                    var color = vectorStyle.Line.Color;
                    lineStyle.Color = new Color32(color.A, color.B, color.G, color.R);
                    lineStyle.ColorMode = ColorMode.Normal;
                    lineStyle.Width = vectorStyle.Line.Width;
                }

                var solidColor = ConvertToColor32(vectorStyle.Fill);
                if (solidColor != null)
                {
                    var polygonStyle = new PolygonStyle();
                    style.Polygon = polygonStyle;

                    polygonStyle.Fill = true;
                    polygonStyle.Color = solidColor;
                }

                if (vectorStyle.Symbol == null)
                {
                    if (vectorStyle.PointSize > 0)
                    {
                        var iconStyle = new IconStyle();

                        var pointColor = vectorStyle.PointColor != null
                            ? ConvertToColor32(vectorStyle.PointColor) ?? new Color32(255, 0, 0, 0)
                            : new Color32(255, 0, 0, 0);

                        iconStyle.Color = pointColor;
                        iconStyle.ColorMode = ColorMode.Normal;
                        iconStyle.Icon = new IconStyle.IconLink(Pushpins.ShadedDot);
                        iconStyle.Scale = vectorStyle.PointSize / 6;

                        style.Icon = iconStyle;
                    }
                }
                else
                {
                    var additionalFile = SaveImagetoDisk(vectorStyle.Symbol);
                    Debug.Assert(additionalFile != null, "additionalFile != null");

                    context.AdditionalFiles.Add(additionalFile);

                    var iconStyle = new IconStyle
                    {
                        Icon = new IconStyle.IconLink(new Uri(context.IsKmz ? Path.GetFileName(additionalFile) : additionalFile, UriKind.Relative)),
                        Scale = vectorStyle.SymbolScale
                    };

                    style.Icon = iconStyle;
                }
            });

            EventHandler endedHandler = delegate { style = null; };

            return context =>
            {
                if (style == null && sharpmapStyle.Enabled)
                {
                    install(context);

                    context.Exporter.Ended -= endedHandler;
                    context.Exporter.Ended += endedHandler;
                }

                return style;
            };
        }
        public static Func <ExportContext, SharpKml.Dom.Style> CreateFromSharpmapStyle(IStyle sharpmapStyle)
        {
            if (sharpmapStyle == null)
            {
                throw new ArgumentNullException("sharpmapStyle");
            }

            var vectorStyle = sharpmapStyle as VectorStyle;

            if (vectorStyle == null)
            {
                return(null);
            }

            SharpKml.Dom.Style style = null;

            var install = new Action <ExportContext>(context =>
            {
                style = new SharpKml.Dom.Style
                {
                    Id = sharpmapStyle.GetHashCode().ToString(CultureInfo.InvariantCulture)
                };

                if (vectorStyle.Line != null)
                {
                    var lineStyle = new LineStyle();
                    style.Line    = lineStyle;

                    var color           = vectorStyle.Line.Color;
                    lineStyle.Color     = new Color32(color.A, color.B, color.G, color.R);
                    lineStyle.ColorMode = ColorMode.Normal;
                    lineStyle.Width     = vectorStyle.Line.Width;
                }

                var solidColor = ConvertToColor32(vectorStyle.Fill);
                if (solidColor != null)
                {
                    var polygonStyle = new PolygonStyle();
                    style.Polygon    = polygonStyle;

                    polygonStyle.Fill  = true;
                    polygonStyle.Color = solidColor;
                }

                if (vectorStyle.Symbol == null)
                {
                    if (vectorStyle.PointSize > 0)
                    {
                        var iconStyle = new IconStyle();

                        var pointColor = vectorStyle.PointColor != null
                            ? ConvertToColor32(vectorStyle.PointColor) ?? new Color32(255, 0, 0, 0)
                            : new Color32(255, 0, 0, 0);

                        iconStyle.Color     = pointColor;
                        iconStyle.ColorMode = ColorMode.Normal;
                        iconStyle.Icon      = new IconStyle.IconLink(Pushpins.ShadedDot);
                        iconStyle.Scale     = vectorStyle.PointSize / 6;

                        style.Icon = iconStyle;
                    }
                }
                else
                {
                    var additionalFile = SaveImagetoDisk(vectorStyle.Symbol);
                    Debug.Assert(additionalFile != null, "additionalFile != null");

                    context.AdditionalFiles.Add(additionalFile);

                    var iconStyle = new IconStyle
                    {
                        Icon  = new IconStyle.IconLink(new Uri(context.IsKmz ? Path.GetFileName(additionalFile) : additionalFile, UriKind.Relative)),
                        Scale = vectorStyle.SymbolScale
                    };

                    style.Icon = iconStyle;
                }
            });

            EventHandler endedHandler = delegate { style = null; };

            return(context =>
            {
                if (style == null && sharpmapStyle.Enabled)
                {
                    install(context);

                    context.Exporter.Ended -= endedHandler;
                    context.Exporter.Ended += endedHandler;
                }

                return style;
            });
        }