Пример #1
1
        /// <summary>
        /// Creates a new KmzFile using the data specified in the KmlFile.
        /// </summary>
        /// <param name="kml">The Kml data to add to the archive.</param>
        /// <returns>
        /// A new KmzFile populated with the data specified in the KmlFile.
        /// </returns>
        /// <remarks>
        /// This overloaded version does not resolve any links in the Kml data
        /// and, therefore, will not add any local references to the archive.
        /// </remarks>
        /// <exception cref="ArgumentNullException">kml is null.</exception>
        public static KmzFile Create(KmlFile kml)
        {
            if (kml == null)
            {
                throw new ArgumentNullException("kml");
            }

            var instance = new KmzFile(new MemoryStream());
            instance._zip = new ZipFile();

            // Add the Kml data
            using (var stream = new MemoryStream())
            {
                kml.Save(stream);
                instance.AddFile(DefaultKmlFilename, stream.ToArray());
            }
            return instance;
        }
Пример #2
0
        static void Main(string[] args)
        {
            String  inFile  = @"C:\tmp\Test\Ferrocarril Belgrano.kml";
            String  outFile = @"C:\tmp\Test\out.kml";
            KmlFile kmlFile = null;

            using (Stream fileStream = File.OpenRead(inFile))
            {
                kmlFile = KmlFile.Load(fileStream);
            }
            Kml      kml = kmlFile.Root as Kml;
            Document d   = kml.Feature as Document;
            Folder   f   = (Folder)d.Features.FirstOrDefault();
            Folder   f2  = (Folder)f.Features.FirstOrDefault();

            Document doc = new Document();

            doc.Name = "MyTestKml";
            d.Schemas.ToList().ForEach(s => doc.AddSchema(s.Clone()));
            doc.AddFeature(f2.Clone());

            // This allows us to save and Element easily.
            KmlFile kmlOut = KmlFile.Create(doc, false);

            using (var stream = System.IO.File.OpenWrite(outFile))
            {
                kmlOut.Save(stream);
            }
        }
Пример #3
0
 public static void SaveToKmlFile(KmlFile kmlFile, String kmlFilePath)
 {
     using (var stream = System.IO.File.OpenWrite(kmlFilePath))
     {
         kmlFile.Save(stream);
     }
 }
Пример #4
0
        public void Save(string filename)
        {
            KmlFile kmlfile = KmlFile.Create(_data, false);

            using (var stream = System.IO.File.OpenWrite(filename))
            {
                kmlfile.Save(stream);
            }
        }
Пример #5
0
        public static void SaveKml(KmlFile file, string filename)
        {
            if (File.Exists(filename))
            {
                File.Delete(filename);
            }

            using (var stream = File.OpenWrite(filename))
            {
                file.Save(stream);
            }
        }
Пример #6
0
        public override void saveKmlDocument(Document kmlDoc)
        {
            // This allows us to save and Element easily.
            var kml = new Kml();

            kml.AddNamespacePrefix(KmlNamespaces.GX22Prefix, KmlNamespaces.GX22Namespace);
            kml.Feature = kmlDoc;


            KmlFile kmlF = KmlFile.Create(kml, false);

            kmlF.Save(@"mykmlFile.kml");
        }
        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));
            };
        }
        void ofd_FileOkSaveKML(object sender, CancelEventArgs e)
        {
            AirNavigationRaceLiveMain.SetStatusText("");
            double channelRadius;
            double altitude;

            // retrieve points from selected tree element

            if (ListOfRouteNames.Count == 0)
            {
                return;
            }

            bool ret = double.TryParse(txtChannelWidth.Text, out channelRadius);

            if (!ret)
            {
                channelRadius = DEFAULT_CHANNEL_WIDTH / 2.0;
            }
            else
            {
                channelRadius = channelRadius / 2.0;
            }

            ret = double.TryParse(txtHeight.Text, out altitude);
            if (!ret)
            {
                altitude = 300;
            }

            bool hasRoundedCorners = chkUseRoundedCorners.Checked;

            SaveFileDialog sfd     = sender as SaveFileDialog;
            string         fname   = sfd.FileName;
            ANRData        anrData = new ANRData();

            anrData.generateParcour(ListOfRoutes, ListOfRouteNames, ListOfNBL, ListOfNBLNames, HAS_MARKERS, CREATE_PROH_AREA, USE_STANDARD_ORDER, channelRadius, altitude, hasRoundedCorners);
            Document document = anrData.Document;
            Kml      kml      = new Kml();

            kml.Feature = document;
            KmlFile file = KmlFile.Create(kml, false);

            using (var stream = System.IO.File.Open(fname, FileMode.Create, FileAccess.Write, FileShare.Read))
            {
                file.Save(stream);
            }
            AirNavigationRaceLiveMain.SetStatusText(string.Format("Route Generator - saved file {0}", sfd.FileName));
        }
Пример #9
0
        public static void SaveFile(KmlFile kmlFile, String filePath)
        {
            string fileExtension = System.IO.Path.GetExtension(filePath);

            using (FileStream fileStream = File.OpenWrite(filePath))
            {
                if (fileExtension.Equals(".kmz", StringComparison.OrdinalIgnoreCase))
                {
                    KmzFile kmzFile = KmzFile.Create(kmlFile);
                    kmzFile.Save(fileStream);
                }
                else
                {
                    kmlFile.Save(fileStream);
                }
            }
        }
