private void AddLocationsFolder(Document document)
        {
            var locationFolder = new Folder
            {
                Name = "Locations"
            };

            document.AddFeature(locationFolder);

            var listStyle = new ListStyle
            {
                ItemType = ListItemType.CheckHideChildren,
            };

            listStyle.AddItemIcon(new ItemIcon
            {
                Href = new Uri("http://maps.google.com/mapfiles/kml/shapes/placemark_circle.png", UriKind.Absolute)
            });

            locationFolder.AddStyle(new Style
            {
                List = listStyle
            });

            locationFolder.AddFeature(this.From.ToKmlPlacemark(KmlCommonElements.PlacementCircleStyleMapReferenceUri));
            locationFolder.AddFeature(this.To.ToKmlPlacemark(KmlCommonElements.PlacementCircleStyleMapReferenceUri));
        }
        public string Export(IEnumerable <IPlantillaCompuestaExportable> plantillas)
        {
            logger.Info("export {0}", Utilities.Serializer.Serialize2JSON(plantillas));
            // Crear el estilo para el ícono
            var style = new Style();

            style.Id   = "plantillaSimpleIcon";
            style.Icon = new IconStyle();
            //style.Icon.Color = new Color32(255, 0, 255, 0);
            //style.Icon.ColorMode = ColorMode.Normal;
            style.Icon.Icon  = new IconStyle.IconLink(new Uri("http://www.tatuel.com.ar/assets/img/plantillas/plantilla-simple.png"));
            style.Icon.Scale = 1.1;
            // Conjunto de localizaciones
            Folder carpeta = new Folder();

            carpeta.Name = "Localizaciones de referencia";
            carpeta.AddStyle(style);
            // Recorrer cada instancia de plantilla simple y cargar ese punto
            Point point;

            foreach (IPlantillaCompuestaExportable pc in plantillas)
            {
                point = new Point();
                point.AltitudeMode = AltitudeMode.Absolute;
                point.Id           = "Tatuel";
                point.TargetId     = pc.idTemporal;
                point.Coordinate   = new Vector(pc.latitud, pc.longitud, pc.altitud);
                Placemark marca = new Placemark();
                marca.Name     = "" + pc.descripcion;
                marca.Geometry = point;
                // descripcion
                marca.Description      = new Description();
                marca.Description.Text = pc.descripcion;
                marca.ExtendedData     = new ExtendedData();
                marca.ExtendedData.AddData(new Data()
                {
                    DisplayName = pc.criterioDeAgrupacion,
                    Name        = "Nombre",
                    Value       = pc.descripcion
                });
                marca.Time = new Timestamp()
                {
                    When = pc.fechaHora
                };
                marca.StyleUrl = new Uri("#plantillaSimpleIcon", UriKind.Relative);
                // agregarlo a la carpeta
                carpeta.AddChild(marca);
            }
            // Crear el archivo KML con esa carpeta
            Kml kml = new Kml();

            kml.Feature = carpeta;
            // Serializar y devolver
            Serializer serializerKml = new Serializer();

            serializerKml.Serialize(kml);
            return(serializerKml.Xml);
        }
        /// <summary>
        /// Creates a KML folder with the visualization settings of the link.
        /// </summary>
        /// <param name="directionVector">The direction vector to convert.</param>
        /// <returns>The KML elements for visualizing the link.</returns>
        public static Folder ToKmlLinkFolder(this IDirectionVector directionVector)
        {
            if (directionVector == null)
            {
                throw new ArgumentNullException(nameof(directionVector), "directionVector is null");
            }

            var fromAsHamnetSite = directionVector.From as IHamnetDbSite;
            var toAsHamnetSite   = directionVector.To as IHamnetDbSite;
            var linkFolder       = new Folder
            {
                Name = (fromAsHamnetSite != null) && (toAsHamnetSite != null)
                    ? $"Link between {fromAsHamnetSite.Callsign?.ToUpperInvariant()} and {toAsHamnetSite.Callsign?.ToUpperInvariant()}"
                    : $"Link between {directionVector.From.Latitude}/{directionVector.From.Longitude} and {directionVector.To.Latitude}/{directionVector.To.Longitude}",
                Visibility = true
            };

            var listStyle = new ListStyle
            {
                ItemType = ListItemType.CheckHideChildren,
            };

            listStyle.AddItemIcon(new ItemIcon
            {
                Href = new Uri("empty_icon.png", UriKind.Relative)
            });

            linkFolder.AddStyle(new Style
            {
                List = listStyle
            });

            linkFolder.AddFeature(CreateLinePlacemark(directionVector.From, directionVector.To, "Line with screen to ground", new Uri("#line", UriKind.Relative), true, string.Empty));

            // description will be added to the larger (outer) zone only - hence the 2.4 GHz zone
            string description = KmlCommonElements.BalloonCssString;

            description += (fromAsHamnetSite != null) && (toAsHamnetSite != null)
                    ? $"<h2>Link between {fromAsHamnetSite.Callsign?.ToUpperInvariant()} and {toAsHamnetSite.Callsign?.ToUpperInvariant()}</h2>"
                    : $"<h2>Link between {directionVector.From.Latitude}/{directionVector.From.Longitude} and {directionVector.To.Latitude}/{directionVector.To.Longitude}</h2>";

            description += $@"<table>
<tr><td class=""left"">distance: </td><td>{directionVector.Distance / 1000.0:F1} km</td></tr>
<tr><td class=""left"">azimuth to: </td><td>{directionVector.Bearing:F1}&#176;</td></tr>
<tr><td class=""left"">elevation to: </td><td>{directionVector.Elevation:F1}&#176;</td></tr>
<tr><td class=""left"">azimuth from: </td><td>{(directionVector.Bearing + 180.0) % 360.0:F3}&#176;</td></tr>
<tr><td class=""left""><a href=""https://en.wikipedia.org/wiki/Free-space_path_loss"">FSPL</a>: </td><td>{directionVector.Distance.FreeSpacePathloss(2.4e9):F1} dB @ 2.4 GHz<br>{directionVector.Distance.FreeSpacePathloss(5.8e9):F1} dB @ 5.8 GHz</td></tr>
</table>";
            linkFolder.AddFeature(CreateFresnelPlacemark(directionVector, "2.4 GHz fresnel zone", 2.4e9, KmlCommonElements.PolygonStyleTransparentReferenceUri, description));
            linkFolder.AddFeature(CreateFresnelPlacemark(directionVector, "5.8 GHz fresnel zone", 5.8e9, KmlCommonElements.PolygonStyleReferenceUri, string.Empty));

            return(linkFolder);
        }
        public FileContentResult DownloadKMLStatic(int id = 0)
        {
            var route = db.Flights.Where(r => r.FlightID == id).Select(r => r.RouteID).FirstOrDefault();

            if (route == null)
            {
                route = id;                //patch if route is for some reason empty
            }
            var flights = db.Flights.Where(r => r.RouteID == route).Select(r => new { r.FlightID }).ToList();

            var doc = new Document();

            doc.Id   = "Route";
            doc.Name = "Route";
            var folder = new Folder();

            folder.Id   = "Flights";
            folder.Name = "Flights";

            foreach (var f in flights)
            {
                var i = flights.IndexOf(f);
                var flightLineStyles = new FlightLineStyles(i);
                var docStyle         = flightLineStyles.style;
                folder.AddStyle(docStyle);

                var placemark = new FlightPlacemarkLineString(f.FlightID);
                placemark.styleUrlRef = docStyle.Id;
                folder.AddFeature(placemark.placemark);
            }
            doc.AddFeature(folder);

            var kml = new Kml();

            kml.Feature = doc;
            KmlFile kmlFile = KmlFile.Create(kml, true);

            //using (var stream = System.IO.File.OpenWrite("C:/temp/kmlfile.kml"))
            //{
            //    kmlFile.Save(stream);

            //};

            using (var stream = new System.IO.MemoryStream())
            {
                kmlFile.Save(stream);
                var kmlFileName = "Flight_" + id + ".kml";
                var fileBytes   = new System.Text.UTF8Encoding().GetBytes(new System.Text.UTF8Encoding().GetString(stream.ToArray()));
                return(File(fileBytes, "application/vnd.google-earth.kml+xml", kmlFileName));
            };
        }
