/// <summary>
        /// Parses the raw KML Data file returned by the inReach service and produces live
        /// waypoint data.
        /// </summary>
        /// <param name="stream">stream to read kml from</param>
        /// <param name="mapShareIdentifier">MapShare identifier used for request</param>
        /// <returns>live waypoint data</returns>
        internal LiveWaypointData ParseRawKmlDataFile(Stream stream, string mapShareIdentifier)
        {
            var file = KmlFile.Load(stream);

            var placemark = file.Root.Flatten().First(x => x is Placemark) as Placemark;

            if (placemark == null)
            {
                throw new FormatException("Garmin inReach Raw KML Data contains no Placemark");
            }

            var point = placemark.Geometry as Point;

            var when = (placemark.Time as Timestamp).When;

            if (when.HasValue)
            {
                this.lastRequestByMapShareIdentifier[mapShareIdentifier] = new DateTimeOffset(when.Value);
            }

            return(new LiveWaypointData
            {
                ID = FormatLiveWaypointId(mapShareIdentifier),
                Name = "Garmin inReach " + placemark.Name,
                Latitude = point.Coordinate.Latitude,
                Longitude = point.Coordinate.Longitude,
                Altitude = (int)(point.Coordinate.Altitude ?? 0.0),
                TimeStamp = when.HasValue ? new DateTimeOffset(when.Value) : DateTimeOffset.Now,
                Description = FormatDescriptionFromPlacemark(placemark),
                DetailsLink = string.Format(MapSharePublicUrl, mapShareIdentifier),
            });
        }
        public List <PostImport.ExcelPost> LesInn(byte[] content)
        {
            var poster = new List <PostImport.ExcelPost>();

            var kml = KmlFile.Load(new MemoryStream(content));

            var root     = (SharpKml.Dom.Kml)kml.Root;
            var document = (Document)root.Feature;

            foreach (var folder in document.Features.OfType <Folder>())
            {
                foreach (var placemark in folder.Features.OfType <Placemark>())
                {
                    var name        = placemark.Name;
                    var description = placemark.Description;
                    var point       = placemark.Geometry as Point;
                    var coordinates = point?.Coordinate ?? new Vector();
                    var image       = placemark.ExtendedData?.Data?.FirstOrDefault()?.Value;
                    var post        = KonverterTilExcelPost(name, description, coordinates, image, document.Name);
                    poster.Add(post);
                }
            }

            return(poster);
        }
示例#3
0
        static void LoadFile()
        {
            FileStream fs;
            KmlFile    file = null;

            Console.WriteLine("Enter KML filepath:");
            try
            {
                fs   = File.OpenRead(Console.ReadLine());
                file = KmlFile.Load(fs);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.Write("Retry/Exit (r/x)? ");
                if (Console.ReadKey().KeyChar == 'r')
                {
                    Console.WriteLine();
                    LoadFile();
                    return;
                }
                else
                {
                    Environment.Exit(0);
                }
            }

            kmlFile = file;
        }
示例#4
0
        public static KmlFile Load(string filename)
        {
            TextReader reader = File.OpenText(filename);
            KmlFile    file   = KmlFile.Load(reader);

            return(file);
        }
示例#5
0
        public void ShouldFindAllTheLinkTypesInTheKmlFile()
        {
            // Verify that GetLinks finds all kinds of hrefs in a KML file.
            string[] expected =
            {
                "http://example.com/icon.jpg",
                "itemicon.png",
                "../more.kml",
                "go.jpeg",
                "so.jpeg",
                "po.jpeg",
                "#myschema",
                "model.dae",
                "style.kml#style"
            };

            using (var stream = SampleData.CreateStream("Engine.Data.Links.kml"))
                using (var reader = new StreamReader(stream))
                {
                    var resolver = new LinkResolver(KmlFile.Load(reader));

                    IEnumerable <string> links = resolver.Links.Select(u => u.OriginalString);

                    Assert.That(links, Is.EquivalentTo(expected));
                }
        }
示例#6
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);
            }
        }