Пример #10
0
 public void Save()
 {
     try
     {
         using (var fileStream = File.OpenWrite(this.OutputFile))
         {
             KmlFile.Save(fileStream);
         }
     }
     catch (Exception e)
     {
         Console.WriteLine(
             "An error occured while saving {0}: {1}",
             System.IO.Path.GetFileName(this.OutputFile),
             e.ToString());
     }
 }
Пример #11
0
        // Creates a KML file from an array of locations
        public static void CreateKML(string fileName, Location[] locations)
        {
            Document document = new Document();

            foreach (Location l in locations)
            {
                // Creates a new Placemark
                Point point = new Point();
                point.Coordinate = new Vector(l.Lat, l.Lon);
                Placemark placemark = new Placemark();
                placemark.Name     = l.Name;
                placemark.Address  = l.Address;
                placemark.Geometry = point;

                // Stores the Placemark in a the document
                document.AddFeature(placemark);
            }

            // Converts the documento to KML format
            Kml root = new Kml();

            root.Feature = document;
            KmlFile kml = KmlFile.Create(root, false);

            try
            {
                // Delete the old file if it exits
                if (File.Exists(@fileName))
                {
                    File.Delete(@fileName);
                }

                // Creates the file
                using (FileStream stream = File.OpenWrite(fileName))
                {
                    // Saves the stream to the selected path
                    kml.Save(stream);
                    MessageBox.Show("File " + fileName + " created.");
                }
            }
            catch (Exception Ex)
            {
                throw new Exception(Ex.Message);
            }
        }
Пример #12
0
        [TestMethod] public void TestKml1()
        {
            var point = new Point();

            point.Coordinate = new Vector(-13.163959, -72.545992);

            // This is the Element we are going to save to the Kml file.
            var placemark = new Placemark();

            placemark.Geometry = point;
            placemark.Name     = "Machu Picchu";

            // This allows us to save and Element easily.
            KmlFile kml = KmlFile.Create(placemark, false);

            using (var stream = System.IO.File.OpenWrite("my placemark.kml"))
            {
                kml.Save(stream);
            }
        }
Пример #13
0
        public async System.Threading.Tasks.Task SaveAsKmlAsync()
        {
            Kml      kml      = new Kml();
            Document document = new Document();

            document.Name = "Weeds from ThistleTracker";
            kml.Feature   = document;
            // Loop & add weedspots
            foreach (WeedSpot spot in _spots)
            {
                Point point = new Point();
                point.Coordinate = new Vector(spot.Latitude, spot.Longitude);
                SharpKml.Dom.Placemark place = new SharpKml.Dom.Placemark();
                place.Name     = spot.Name;
                place.Geometry = point;
                document.AddFeature(place);
            }
            string fileName = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Weeds.kml");

            // delete if existing
            if (File.Exists(fileName))
            {
                File.Delete(fileName);
            }

            // Create KML file
            KmlFile kmlFile = KmlFile.Create(kml, true);

            using (FileStream stream = File.OpenWrite(fileName))
            {
                kmlFile.Save(stream);
            }

            // Share with other apps
            await Share.RequestAsync(new ShareFileRequest
            {
                Title = "ThistleTracker KML Export",
                File  = new ShareFile(fileName)
            });
        }
Пример #14
0
        private void gererateKML(DataPoint[] arrData, String dir, String fileName, Dictionary <int, Double> areaTimes)
        {
            Document doc = new Document();

            Dictionary <int, List <Placemark> > placemarks = new Dictionary <int, List <Placemark> >();

            for (int i = 0; i < arrData.Length; i++)
            {
                DataPoint dataPoint = arrData[i];

                double areaTime;

                // Check if point meets min area time threshold, and check that it is not noise
                if ((areaTimes.TryGetValue(dataPoint.AID, out areaTime)) && (areaTime >= (double)minAreaTime) && (dataPoint.AID != ClusterComputer.NOISE))
                {
                    Point point = new Point();
                    point.Coordinate = new Vector(dataPoint.LAT, dataPoint.LON);

                    Placemark placemark = new Placemark();
                    placemark.Geometry = point;
                    placemark.Name     = String.Format("{0} - {1}", dataPoint.AID.ToString(), dataPoint.IID.ToString());

                    doc.AddFeature(placemark);
                }
            }

            KmlFile file = KmlFile.Create(doc, true);

            String fName;

            fName = String.Format(@"\{0}_MinAreaTime_{1}.kml", fileName, minAreaTime.ToString());

            FileStream outStream = new FileStream(dir + fName, FileMode.Create, FileAccess.ReadWrite);

            file.Save(outStream);

            outStream.Close();
        }