예제 #5
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");
        }
예제 #6
0
        public void ProduceKml(string file)
        {
            Kml      doc = new Kml();
            Document d   = new Document()
            {
                Name = Path.GetFileName(file)
            };

            doc.Feature = d;

            Folder root = new Folder()
            {
                Name = "Network"
            };

            d.AddFeature(root);
            StyleMapCollection style_default = GenerateNewStyle("default", d, null);

            List <string> folders = (from i in Locations.Values where !string.IsNullOrWhiteSpace(i.ParentName) select i.ParentName).Distinct().ToList();

            foreach (var str in folders)
            {
                Folder fPlacemark = new Folder()
                {
                    Name = str
                };
                Folder fPath = new Folder()
                {
                    Name = "Paths"
                };
                root.AddFeature(fPlacemark);
                if (!Locations.ContainsKey(str))
                {
                    Locations.Add(str, new Location()
                    {
                        Name = str, PlacemarkFolder = fPlacemark
                    });
                }
                else
                {
                    fPlacemark.AddFeature(fPath);
                    Locations[str].PathFolder      = fPath;
                    Locations[str].PlacemarkFolder = fPlacemark;
                }
                GenerateNewStyle(str.Sanitize(), d, Locations[str]);
            }
            foreach (var loc in Locations.Values)
            {
                var parent = (from i in Locations.Values where i.Name == loc.ParentName select i).FirstOrDefault();
                loc.Parent = parent;
            }

            foreach (var loc in Locations.Values)
            {
                if (loc.Coordinates == null)
                {
                    continue;
                }
                Placemark plPoint = new Placemark();
                Placemark plPath  = new Placemark();

                if (loc.Parent != null)
                {
                    switch (Labels)
                    {
                    case LabelMode.All:
                        plPoint.StyleUrl = new Uri($"#msn_{loc.ParentName.Sanitize()}", UriKind.Relative);
                        break;

                    case LabelMode.Some:
                        if (IsImportant(loc.Name))
                        {
                            plPoint.StyleUrl = new Uri($"#msn_{loc.ParentName.Sanitize()}", UriKind.Relative);
                        }
                        else
                        {
                            plPoint.StyleUrl = new Uri($"#msn_{loc.ParentName.Sanitize()}_nolabels", UriKind.Relative);
                        }
                        break;

                    case LabelMode.None:
                        plPoint.StyleUrl = new Uri($"#msn_{loc.ParentName.Sanitize()}_nolabels", UriKind.Relative);
                        break;
                    }
                }
                else if (loc.StyleMap != null)
                {
                    switch (Labels)
                    {
                    case LabelMode.All:
                    case LabelMode.Some:
                        plPoint.StyleUrl = new Uri($"#{loc.StyleMap.Id}", UriKind.Relative);
                        break;

                    case LabelMode.None:
                        plPoint.StyleUrl = new Uri($"#{loc.StyleMapNoLabels.Id}", UriKind.Relative);
                        break;
                    }
                }
                else
                {
                    plPoint.StyleUrl = new Uri($"#{style_default.Id}", UriKind.Relative);
                }
                plPoint.Name     = loc.Name;
                plPoint.Geometry = new SharpKml.Dom.Point()
                {
                    Coordinate = loc.Coordinates
                };
                Folder placemarkFolder = loc.Parent?.PlacemarkFolder ?? loc.PlacemarkFolder ?? root;
                placemarkFolder.AddFeature(plPoint);
                if (loc.Parent?.Coordinates != null)
                {
                    plPath.StyleUrl = new Uri($"#msn_{loc.ParentName.Sanitize()}", UriKind.Relative);
                    plPath.Name     = loc.Name + " Path";
                    LineString l = new LineString();
                    l.Coordinates = new CoordinateCollection();
                    l.Coordinates.Add(loc.Coordinates);
                    l.Coordinates.Add(loc.Parent.Coordinates);
                    plPath.Geometry = l;
                    loc.Parent.PathFolder.AddFeature(plPath);
                }
            }
            Folder linksFolder = new Folder()
            {
                Name = "Links"
            };
            Style s = new Style()
            {
                Id   = $"sn_links",
                Line = new LineStyle()
                {
                    Color = new Color32(255, 255, 0, 0),
                    Width = 4.0
                }
            };

            root.AddStyle(s);
            if (Links.Count > 0)
            {
                root.AddFeature(linksFolder);
            }
            foreach (Link link in Links)
            {
                Placemark p = new Placemark()
                {
                    Name = link.Name
                };
                LineString l = new LineString();
                l.Coordinates = new CoordinateCollection();
                l.Coordinates.Add(link.Location1.Coordinates);
                l.Coordinates.Add(link.Location2.Coordinates);
                p.Geometry = l;
                linksFolder.AddFeature(p);
                p.StyleUrl = new Uri($"#{s.Id}", UriKind.Relative);
            }
            Serializer serializer = new Serializer();

            serializer.Serialize(doc);
            File.WriteAllText(file, serializer.Xml);
        }
        public string Export(IPlantillaCompuestaExportable plantilla, IEnumerable <IInstanciaPlantillaCompuestaExportable> instancias)
        {
            logger.Info("export {0}, {1}", Utilities.Serializer.Serialize2JSON(plantilla), Utilities.Serializer.Serialize2JSON(instancias));
            // Crear el estilo para el ícono
            var style = new Style();

            style.Id   = "plantillaSimpleIcon";
            style.Icon = new IconStyle();
            //style.Icon.Color = new Color32(255, 0, 255, 0);
            //style.Icon.ColorMode = ColorMode.Normal;
            style.Icon.Icon  = new IconStyle.IconLink(new Uri("http://www.tatuel.com.ar/assets/img/plantillas/plantilla-simple.png"));
            style.Icon.Scale = 1.1;
            // Conjunto de localizaciones
            Folder carpeta = new Folder();

            carpeta.Name = "Localizaciones de carga de datos";
            carpeta.AddStyle(style);
            // Recorrer cada instancia de plantilla simple y cargar ese punto
            Point point;

            foreach (Models.IInstanciaPlantillaCompuestaExportable ipc in instancias)
            {
                //if (ipc.posicion != null)
                //{
                point = new Point();
                point.AltitudeMode = AltitudeMode.Absolute;
                point.Id           = "Tatuel";
                //LatitudLongitud latlon = (LatitudLongitud)ipc.posicion;
                point.Coordinate = new Vector(ipc.latitud, ipc.longitud, ipc.altitud);
                Placemark marca = new Placemark();
                marca.Name     = "" + ipc.descripcion;
                marca.Geometry = point;
                // descripcion
                marca.Description      = new Description();
                marca.Description.Text = "Punto de carga de datos ";
                marca.ExtendedData     = new ExtendedData();
                marca.ExtendedData.AddData(new Data()
                {
                    DisplayName = "Datos serializados en formato JSON",
                    Name        = "Datos serializados en formato JSON",
                    Value       = Utilities.Serializer.Serialize2JSON(new
                    {
                        accuracy        = ipc.accuracy,
                        altitud         = ipc.altitud,
                        altitudAccuracy = ipc.altitudAccuracy,
                        descripcion     = ipc.descripcion,
                        fechaHora       = ipc.fechaHora,
                        idTemporal      = ipc.idTemporal,
                        latitud         = ipc.latitud,
                        longitud        = ipc.longitud
                    })
                });
                marca.Time = new Timestamp()
                {
                    When = ipc.fechaHora
                };
                marca.StyleUrl = new Uri("#plantillaSimpleIcon", UriKind.Relative);
                // agregarlo a la carpeta
                carpeta.AddChild(marca);
                //}
            }
            // Crear el archivo KML con esa carpeta
            Kml kml = new Kml();

            kml.Feature = carpeta;
            // Serializar y devolver
            Serializer serializerKml = new Serializer();

            serializerKml.Serialize(kml);
            return(serializerKml.Xml);
        }