示例#7
0
 private static KmlFile LoadKml(string path)
 {
     using (Stream file = File.OpenRead(path))
     {
         return(KmlFile.Load(file));
     }
 }
示例#8
0
        public static KmlFile OpenFile(string prompt)
        {
            string filename = GetInputFile(prompt, "Data/20191114.kml");

            KmlFile file;

            try
            {
                using (FileStream stream = File.Open(filename, FileMode.Open))
                {
                    file = KmlFile.Load(stream);
                }
            }
            catch (Exception ex)
            {
                DisplayError(ex.GetType() + "\n" + ex.Message);
                return(null);
            }

            if (file.Root == null)
            {
                DisplayError("Unable to find any recognized Kml in the specified file.");
                return(null);
            }
            return(file);
        }
示例#9
0
        public void TestAltMarkupData()
        {
            using (var stream = SampleData.CreateStream("Engine.Data.Entity Data.kml"))
            {
                KmlFile   file      = KmlFile.Load(stream);
                Placemark placemark = file.Root as Placemark;
                Assert.That(placemark, Is.Not.Null);

                EntityMapper mapper = new EntityMapper(file);
                mapper.ParseEntityFields(placemark);

                Assert.That(mapper.Entities.Count, Is.EqualTo(6));
                for (int i = 0; i < 4; ++i)
                {
                    Assert.That(mapper.Markup[i], Is.EqualTo(AltMarkup[i]));
                }

                // Assert that a second parse produces the same result (this
                // is different to the C++ version, which clears the Entities
                // but adds to the Markup - we reset both.
                mapper.ParseEntityFields(placemark);
                Assert.That(mapper.Entities.Count, Is.EqualTo(6));
                Assert.That(mapper.Markup.Count, Is.EqualTo(4));
            }
        }
示例#10
0
        /// <summary>
        /// Creates a new KML data file from stream
        /// </summary>
        /// <param name="stream">stream to read from</param>
        /// <param name="isKml">indicates if stream contains a kml or a kmz file</param>
        public KmlDataFile(Stream stream, bool isKml)
        {
            if (isKml)
            {
                using (var reader = new StreamReader(stream))
                {
                    this.kml = KmlFile.Load(reader);

                    if (this.kml.Root == null &&
                        stream.CanSeek)
                    {
                        stream.Seek(0, SeekOrigin.Begin);

                        this.kml = this.ReadLegacyKmlStream(stream, isKml);
                    }
                }
            }
            else
            {
                var kmz = KmzFile.Open(stream);
                this.kml = kmz.GetDefaultKmlFile();
            }

            if (this.kml != null)
            {
                this.ScanKml();
            }
        }
示例#11
0
 /// <summary>
 /// Loads a .kml file from stream
 /// </summary>
 /// <param name="kmlStream">stream containing a .kml file</param>
 public void Load(Stream kmlStream)
 {
     using (var reader = new StreamReader(kmlStream))
     {
         var kml = KmlFile.Load(reader);
         this.ParseKmlFile(kml);
     }
 }
        void LoadSiteAndInstrumentsData()
        {
            Sites.Clear();
            InsTypes.Clear();

            using (FileStream fs = new FileStream(InputGeoPath, FileMode.Open))
            {
                var kmlF = KmlFile.Load(fs);
                var kmlR = kmlF.Root as Kml;
                if (kmlR != null)
                {
                    var container    = kmlR.Feature as Container;
                    var siteFeatures = container.Features;

                    foreach (var siteFeature in siteFeatures)
                    {
                        var siteFolder = siteFeature as Folder;
                        var gmSite     = new GMSite(siteFolder.Name);

                        foreach (var pt in siteFolder.Features)
                        {
                            var place = pt as Placemark;

                            var placeGeo = place.Geometry as SharpKml.Dom.Point;

                            // Console.WriteLine(siteFeature.Name + " - " + place.Name);
                            string placeName = place.Name;
                            if (placeName.StartsWith("*"))
                            {
                                // placeName.Substring(1);
                                gmSite.Latitude  = placeGeo.Coordinate.Latitude;
                                gmSite.Longitude = placeGeo.Coordinate.Longitude;
                            }
                            else
                            {
                                int idxLeft  = placeName.IndexOf('[');
                                int idxRight = placeName.IndexOf(']');

                                string insTypeName = placeName.Substring(idxLeft + 1, idxRight - idxLeft - 1);
                                string insName     = placeName.Substring(idxRight + 1, placeName.Length - idxRight - 1);
                                if (!InsTypes.ContainsKey(insTypeName))
                                {
                                    InsTypes.Add(insTypeName, new GMInstrumentType(insTypeName));
                                }

                                var gmIns = new GMInstrument(insName, placeGeo.Coordinate.Longitude, placeGeo.Coordinate.Latitude,
                                                             InsTypes[insTypeName]);
                                gmSite.Instruments.Add(gmIns);
                            }

                            ResultLog += siteFeature.Name + " - " + place.Name + "\r\n";
                        }

                        Sites.Add(gmSite);
                    }
                }
            }
        }