Пример #15
0
        private static void FPConverter(string file)
        {
            var lpFile = file;

            if (!File.Exists(lpFile))
            {
                return;
            }

            XNamespace ns  = "http://earth.google.com/kml/2.2";
            var        doc = XDocument.Load(lpFile);

            var placemarks = doc.Root
                             .Element(ns + "Document")
                             .Elements(ns + "Folder")
                             .Elements(ns + "Placemark");

            var kml = new Kml();

            var document = new Document();

            document.Name = Path.GetFileNameWithoutExtension(lpFile);


            foreach (var obj in placemarks)
            {
                var name = obj
                           .Element(ns + "name");


                Folder folder = new Folder()
                {
                    Name = name.Value,
                };

                Placemark newLine = new Placemark();
                newLine.Name = name.Value;

                var coordinates = obj
                                  .Elements(ns + "LineString")
                                  .Elements(ns + "coordinates");


                var runNumber = name.Value.Trim();
                var runsubs   = runNumber.Substring(3);

                const double Scale = 0.3048;


                if (!string.IsNullOrEmpty(runNumber))
                {
                    if (coordinates.Any())
                    {
                        foreach (var coords in coordinates)
                        {
                            var value = coords.Value;
                            var num   = Regex.Match(value, @"[0-9]{0,4}\s+");

                            LineString line = new LineString();

                            var newCoords = coords.Value.Trim();

                            // splitting string values from original kml
                            // into usable data for Vector class
                            string[] splitCoords  = newCoords.Split(' ');
                            string[] splitCoords1 = splitCoords[0].Split(',');
                            string[] splitCoords2 = splitCoords[1].Split(',');

                            double long1   = double.Parse(splitCoords1[0]);
                            double lat1    = double.Parse(splitCoords1[1]);
                            double height1 = double.Parse(splitCoords1[2]);

                            double long2   = double.Parse(splitCoords2[0]);
                            double lat2    = double.Parse(splitCoords2[1]);
                            double height2 = double.Parse(splitCoords2[2]);


                            CoordinateCollection CoordsCollection = new CoordinateCollection();
                            CoordsCollection.Add(new Vector(lat1, long1, height1));
                            CoordsCollection.Add(new Vector(lat2, long2, height2));

                            // Start placemark code
                            Placemark flightLabel = new Placemark();

                            Point  point       = new Point();
                            Vector pointVector = new Vector();

                            pointVector.Latitude  = ReturnCentre(lat1, lat2);
                            pointVector.Longitude = ReturnCentre(long1, long2);

                            point.Coordinate = pointVector;

                            flightLabel.Geometry = point;
                            // end placemark code

                            line.Coordinates = CoordsCollection;
                            newLine.Geometry = line;

                            //puts placemark into <folder>
                            folder.AddFeature(newLine);


                            //add the folder to the document.
                            document.AddFeature(folder);


                            if (num.Success)
                            {
                                var valueStr = num.Value.Trim();

                                if (int.TryParse(valueStr, out var height))
                                {
                                    checked
                                    {
                                        var feet = (height / Scale);
                                        flightLabel.Name = runNumber + "/" + Convert.ToInt32(feet) + "ft";
                                    }
                                }
                            }

                            folder.AddFeature(flightLabel);

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

                            using (var fs = File.OpenWrite(document.Name + "-TEST-ONLY-DO-NOT-FLY.kml"))
                            {
                                kmlFile.Save(fs);
                            }
                        }
                    }
                }
            }
        }
Пример #16
0
        /// <summary>
        /// converte la feature class in kml. Se non sono presenti le coordinate il dato non viene inserito
        /// </summary>
        /// <param name="sourceWorkspace">workspace con la feature class</param>
        /// <param name="outputName">nome della feature class e del csv di output</param>
        /// <param name="targetPath">percorso dove salvare il file di output</param>
        /// <param name="delimitator">delimitatore utilizzato nel csv</param>
        private void ConvertFeatureClassPointToKml(IWorkspace sourceWorkspace, string outputName, string targetPath)
        {
            IFeatureCursor featureCursor = null;

            try
            {
                IFeatureWorkspace featureWorkspace = sourceWorkspace as IFeatureWorkspace;
                IFeatureClass     featureClass     = featureWorkspace.OpenFeatureClass(outputName);
                if (featureClass.ShapeType != esriGeometryType.esriGeometryPoint)
                {
                    throw new Exception($"Per esportare in {Enum.GetName(typeof(FileExtension), FileExtension.kmz)} occorre una feature class di tipo {Enum.GetName(typeof(esriGeometryType), esriGeometryType.esriGeometryPoint)}!");
                }

                featureCursor = featureClass.Search(null, true);

                var folder = new Folder();
                folder.Id   = outputName;
                folder.Name = outputName;

                Dictionary <int, string> fields = new Dictionary <int, string>();
                IField field = null;
                for (int i = 0; i < featureCursor.Fields.FieldCount; i++)
                {
                    field = featureCursor.Fields.Field[i];
                    if ((field.Type == esriFieldType.esriFieldTypeBlob) || (field.Type == esriFieldType.esriFieldTypeGeometry) ||
                        (field.Type == esriFieldType.esriFieldTypeGlobalID) || (field.Type == esriFieldType.esriFieldTypeGUID) ||
                        (field.Type == esriFieldType.esriFieldTypeRaster) || (field.Type == esriFieldType.esriFieldTypeXML))
                    {
                        continue;
                    }

                    fields.Add(i, field.Name);
                }

                IFeature     feature      = null;
                Placemark    placemark    = null;
                Vector       vector       = null;
                ExtendedData extendedData = null;
                while ((feature = featureCursor.NextFeature()) != null)
                {
                    if ((feature.ShapeCopy == null) || (feature.ShapeCopy.IsEmpty))
                    {
                        continue;
                    }

                    IPoint p = feature.ShapeCopy as IPoint;
                    if (p.SpatialReference.FactoryCode != Helper.SpatialReferenceWGS84.FactoryCode)
                    {
                        p.Project(Helper.SpatialReferenceWGS84);
                    }

                    vector = new Vector(p.Y, p.X);


                    placemark      = new Placemark();
                    placemark.Id   = feature.OID.ToString();
                    placemark.Name = feature.OID.ToString();

                    extendedData = new ExtendedData();
                    foreach (int i in fields.Keys)
                    {
                        Data data = new Data();
                        data.DisplayName = fields[i];
                        data.Name        = fields[i];
                        data.Value       = feature.get_Value(i).ToString();
                        extendedData.AddData(data);
                    }

                    placemark.ExtendedData = extendedData;
                    placemark.Geometry     = new SharpKml.Dom.Point {
                        Coordinate = vector
                    };

                    folder.AddFeature(placemark);
                }

                Kml kml = new Kml();
                kml.AddNamespacePrefix(KmlNamespaces.GX22Prefix, KmlNamespaces.GX22Namespace);
                kml.Feature = folder;
                KmlFile kmlfile = KmlFile.Create(kml, false);
                using (var stream = File.OpenWrite(System.IO.Path.Combine(targetPath, System.IO.Path.ChangeExtension(outputName, Enum.GetName(typeof(FileExtension), FileExtension.kmz)))))
                {
                    kmlfile.Save(stream);
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                if (featureCursor != null)
                {
                    Marshal.FinalReleaseComObject(featureCursor);
                }
            }
        }
Пример #17
0
        public async Task <ResponseMessage> ExportDesign(string designId)
        {
            try
            {
                var project = await _designService.GetDesign(designId);

                string projectPath = string.Empty;

                if (project.BluePrint != null)
                {
                    List <Cable>         cables         = new List <Cable>();
                    List <MicroDuct>     microduct      = new List <MicroDuct>();
                    List <Chamber>       chambers       = new List <Chamber>();
                    List <ODF>           oDFs           = new List <ODF>();
                    List <Duct>          ducts          = new List <Duct>();
                    List <Pole>          poles          = new List <Pole>();
                    List <Splitter>      splitters      = new List <Splitter>();
                    List <SpliceClosure> spliceClosures = new List <SpliceClosure>();
                    List <FAT>           fat            = new List <FAT>();
                    List <FDT>           fdt            = new List <FDT>();


                    if (project.BluePrint.Children != null && project.BluePrint.Children.Count > 0)
                    {
                        ExtractNetwork(project.BluePrint.Children, cables, chambers, oDFs, ducts, microduct, poles, spliceClosures, splitters, fat, fdt);
                    }

                    if (cables.Count > 0 || chambers.Count > 0 || oDFs.Count > 0 || ducts.Count > 0 || poles.Count > 0 || splitters.Count > 0 || spliceClosures.Count > 0)
                    {
                        var uploadFolder = "\\Uploads\\" + LoginUser.Id + "\\" + System.Guid.NewGuid().ToString();

                        var uploadPath = _hostingEnvironment.ContentRootPath + uploadFolder;

                        Directory.CreateDirectory(uploadPath);


                        projectPath = Path.Combine(uploadPath, "DesignExport.kml");


                        Kml                kml       = new Kml();
                        Placemark          placemark = new Placemark();
                        SharpKml.Dom.Point point;

                        SharpKml.Dom.Document document1 = new SharpKml.Dom.Document();
                        var style = new Style();

                        foreach (var chamber in chambers)
                        {
                            placemark              = new Placemark();
                            placemark.Name         = chamber.EntityType;
                            placemark.ExtendedData = new ExtendedData();

                            point = new SharpKml.Dom.Point();

                            point.Coordinate   = new SharpKml.Base.Vector(Convert.ToDouble(chamber.Geometry.coordinates[1]), Convert.ToDouble(chamber.Geometry.coordinates[0]));
                            placemark.Geometry = point;

                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "Code",
                                Value = chamber.Code
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "ConstructionStage",
                                Value = chamber.ConstructionStage
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "ActivationStage",
                                Value = chamber.ActivationStage
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "Accessibility",
                                Value = chamber.Accessibility
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "HierarchyType",
                                Value = chamber.HierarchyType
                            });

                            document1.AddFeature(placemark);
                        }

                        foreach (var chamber in oDFs)
                        {
                            placemark              = new Placemark();
                            placemark.Name         = chamber.EntityType;
                            placemark.ExtendedData = new ExtendedData();

                            point = new SharpKml.Dom.Point();

                            point.Coordinate   = new SharpKml.Base.Vector(Convert.ToDouble(chamber.Geometry.coordinates[1]), Convert.ToDouble(chamber.Geometry.coordinates[0]));
                            placemark.Geometry = point;

                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "Code",
                                Value = chamber.Code
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "ConstructionStage",
                                Value = chamber.ConstructionStage
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "ActivationStage",
                                Value = chamber.ActivationStage
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "Accessibility",
                                Value = chamber.Accessibility
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "HierarchyType",
                                Value = chamber.HierarchyType
                            });

                            document1.AddFeature(placemark);
                        }
                        foreach (var chamber in poles)
                        {
                            placemark              = new Placemark();
                            placemark.Name         = chamber.EntityType;
                            placemark.ExtendedData = new ExtendedData();

                            point = new SharpKml.Dom.Point();

                            point.Coordinate   = new SharpKml.Base.Vector(Convert.ToDouble(chamber.Geometry.coordinates[1]), Convert.ToDouble(chamber.Geometry.coordinates[0]));
                            placemark.Geometry = point;

                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "Code",
                                Value = chamber.Code
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "ConstructionStage",
                                Value = chamber.ConstructionStage
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "ActivationStage",
                                Value = chamber.ActivationStage
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "Accessibility",
                                Value = chamber.Accessibility
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "HierarchyType",
                                Value = chamber.HierarchyType
                            });

                            document1.AddFeature(placemark);
                        }
                        foreach (var chamber in splitters)
                        {
                            placemark              = new Placemark();
                            placemark.Name         = chamber.EntityType;
                            placemark.ExtendedData = new ExtendedData();

                            point = new SharpKml.Dom.Point();

                            point.Coordinate   = new SharpKml.Base.Vector(Convert.ToDouble(chamber.Geometry.coordinates[1]), Convert.ToDouble(chamber.Geometry.coordinates[0]));
                            placemark.Geometry = point;

                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "Code",
                                Value = chamber.Code
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "ConstructionStage",
                                Value = chamber.ConstructionStage
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "ActivationStage",
                                Value = chamber.ActivationStage
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "Accessibility",
                                Value = chamber.Accessibility
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "HierarchyType",
                                Value = chamber.HierarchyType
                            });

                            document1.AddFeature(placemark);
                        }
                        foreach (var chamber in spliceClosures)
                        {
                            placemark              = new Placemark();
                            placemark.Name         = chamber.EntityType;
                            placemark.ExtendedData = new ExtendedData();

                            point = new SharpKml.Dom.Point();

                            point.Coordinate   = new SharpKml.Base.Vector(Convert.ToDouble(chamber.Geometry.coordinates[1]), Convert.ToDouble(chamber.Geometry.coordinates[0]));
                            placemark.Geometry = point;

                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "Code",
                                Value = chamber.Code
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "ConstructionStage",
                                Value = chamber.ConstructionStage
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "ActivationStage",
                                Value = chamber.ActivationStage
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "Accessibility",
                                Value = chamber.Accessibility
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "HierarchyType",
                                Value = chamber.HierarchyType
                            });

                            document1.AddFeature(placemark);
                        }

                        foreach (var chamber in cables)
                        {
                            placemark              = new Placemark();
                            placemark.Name         = chamber.EntityType;
                            placemark.ExtendedData = new ExtendedData();

                            point = new SharpKml.Dom.Point();

                            SharpKml.Dom.LineString linestring = new SharpKml.Dom.LineString();

                            CoordinateCollection coordinates = new CoordinateCollection();

                            foreach (var coordinate in chamber.Geometry.coordinates)
                            {
                                coordinates.Add(new Vector(coordinate[1], coordinate[0]));
                            }
                            linestring.Coordinates = coordinates;
                            placemark.Geometry     = linestring;

                            placemark.ExtendedData = new ExtendedData();

                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "Code",
                                Value = chamber.Code
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "ALocation",
                                Value = chamber.ALocation
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "BLocation",
                                Value = chamber.BLocation
                            });
                            if (chamber.IsUnderground.HasValue)
                            {
                                placemark.ExtendedData.AddData(new Data
                                {
                                    Name  = "IsUnderground",
                                    Value = chamber.IsUnderground.ToString()
                                });
                            }

                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "ConstructionStage",
                                Value = chamber.ConstructionStage
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "ActivationStage",
                                Value = chamber.ActivationStage
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "Accessibility",
                                Value = chamber.Accessibility
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "HierarchyType",
                                Value = chamber.HierarchyType
                            });

                            document1.AddFeature(placemark);
                        }

                        foreach (var chamber in ducts)
                        {
                            placemark              = new Placemark();
                            placemark.Name         = chamber.EntityType;
                            placemark.ExtendedData = new ExtendedData();

                            point = new SharpKml.Dom.Point();

                            SharpKml.Dom.LineString linestring = new SharpKml.Dom.LineString();

                            CoordinateCollection coordinates = new CoordinateCollection();

                            foreach (var coordinate in chamber.Geometry.coordinates)
                            {
                                coordinates.Add(new Vector(coordinate[1], coordinate[0]));
                            }
                            linestring.Coordinates = coordinates;
                            placemark.Geometry     = linestring;

                            placemark.ExtendedData = new ExtendedData();

                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "Code",
                                Value = chamber.Code
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "ConstructionStage",
                                Value = chamber.ConstructionStage
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "ActivationStage",
                                Value = chamber.ActivationStage
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "Accessibility",
                                Value = chamber.Accessibility
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "HierarchyType",
                                Value = chamber.HierarchyType
                            });

                            document1.AddFeature(placemark);
                        }


                        kml.Feature = document1;
                        KmlFile kmlfile = KmlFile.Create(kml, false);

                        System.IO.File.Create(projectPath).Dispose();

                        using (var stream1 = System.IO.File.OpenWrite(projectPath))
                        {
                            kmlfile.Save(stream1);
                        }
                    }
                }


                return(new ResponseMessage()
                {
                    Status = "ok", Data = projectPath
                });
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "Error export design.");
                return(new ResponseMessage()
                {
                    Status = "Error", Message = "Error export design."
                });
            }
        }