示例#13
0
        public void track_from_ge()
        {
            using (var stream = new FileStream(@"C:\Dev\replay\Dev\Src\Plugins\KmlPlugin\TestData\TimeSpan_example\doc.kml", FileMode.Open))
            {
                var kml = KmlFile.Load(stream);

                Assert.That(kml.Root, Is.Not.Null);
            }
        }
示例#14
0
        /// <summary>
        /// Creates a KmlProvider from a Kml stream
        /// </summary>
        /// <param name="stream">The stream to read from</param>
        /// <exception cref="ArgumentNullException"></exception>
        public static KmlProvider FromKml(Stream stream)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

            return(new KmlProvider(KmlFile.Load(stream)));
        }
示例#15
0
        public static KmlFile GetKmlEntryFromKmlFile(string kmlFile)
        {
            string compatibleXml = GetCompatibleXml(new StreamReader(kmlFile).ReadToEnd());

            using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(compatibleXml)))
            {
                return(KmlFile.Load(stream));
            }
        }
示例#16
0
        /// <summary>
        /// Creates a KmlProvider from a Kml stream
        /// </summary>
        /// <param name="stream">The stream to read from</param>
        /// <param name="stylesOnly">True to skip geometries and read styles only</param>
        /// <exception cref="ArgumentNullException"></exception>
        public static KmlProvider FromKml(Stream stream, bool stylesOnly = false)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

            return(new KmlProvider(KmlFile.Load(stream), stylesOnly, GetFileStreamPath(stream)));
        }
示例#17
0
        public static Kml Parse(string filePath)
        {
            KmlFile file = KmlFile.Load(filePath);
            Kml     kml  = file.Root as Kml;

            if (kml == null)
            {
                throw new Exception("Could not parse file into KML. If this is a KMZ, unzip it first!");
            }
            return(kml);
        }
示例#18
0
 public void should_load_track_geometry()
 {
     using (var stream = SampleData.CreateStream("Engine.Data.Tracks.kml"))
     {
         KmlFile file      = KmlFile.Load(stream);
         var     placemark = file.FindObject("geoffrey") as Placemark;
         var     track     = placemark.Geometry as Track;
         Assert.That(track, Is.Not.Null);
         Assert.That(track.When.Count(), Is.EqualTo(track.Coordinates.Count()));
     }
 }
        internal static Kml Parse(Stream fileStream)
        {
            KmlFile file = KmlFile.Load(fileStream);
            Kml     kml  = file.Root as Kml;

            if (kml == null)
            {
                throw new Exception("Could not parse file into KML. If this is a KMZ, unzip it first!");
            }
            return(kml);
        }
        public void should_load_kmls_even_when_the_namespace_is_wrong()
        {
            using (var stream = SampleData.CreateStream("Engine.Data.OverlayBadNamespace.kml"))
            {
                KmlFile file = KmlFile.Load(stream);
                Assert.That(file.Root, Is.Not.Null);

                var featureCount = ((Container)((Kml)file.Root).Feature).Features.Count();
                Assert.That(featureCount, Is.EqualTo(12));
            }
        }
示例#21
0
        private static async Task <BusService> GetServiceFromKml(string filePath)
        {
            using (var reader = File.OpenText(filePath))
            {
                var kml      = KmlFile.Load(reader);
                var nodes    = kml.Root.Flatten();
                var document = nodes.OfType <Document>().Single();

                var routes    = new List <Route>();
                var landmarks = new List <PlaceDetail>();

                var placemarks = nodes.OfType <Placemark>();
                foreach (var placemark in placemarks)
                {
                    var geometries = placemark.Geometry.Flatten().ToLookup(geometry => geometry.GetType());

                    foreach (LineString line in geometries[typeof(LineString)])
                    {
                        var coordinates = line.Coordinates.Select(pair => new Coordinate(pair.Latitude, pair.Longitude));
                        var snapped     = await GMapsClient.SnapToRoadsAsync(coordinates);

                        var placeIds = snapped.Select(snappedPlace => snappedPlace.PlaceId).Distinct();

                        var places = await Task.WhenAll(
                            placeIds.Select(id => GMapsClient.GetPlaceDetailAsync(id))
                            );

                        var route = new Route
                        {
                            Name   = placemark.Name,
                            Places = places,
                        };

                        routes.Append(route);
                    }

                    foreach (Point point in geometries[typeof(Point)])
                    {
                        // TODO get place id from coordinate?
                        // Could just use embedded info.
                    }
                }

                var service = new BusService
                {
                    Name      = document.Name,
                    Routes    = routes,
                    Landmarks = landmarks,
                };

                return(service);
            }
        }
示例#22
0
        public void TestUpdateOperations()
        {
            using (Stream stream = SampleData.CreateStream("Engine.Data.Update.kml"))
            {
                var file = KmlFile.Load(stream);

                foreach (TestCase test in TestCases)
                {
                    RunTestCase(test, file);
                }
            }
        }
示例#23
0
        /// <summary>
        /// Creates a KmlProvider from a Kml stream
        /// </summary>
        /// <param name="stream">The stream to read from</param>
        /// <exception cref="ArgumentNullException"></exception>
        public static KmlProvider FromKml(Stream stream)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

            var kml = new KmlProvider(KmlFile.Load(stream));

            //kml.InitIds();
            return(kml);
        }