Пример #18
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");
        }
Пример #19
0
        static void Main(string[] args)
        {
            TextDatei textDatei = new TextDatei();

            int  state         = 0;
            bool exit          = false;
            bool argsFertig    = false;
            bool startWithArgs = false;

            string       file_path_gesamt = "";      // Gesamter Pfad der Datei. Zum Beispiel:           "F:\\Dropbox\\Schlapphut-Projekt\\GPS-Files\\20180628.SLP"
            string       dir_path         = "";      // Pfad zum Verzeichnis der Datei. Zum Beispiel:    "F:\\Dropbox\\Schlapphut-Projekt\\GPS-Files"
            string       file_name        = "";      // Name der Datei. Zum Beispiel:                    "20180628"
            string       file_type        = "";      // Dateityp der Datei. Zum Beispiel:                "SLP"
            const string dir_kml          = "\\KML"; // Unterverzeichnis, in welchem die konvertierte KML-Datei gespeichert wird

            SlpType slpFileType = SlpType.None;      // Der Typ der SLP-Datei

            List <String> file_lines = new List <string>();

            // Fuer KML-Dokument
            var root = new Document();

            root.Open = true;       // Bei Google-Earth das Tree-Menu ausklappen

            // Erstelle Styles
            Style         normalStyle    = CreateNormalSyle();
            Style         highlightStyle = CreateHighlightSyle();
            StyleSelector styleSelector  = createPlacemarkLineStyleMap(normalStyle, highlightStyle);

            // Weise Styles zu
            root.AddStyle(normalStyle);
            root.AddStyle(highlightStyle);
            root.AddStyle(styleSelector);


            Console.ForegroundColor = ConsoleColor.DarkGray;
            Console.WriteLine("KML Converter v1.0 (c) Axfire123, June 2018\r\n");
            Console.ResetColor();



            while (!exit)
            {
                switch (state)
                {
                case -1:        // Reset
                {
                    Console.WriteLine("\r\n\r\n");
                    state = 0;
                    break;
                }

                case 0:     // Dateipfad einlesen
                {
                    // Prüfen, ob beim Programmaufruf eine oder mehrere
                    // Zeichenfolgen übergeben worden sind
                    if ((args.Length == 0) || (argsFertig == true))
                    {
                        Console.WriteLine("Bitte ziehe eine SLP-Datei in das Fenster und bestätige mit Enter\r\n");
                        //Console.ResetColor();
                        file_path_gesamt = Console.ReadLine();
                        if (file_path_gesamt == String.Empty)
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("Es wurde keine Datei ausgewählt!");
                            state = -1;
                        }
                        else
                        {
                            state = 1;
                        }
                    }
                    else
                    {
                        file_path_gesamt = args[0];
                        state            = 1;
                        startWithArgs    = true;
                    }

                    break;
                }

                case 1:     // Untersuche einzulesende Datei
                {
                    dir_path  = getDirFromPath(file_path_gesamt);
                    file_name = getNameFromPath(file_path_gesamt);
                    file_type = getFileTypeFromPath(file_path_gesamt);

                    // püfe auf richtiges Dateiformat
                    if (file_type.ToLower() != "slp")
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("Die gewählte Datei ist vom falschen Typ. Es werden nur .txt Dateien unterstützt!");
                        Console.ResetColor();
                        state = -1;
                    }
                    else
                    {
                        state = 2;
                    }
                    //
                    break;
                }

                case 2:     // Datei einlesen
                {
                    try
                    {
                        // Lese Datei ein
                        for (int i = 0; i < textDatei.getNumberOfLines(file_path_gesamt); i++)
                        {
                            file_lines.Add(textDatei.ReadLine(file_path_gesamt, i + 1));
                        }


                        if (file_lines.Count != 0)
                        {
                            Console.WriteLine("Datei \"{0}.slp\" erfolgreich eingelesen", file_name);
                            state = 6;
                        }
                        else
                        {
                            Console.WriteLine("Aus Datei \"{0}.slp\" konnte keine Zeilen gelesen werden", file_name);
                            state = -1;
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Datei \"{0}.slp\" konnte nicht gelesen werden", file_name);
                        Console.WriteLine(ex.Message);
                        state = -1;
                    }


                    break;
                }

                case 6:     // Typ der SLP-Datei prüfen. Handelt es sich um Tracks oder Points?
                {
                    // In der ersten Zeile der SLP-Datei sollte der Typ stehen
                    if (file_lines[0] == "TYPE=TRACK")
                    {
                        state       = 3;
                        slpFileType = SlpType.Track;
                        Console.WriteLine("TYPE=TRACK in \"{0}.slp\" gefunden", file_name);
                    }
                    else if (file_lines[0] == "TYPE=POINT")
                    {
                        state       = 7;
                        slpFileType = SlpType.Point;
                        Console.WriteLine("TYPE=POINT in \"{0}.slp\" gefunden", file_name);
                    }
                    else
                    {
                        state       = 3;
                        slpFileType = SlpType.Track;
                        Console.WriteLine("Keine Version in \"{0}.slp\" gefunden. Gehe von TYPE=TRACK aus", file_name);
                    }

                    break;
                }

                case 3:     // Version Track: Zeilen der Datei konvertieren und zu Track hinzufuegen
                {
                    double   lat;
                    double   lon;
                    DateTime dateTime;
                    bool     trackAnfang;
                    bool     ersterTrackGefunden = false;

                    int       placemarkNumber = 1;
                    var       track           = new SharpKml.Dom.GX.Track();
                    Placemark placemark       = new Placemark();
                    placemark.Name = "Track " + placemarkNumber;
                    placemark.Open = true;              // Bei Google-Earth das Tree-Menu ausklappen

                    for (int i = 0; i < file_lines.Count; i++)
                    {
                        if (parseLine(file_lines[i], out lat, out lon, out dateTime, out trackAnfang))
                        {
                            // Wurde ein Trackanfang gefunden
                            if (trackAnfang)
                            {
                                // Handel es sich um den ertsen Track der Datei
                                if (ersterTrackGefunden == false)
                                {
                                    // ja => mache nichts
                                    ersterTrackGefunden = true;
                                }
                                else
                                {
                                    // nein => speicher aktuellen Track ab

                                    // hat Track ueberhaupt Inhalt?
                                    if (track.Coordinates.Count() > 0)
                                    {
                                        // Weise Styleselector zu
                                        placemark.StyleUrl = new Uri(String.Format("#{0}", styleSelector.Id), UriKind.Relative);

                                        // Placemark Description
                                        DateTime start = track.When.ElementAt(0);                                 // Hole das Startdatum des Tracks
                                        DateTime ende  = track.When.ElementAt <DateTime>(track.When.Count() - 1); // Hole das Enddatum des Tracks

                                        SharpKml.Dom.Description description = new Description();
                                        description.Text      = String.Format("Start: {0}\nEnde: {1}\nZeit: {2} Minuten", start.ToLongTimeString(), ende.ToLongTimeString(), Convert.ToInt16(ende.Subtract(start).TotalMinutes));
                                        placemark.Description = description;

                                        // Placemark Geometry / Inhalt
                                        placemark.Geometry = track;

                                        // Fuege Track hinzu
                                        root.AddFeature(placemark);

                                        // Placemark Nummer erhoehen
                                        placemarkNumber++;
                                    }

                                    // Neue Instanzen bilden
                                    track          = new SharpKml.Dom.GX.Track();
                                    placemark      = new Placemark();
                                    placemark.Name = "Track " + placemarkNumber;
                                }
                            }
                            else
                            {
                                // speicher Koordinaten-Daten in Track
                                var vector = new Vector(lat, lon);
                                track.AddCoordinate(vector);
                                track.AddWhen(dateTime);
                            }
                        }
                    }

                    // speicher ggf. letzten Track ab
                    if (track.When.Count() > 0)
                    {
                        // Weise Styleselector zu
                        placemark.StyleUrl = new Uri(String.Format("#{0}", styleSelector.Id), UriKind.Relative);

                        // Placemark Description
                        DateTime start = track.When.ElementAt(0);                                 // Hole das Startdatum des Tracks
                        DateTime ende  = track.When.ElementAt <DateTime>(track.When.Count() - 1); // Hole das Enddatum des Tracks

                        SharpKml.Dom.Description description = new Description();
                        description.Text      = String.Format("Start: {0}\nEnde: {1}\nZeit: {2} Minuten", start.ToLongTimeString(), ende.ToLongTimeString(), Convert.ToInt16(ende.Subtract(start).TotalMinutes));
                        placemark.Description = description;

                        // Placemark Geometry / Inhalt
                        placemark.Geometry = track;

                        // Fuege Track hinzu
                        root.AddFeature(placemark);
                    }

                    state = 4;
                    break;
                }


                case 7:     // Type Point: Zeilen der Datei konvertieren und zu Point hinzufuegen
                {
                    double   lat;
                    double   lon;
                    DateTime dateTime;
                    bool     trackAnfang;               // Auch wenn es beim Poit keinen Trackanfang gibt, wird die Variabel fuer die Funktion gebraucht

                    int placemarkNumber = 1;



                    for (int i = 0; i < file_lines.Count; i++)
                    {
                        if (parseLine(file_lines[i], out lat, out lon, out dateTime, out trackAnfang))
                        {
                            // Wurde ein Trackanfang gefunden
                            if (trackAnfang)
                            {
                                continue;           // es gibt beim Point keinen Trackanfang...
                            }
                            else
                            {
                                var       point     = new SharpKml.Dom.Point();
                                Placemark placemark = new Placemark();
                                placemark.Name = "Point " + placemarkNumber++;
                                placemark.Open = true;              // Bei Google-Earth das Tree-Menu ausklappen

                                // Speicher Daten in Point
                                Vector vector = new Vector(lat, lon);
                                point.Coordinate = vector;

                                // Erzeuge Placemark-Beschreibung
                                SharpKml.Dom.Description description = new Description();
                                description.Text      = String.Format("Datum: {0}\nUhrzeit: {1}", dateTime.ToLongDateString(), dateTime.ToLongTimeString());
                                placemark.Description = description;
                                // Fuege den Point dem Placemark hinzu
                                placemark.Geometry = point;

                                // Fuege den Placemark dem Dokument hinzu
                                root.AddFeature(placemark);
                            }
                        }
                    }

                    state = 4;
                    break;
                }

                case 4:     // KML-File erstellen
                {
                    KmlFile kml = KmlFile.Create(root, false);

                    try
                    {
                        String kmlDirPath = dir_path + dir_kml;                                 // Pfad zum Verzeichnis

                        // KML-File Name
                        // konvertiere den "yyMMdd" Namen der SLP-Datei in das besser lesbare "yy-MM-dd" Format
                        String kml_file_name = String.Empty;
                        try
                        {
                            DateTime dateTime = DateTime.ParseExact(file_name, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);
                            kml_file_name = dateTime.ToString("yyyy-MM-dd");
                        }
                        catch
                        {
                            kml_file_name = file_name;
                        }
                        //

                        // SLP-Typ als Name anhaengen
                        if (slpFileType == SlpType.Track)
                        {
                            kml_file_name += " Track";
                        }
                        else if (slpFileType == SlpType.Point)
                        {
                            kml_file_name += " Point";
                        }

                        String kmlFilePath = kmlDirPath + "\\" + kml_file_name + ".kml";            // Pfad zur Datei

                        // Directory erzeugen, falls nicht vorhanden
                        if (!Directory.Exists(kmlDirPath))
                        {
                            Directory.CreateDirectory(kmlDirPath);
                        }

                        // Speicher
                        using (FileStream stream = File.OpenWrite(kmlFilePath))
                        {
                            kml.Save(stream);
                        }
                        Console.WriteLine("KML-Datei \"{0}.kml\" wurde erfolgreich gespeichert", file_name);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("KML-Datei \"{0}.kml\" konnte nicht gespeichert werden", file_name);
                        Console.WriteLine(ex.Message);
                    }

                    root      = new Document();
                    root.Open = true;               // Bei Google-Earth das Tree-Menu ausklappen

                    state = 5;
                    break;
                }

                case 5:     // Wie gehts weiter?

                    if (startWithArgs)
                    {
                        exit = true;
                        // warte x Sekunden, bis Programm geschlossen wird
                        Console.Write("Programm wird beendet ");
                        System.Threading.Thread.Sleep(100);
                        Console.Write(".");
                        System.Threading.Thread.Sleep(100);
                        Console.Write(".");
                        System.Threading.Thread.Sleep(100);
                        Console.Write(".");
                        System.Threading.Thread.Sleep(100);
                        Console.Write(".");
                        System.Threading.Thread.Sleep(100);
                        Console.Write(".");
                        System.Threading.Thread.Sleep(100);
                        Console.Write(".");
                        System.Threading.Thread.Sleep(100);
                        Console.Write(".");
                        System.Threading.Thread.Sleep(100);
                        Console.Write("\r\nBey!");
                        System.Threading.Thread.Sleep(500);
                    }
                    else
                    {
                        state = -1;
                    }
                    break;
                }
            }
        }