示例#24
0
        public KmlDocument(String data)
        {
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(data));

            kf = KmlFile.Load(ms);
            Kml      kml = kf.Root as Kml;
            Document doc = kml?.Flatten().OfType <Document>().FirstOrDefault();

            if (doc != null)
            {
                _documentDescription = (doc.Description != null) ? doc.Description.Text : "";
            }
        }
        private void OnLoadAllFilesClick(object sender, RoutedEventArgs e)
        {
            #region Loading KML files

            try
            {
                DirectoryInfo di    = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Kmz\data\kml");
                FileInfo[]    files = di.GetFiles("*.kml");
                foreach (FileInfo file in files)
                {
                    KmlFile kmlFile;
                    try
                    {
                        kmlFile = KmlFile.Load(file.Open(FileMode.Open));
                        AddToList(kmlFile);
                    }
                    catch
                    {
                    }
                }
            }
            catch
            {
            }

            #endregion Loading KML files

            #region Loading sections

            try
            {
                DirectoryInfo di    = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Kmz\data\sections");
                FileInfo[]    files = di.GetFiles("*.jpg");
                foreach (FileInfo file in files)
                {
                    Section section = new Section();
                    try
                    {
                        section.Image = Bitmap.FromStream(file.Open(FileMode.Open)) as Bitmap;
                        section.Name  = file.Name;
                        AddToList(section);
                    }
                    catch
                    {
                    }
                }
            }
            catch
            { }
            #endregion Loading sections
        }
        void ofd_FileOkSelectKML(object sender, CancelEventArgs e)
        {
            AirNavigationRaceLiveMain.SetStatusText("");

            RoutePoints      = new List <Vector>();
            ListOfRoutes     = new List <List <Vector> >();
            ListOfRouteNames = new List <string>();
            ListOfNBL        = new List <List <Vector> >();
            ListOfNBLNames   = new List <string>();

            treeViewAvailableRoutes.Nodes.Clear();
            OpenFileDialog ofd   = sender as OpenFileDialog;
            string         fName = ofd.FileName;

            FileNameKML = ofd.FileName;

            if (fName == string.Empty)
            {
                return;
            }

            KmlFile file;

            try
            {
                using (FileStream stream = File.Open(fName, FileMode.Open))
                {
                    file = KmlFile.Load(stream);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }


            if ((file != null) && (file.Root != null))
            {
                Kml      kml = file.Root as Kml;
                TreeView trv = treeViewAvailableRoutes;
                ExtractPlaceMarkLineStrings(kml.Feature, trv);
                btnAddRoute.Visible            = true;
                chkAddAllRoutes.Visible        = true;
                lblSelectedRoutes.Visible      = true;
                btnClearSelectedRoutes.Visible = true;
                treeViewSelectedRoutes.Visible = true;
            }
            AirNavigationRaceLiveMain.SetStatusText(string.Format("Route Generator - loaded file {0}", ofd.FileName));
        }
        /// <summary>
        /// Creates a KmlProvider from a Kmz stream
        /// </summary>
        /// <param name="stream">The stream to read from</param>
        /// <param name="internalFile">The internal file to read</param>
        /// <exception cref="ArgumentNullException"></exception>
        public static KmlProvider FromKmz(Stream stream, string internalFile = null)
        {
            var kmz = KmzFile.Open(stream);

            if (string.IsNullOrEmpty(internalFile))
            {
                return(new KmlProvider(kmz.GetDefaultKmlFile()));
            }

            //NOTE:DON'T KNOW IF THIS IS CORRECT!
            using (var ms = new MemoryStream(kmz.ReadFile(internalFile)))
            {
                return(new KmlProvider(KmlFile.Load(ms)));
            }
        }
示例#28
0
        /// <summary>
        /// Creates a KmlProvider from a Kmz stream
        /// </summary>
        /// <param name="stream">The stream to read from</param>
        /// <param name="internalFile">The internal file to read, or null for default kml document</param>
        /// <param name="stylesOnly">True to skip geometries and read styles only</param>
        /// <exception cref="ArgumentNullException"></exception>
        public static KmlProvider FromKmz(Stream stream, string internalFile = null, bool stylesOnly = false)
        {
            var kmz = KmzFile.Open(stream);

            if (string.IsNullOrEmpty(internalFile))
            {
                // typically doc.kml, but sometimes kmzFileNameBase.kml
                return(new KmlProvider(kmz.GetDefaultKmlFile(), stylesOnly, GetFileStreamPath(stream)));
            }
            else
            {
                using (var ms = new MemoryStream(kmz.ReadFile(internalFile)))
                    return(new KmlProvider(KmlFile.Load(ms), stylesOnly, GetFileStreamPath(stream)));
            }
        }
        public IEnumerable <Placemark> GetSportData()
        {
            const string cacheKey = "SportData";

            return(_cache.Get(cacheKey, () =>
            {
                var stream = File.OpenRead(OpenDataPath.SportFiltered);
                var file = KmlFile.Load(stream);
                stream.Close();
                var document = file.Root as Document;
                var result = document.Flatten().OfType <Placemark>().ToList();
                _cache.Set(cacheKey, result);
                return result;
            }));
        }
        public IEnumerable <Placemark> GetHospitalDataById(int id)
        {
            string cacheKey = $"HospitalData_{id}";

            return(_cache.Get(cacheKey, () =>
            {
                var stream = File.OpenRead(OpenDataPath.HospitalEmptyFiltered);
                var file = KmlFile.Load(stream);
                stream.Close();
                var document = file.Root as Document;
                var result = document.Flatten().OfType <Placemark>()
                             .Where(p => p.TargetId.Split(',').Contains(id.ToString())).ToList();
                _cache.Set(cacheKey, result);
                return result;
            }));
        }