Пример #20
0
        public static string getKMLstring(Color lapColor,
                                          List <double> latitudes,
                                          List <double> longitudes,
                                          List <double> altitudes = null)
        {
            // make sure the parameters are of the same length
            if (((altitudes != null) && !(latitudes.Count == longitudes.Count && altitudes.Count == longitudes.Count)) ||
                !(latitudes.Count == longitudes.Count))
            {
                throw new Exception("The length of the parameters must match");
            }

            // Create the KML stuff
            Kml kml = new Kml();

            kml.AddNamespacePrefix("gx", "http://www.google.com/kml/ext/2.2");
            Document   doc   = new Document();
            Style      style = new Style();
            Placemark  pMark = new Placemark();
            LineString ls    = new LineString();

            ls.Coordinates = new CoordinateCollection();

            // Define the style
            style.Line       = new LineStyle();
            style.Id         = "redline";
            style.Line.Color = new Color32(lapColor.A, lapColor.B, lapColor.G, lapColor.R);
            //style.Line.ColorMode = ColorMode.Normal;
            style.Line.Width = 2;

            // Define a new style
            Style style2 = new Style();

            style2.Line       = new LineStyle();
            style2.Id         = "blueline";
            style2.Line.Color = new Color32(Colors.LightBlue.A, Colors.LightBlue.B, Colors.LightBlue.G, Colors.LightBlue.R);
            //style2.Line.ColorMode = ColorMode.Normal;
            style2.Line.Width = 2;

            // add style to placemark
            pMark.StyleUrl = new Uri("#redline", UriKind.Relative);

            // loop through the lines in the file
            if (altitudes != null)
            {
                ls.AltitudeMode = AltitudeMode.Absolute;
                for (int i = 0; i < latitudes.Count; i++)
                {
                    ls.Coordinates.Add(new Vector(latitudes[i], longitudes[i], altitudes[i]));
                }
            }
            else // no altitude provided
            {
                for (int i = 0; i < latitudes.Count; i++)
                {
                    ls.Coordinates.Add(new Vector(latitudes[i], longitudes[i]));
                }
            }

            // Set properties on the line string
            ls.Extrude    = false;
            ls.Tessellate = true;

            // Add the line string to the placemark
            pMark.Geometry = ls;

            // Generate a LookAt object to center the view on the placemark
            doc.Viewpoint = pMark.CalculateLookAt();

            // Add the placemark and style to the document
            doc.AddFeature(pMark);
            doc.AddStyle(style);
            doc.AddStyle(style2);

            // Add the document to the kml object
            kml.Feature = doc;

            // Create the KML file
            KmlFile kmlFile = KmlFile.Create(kml, false);

            //TODO for debugging purposes, save the kml file to test folder.
            kmlFile.Save("test.kml");

            // Return the KML file as a string
            return(kmlFile.SaveString());
        }
Пример #21
0
 public static void SaveEntry(KmlFile kml, string name, string filePath)
 {
     kml.Save(filePath);
 }