Exemple #1
0
        public void KmlReadTestv2_0_response()
        {
            // instantiate and load the gpx test document.
            XmlStreamSource source = new XmlStreamSource(
                Assembly.GetExecutingAssembly().GetManifestResourceStream("OsmSharp.Test.Unittests.test.v2.0.response.kml"));
            KmlDocument document = new KmlDocument(source);
            object kml = document.Kml;

            if (kml is OsmSharp.IO.Xml.Kml.v2_0_response.kml)
            { // all ok here!
                OsmSharp.IO.Xml.Kml.v2_0_response.kml kml_type = (kml as OsmSharp.IO.Xml.Kml.v2_0_response.kml);

                // test the gpx test file content.
                Assert.IsNotNull(kml_type.Item, "No item was found!");
                Assert.IsInstanceOf<OsmSharp.IO.Xml.Kml.v2_0_response.Response>(kml_type.Item, "Incorrect item type!");

                OsmSharp.IO.Xml.Kml.v2_0_response.Response type = (kml_type.Item as OsmSharp.IO.Xml.Kml.v2_0_response.Response);
                Assert.AreEqual(type.Items.Length, 8, "Incorrect number of items in response!");
            }
            else
            {
                Assert.Fail("No kml data was read, or data was of the incorrect type!");
            }

            document.Close();
            source.Close();
        }
        public Form1()
        {
            InitializeComponent();

            KmlDocument kdoc = new KmlDocument();
            kdoc.LoadFromFile("Test.kml");

            KmlNodeCollection nodeCollection = kdoc.SelectNodes("item");
            int i = 0;
            int errors = 0;
            DateTime start = DateTime.Now;
            foreach (KmlNode knode in nodeCollection)
            {
                i++;
                try
                {
                    textBox1.AppendText(knode.SelectSingleNode("Index").Values[1] + "\r\n");
                    //textBox1.AppendText(knode.Values[1] + "\n");
                    //textBox1.AppendText(knode.ToString() + "\r\n");
                    // MessageBox.Show(knode.ToString());
                }
                catch (Exception)
                {
                    errors++;
                }
            }
               // textBox1.Text = kdoc.ToString();
            DateTime end = DateTime.Now;
            TimeSpan span = end - start;
            MessageBox.Show("Read and re-generated " + i + " items with " + errors + " errors in " + span.TotalSeconds + " seconds.");
            //MessageBox.Show(kdoc.RootNode.ToString());
        }
Exemple #3
0
        private void CalculateImageAndTransformationMatrix(string fileName)
        {
            var zipFile = new Ionic.Zip.ZipFile(fileName);
              var mapSize = new Size();
              Transformation = new Transformation();

              // get entry for kml file and image file
              KmlDocument kmlDocument = null;
              foreach (var entry in zipFile)
              {
            if (entry.FileName == entry.LocalFileName && Path.GetExtension(entry.FileName) == ".kml")
            {
              using (var kmlStream = new MemoryStream())
              {
            entry.Extract(kmlStream);
            kmlStream.Position = 0;
            kmlDocument = new KmlDocument(kmlStream);
              }
              break;
            }
              }

              if (kmlDocument != null)
              {
            // we have got a kml document, get map image file stream from it
            foreach (var entry in zipFile)
            {
              if (entry.FileName == kmlDocument.ImageFileName)
              {
            ImageStream = new MemoryStream();
            entry.Extract(ImageStream);
            ImageStream.Position = 0;
            // check if image is QR jpeg
            var ed = QuickRouteJpegExtensionData.FromStream(ImageStream);
            if(ed != null)
            {
              // get transformation matrix from QR jpeg metadata
              Transformation = ed.Sessions.CalculateAverageTransformation();
              ImageStream.Position = 0;
              return;
            }
            else
            {
              // it is not, use normal image bounds
              ImageStream.Position = 0;
              mapSize = Image.FromStream(ImageStream).Size; // need to get image object to get image size
            }
            ImageStream.Position = 0;
            break;
              }
            }
              }

              if (kmlDocument != null && ImageStream != null)
              {
            // finally, calculate the transformation
            Transformation = new Transformation(kmlDocument.LongLatBox, mapSize);
              }
        }
Exemple #4
0
        public static void LoadConfigFiles(string Directory)
        {
            configKml = new KmlDocument();

            ServerConsole.WriteLine("Loading config files");

            //get directory info
            DirectoryInfo di = new DirectoryInfo(Directory);
            //cycle each file inside
            foreach (FileInfo fi in di.GetFiles())
            {
                //load into kdoc
                configKml.LoadFromFile(fi.FullName);
                ServerConsole.WriteLine("Loading config: {0}", MessageLevel.Message, fi.Name);
            }
        }
        public KmlDocument Create(string content)
        {
            var xdoc  = XDocument.Parse(content, LoadOptions.None);
            var xroot = xdoc.Root.ElementByLocalName("Document");

            var model = new KmlDocument {
                Title       = xroot.ElementByLocalName("name").Value,
                Description = xroot.ElementByLocalName("description")?.Value
            };

            foreach (var xfolder in xroot.ElementsByLocalName("Folder"))
            {
                model.Folders.Add(CreateKmlFolder(xfolder));
            }

            return(model);
        }
        public async Task When_going_next_and_placemarks_arent_available_then_false_is_returned()
        {
            // Arrange
            var kmlDocument = new KmlDocument
            {
                Folders =
                {
                    new KmlFolder(new[]  {
                        new KmlPlacemark {
                            Name = "pm-1"
                        }
                    }
                                  )
                }
            };
            var vm = new StepPickViewModel
            {
                KmlObjectsTree =
                {
                    FoldersToInclude        =
                    {
                        new KmlFolderNodeViewModel(kmlDocument.Folders[0])
                        {
                            Enabled  = true,
                            Children =
                            {
                                new KmlPlacemarkNodeViewModel(kmlDocument.Folders[0].Placemarks[0], null)
                                {
                                    Enabled = false
                                }
                            }
                        }
                    }
                }
            };

            _presenter.SetupGet(x => x.ViewModel).Returns(vm);
            _presenter.Object.SetDocument(kmlDocument);
            _userSessionMock.SetupProperty(x => x.Document);

            // Act
            var result = await _presenter.Object.BeforeGoNext();

            // Verify
            Assert.IsFalse(result);
        }
        public async Task <List <DiscoveredPlace> > Discover(KmlDocument document, string language, IDiscoveringProgress progressTracker, CancellationToken cancellationToken)
        {
            var placemarks = document.Folders.Where(x => !x.ContainsRoute).SelectMany(x => x.Placemarks).ToList();

            const int loopsCount = 3;

            progressTracker.ReportNumberOfIterations(placemarks.Count * loopsCount);

            var hereTask       = DiscoverOnHere(placemarks, language, progressTracker, cancellationToken);
            var foursquareTask = DiscoverOnFoursquare(placemarks, language, progressTracker, cancellationToken);

            var result = await Task.WhenAll(hereTask, foursquareTask);

            progressTracker.ReportDone();

            return(result.SelectMany(x => x).ToList());
        }
Exemple #8
0
        public static KmlDocument createKmlTracks(ArrayList trks)
        {
            KmlDocument kmlDoc = new KmlDocument("Selected Track" + (trks.Count > 1 ? "s" : (": " + ((Track)trks[0]).Name)), 1);

            KmlFolder waypointsFolder = kmlDoc.CreateFolder("Waypoints");

            KmlFolder tracksFolder = kmlDoc.CreateFolder("Tracks");

            foreach (Track trk in trks)
            {
                KmlTrack kTrack = new KmlTrack(tracksFolder, trk);
            }

            kmlDoc.CreateAbout();

            return(kmlDoc);
        }
Exemple #9
0
        public static void LoadConfigFiles(string Directory)
        {
            configKml = new KmlDocument();

            ServerConsole.WriteLine("Loading config files");

            //get directory info
            DirectoryInfo di = new DirectoryInfo(Directory);

            //cycle each file inside
            foreach (FileInfo fi in di.GetFiles())
            {
                //load into kdoc
                configKml.LoadFromFile(fi.FullName);
                ServerConsole.WriteLine("Loading config: {0}", MessageLevel.Message, fi.Name);
            }
        }
        public async Task When_step_is_activated_with_url_provided_the_kml_is_downloaded_and_readed()
        {
            // Arrange
            var folderPrefix = "folder-prefix";
            var kmlDocument  = new KmlDocument();
            var vm           = SetupForActivatedMethod(kmlDocument);

            _resourceNameMock.Setup(x => x.GetTempFolderPrefix()).Returns(folderPrefix);

            // Act
            await _presenter.Object.Activated();

            // Verify
            _webClientkMock.Verify(x => x.GetAsync(new Uri(DEFAULT_KML_URL)), Times.Once);
            Assert.IsTrue(Regex.IsMatch(vm.InputFileName,
                                        $@"{Path.GetTempPath().Replace(@"\", @"\\")}{folderPrefix}[\w\-]{{36}}\.kmz"));
            _kmlObjectsTreePresenterMock.Verify(x => x.HandleActivated(kmlDocument, It.IsAny <CancellationToken>()));
        }
        public async Task Discover_processes_only_folders_without_routes()
        {
            // Arrange
            const int loopsCount = 3;
            var       document   = new KmlDocument {
                Folders =
                {
                    new KmlFolder(new [] { CreateSamplePlacemark()  }),
                    new KmlFolder(new [] { CreateSamplePlacemark()  }),
                    new KmlFolder(new [] { CreateSamplePlacemark(2) })
                }
            };
            var placemarksToBeProcessed = document.Folders.Take(2).SelectMany(f => f.Placemarks).ToList();
            var hereDiscovered          = new List <DiscoveredPlace> {
                new DiscoveredPlace {
                    Venue = new HereVenue {
                        Id = "here1"
                    }
                }
            };
            var foursquareDiscovered = new List <DiscoveredPlace> {
                new DiscoveredPlace {
                    Venue = new FoursquareVenue {
                        Id = "4sq1"
                    }
                }
            };

            _service.Setup(x => x.DiscoverOnHere(placemarksToBeProcessed,
                                                 DEFAULT_LANGUAGE, _progressTrackerMock.Object, _cancel))
            .Returns(Task.FromResult(hereDiscovered));
            _service.Setup(x => x.DiscoverOnFoursquare(placemarksToBeProcessed,
                                                       DEFAULT_LANGUAGE, _progressTrackerMock.Object, _cancel))
            .Returns(Task.FromResult(foursquareDiscovered));

            // Act
            var result = await _service.Object.Discover(document, DEFAULT_LANGUAGE, _progressTrackerMock.Object, _cancel);

            // Verify
            _progressTrackerMock.Verify(x => x.ReportNumberOfIterations(placemarksToBeProcessed.Count * loopsCount));
            Assert.AreEqual(hereDiscovered[0], result[0]);
            Assert.AreEqual(foursquareDiscovered[0], result[1]);
        }
Exemple #12
0
 private void ReadKmlDocumentIntoViewModel(KmlDocument document)
 {
     ViewModel.FoldersToInclude.Clear();
     foreach (var folder in document.Folders)
     {
         var isRoute  = _kmlCalculator.CompleteFolderIsRoute(folder);
         var folderVm = new KmlFolderNodeViewModel(folder)
         {
             Enabled = true, IsPartOfRoute = isRoute
         };
         foreach (var placemark in folder.Placemarks)
         {
             folderVm.Children.Add(new KmlPlacemarkNodeViewModel(placemark, folderVm)
             {
                 Enabled       = true,
                 IsPartOfRoute = isRoute
             });
         }
         ViewModel.FoldersToInclude.Add(folderVm);
     }
 }
        private void ImportFromKmlFile(NavigationEventArgs e)
        {
            KmlDocument      kd             = e.Parameter as KmlDocument;
            List <Folder>    folderNodes    = kd.GetFolders();
            List <Placemark> placemarkNodes = kd.GetPlacemarks(folderNodes[0]);

            foreach (var placemarkNode in placemarkNodes)
            {
                try
                {
                    if (!KmlDocument.IsRoutePlacemark(placemarkNode))
                    {
                        Point p = kd.GetPoint(placemarkNode);
                        _appState.Points.Add(p);
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.StackTrace);
                }
            }
        }
Exemple #14
0
        public static KmlDocument createKmlAreaWithObjects(ArrayList wpts, ArrayList eqs, ArrayList trks)
        {
            KmlDocument kmlDoc = new KmlDocument("Selected Area", 1);

            if (wpts.Count > 0)
            {
                KmlFolder waypointsFolder = kmlDoc.CreateFolder("Waypoints");

                foreach (Waypoint wpt in wpts)
                {
                    KmlWaypoint kWpt = new KmlWaypoint(waypointsFolder, wpt);
                }
            }

            if (eqs.Count > 0)
            {
                KmlFolder earthquakesFolder = kmlDoc.CreateFolder("Earthquakes");

                foreach (Earthquake eq in eqs)
                {
                    KmlEarthquake kEq = new KmlEarthquake(earthquakesFolder, eq);
                }
            }

            if (trks.Count > 0)
            {
                KmlFolder tracksFolder = kmlDoc.CreateFolder("Tracks");

                foreach (Track trk in trks)
                {
                    KmlTrack kTrack = new KmlTrack(tracksFolder, trk);
                }
            }

            kmlDoc.CreateAbout();

            return(kmlDoc);
        }
        public static KmlDocument createKmlAreaWithObjects(ArrayList wpts, ArrayList eqs, ArrayList trks)
        {
            KmlDocument kmlDoc = new KmlDocument("Selected Area", 1);

            if(wpts.Count > 0)
            {
                KmlFolder waypointsFolder = kmlDoc.CreateFolder("Waypoints");

                foreach(Waypoint wpt in wpts)
                {
                    KmlWaypoint kWpt = new KmlWaypoint(waypointsFolder, wpt);
                }
            }

            if(eqs.Count > 0)
            {
                KmlFolder earthquakesFolder = kmlDoc.CreateFolder("Earthquakes");

                foreach(Earthquake eq in eqs)
                {
                    KmlEarthquake kEq = new KmlEarthquake(earthquakesFolder, eq);
                }
            }

            if(trks.Count > 0)
            {
                KmlFolder tracksFolder = kmlDoc.CreateFolder("Tracks");

                foreach(Track trk in trks)
                {
                    KmlTrack kTrack = new KmlTrack(tracksFolder, trk);
                }
            }

            kmlDoc.CreateAbout();

            return kmlDoc;
        }
        public async Task <(string tempPath, MooiDocument document)> Generate([NotNull] KmlDocument document
                                                                              , [NotNull] List <DiscoveredPlace> discoveredPlaces, string language, IResourceFetchingProgress progress)
        {
            // TODO: Add cancellationtoken approach

            var tempPath = CreateAndGetTempPath();

            foreach (var resource in document.Resources)
            {
                await _file.WriteBytesAsync(Path.Combine(tempPath, resource.FileName), resource.Blob);
            }
            progress.ReportResourceEntriesProcessed();

            await _foursquare.PopulateWithDetailedInfo(discoveredPlaces.Where(x => !x.IsForPlacemark), language, CancellationToken.None);

            var mooiDocument = _mooiDocumentFactory.Create(document, discoveredPlaces, tempPath);

            await FetchMapImages(mooiDocument, tempPath, progress);

            progress.ReportDone();

            return(tempPath, mooiDocument);
        }
Exemple #17
0
        private void ResetKml()
        {
            // Clear any existing layers from the map.
            MyMapView.Map.OperationalLayers.Clear();

            // Reset the most recently placed placemark.
            _currentPlacemark = null;

            // Create a new KML document.
            _kmlDocument = new KmlDocument()
            {
                Name = "KML Sample Document"
            };

            // Create a KML dataset using the KML document.
            _kmlDataset = new KmlDataset(_kmlDocument);

            // Create the KML layer using the KML dataset.
            _kmlLayer = new KmlLayer(_kmlDataset);

            // Add the KML layer to the map.
            MyMapView.Map.OperationalLayers.Add(_kmlLayer);
        }
Exemple #18
0
        public void When_creating_model_the_values_are_copied_correctly()
        {
            // Arrange
            var kmlDocument = new KmlDocument {
                Title       = "kml-title",
                Description = "kml-desc",
                Folders     =
                {
                    new KmlFolder("folder-1", new List <KmlPlacemark> {
                        new KmlPlacemark()
                    })
                }
            };

            _mooiGroupFactoryMock.Setup(x => x.CreateList(kmlDocument.Folders[0], null, string.Empty)).Returns(new List <MooiCluster>());

            // Act
            var result = _factory.Create(kmlDocument, null, string.Empty);

            // Verify
            Assert.AreEqual(kmlDocument.Title, result.Title);
            Assert.AreEqual(kmlDocument.Description, result.Description);
            Assert.AreEqual(kmlDocument.Folders[0].Name, result.Sections[0].Name);
        }
        private void DoReadKml()
        {
            if (this._stream.CanSeek)
            {
                this._stream.Seek(0L, SeekOrigin.Begin);
            }
            KmlDocument kmlDocument = new KmlDocument((IXmlSource) new XmlStreamSource(this._stream));
            object      kml         = kmlDocument.Kml;

            switch (kmlDocument.Version)
            {
            case KmlVersion.Kmlv2_1:
                this.ConvertKml(kml as KmlType);
                break;

            case KmlVersion.Kmlv2_0:
                this.ConvertKml(kml as OsmSharp.IO.Xml.Kml.v2_0.kml);
                break;

            case KmlVersion.Kmlv2_0_response:
                this.ConvertKml(kml as OsmSharp.IO.Xml.Kml.v2_0_response.kml);
                break;
            }
        }
        private void UpdateItems()
        {
            KmlDocument kdoc = new KmlDocument();
            kdoc.LoadFromFile(MessageE);
            kdoc.LoadFromFile(InitItem);

            ItemNames = new Dictionary<int, string>();
            ItemDescriptions = new Dictionary<int, string>();

            //load item names
            foreach (KmlNode knode in kdoc.SelectNodes("itemname"))
            {
                int Index = knode.Values[1].ValueAsInt;
                string Name = knode.Values[2].Value;

                if (!ItemNames.ContainsKey(Index))
                {
                    ItemNames.Add(Index, Name);
                }
            }

            //load prefix names
            using (ISession session = Database.Factory.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    foreach (KmlNode knode in kdoc.SelectNodes("prefixname"))
                    {
                        int Index = knode.Values[1].ValueAsInt;
                        string Name = knode.Values[2].Value;
                        Prefix prefix = new Prefix();
                        prefix.Index = Index;
                        prefix.Name = Name;
                        session.SaveOrUpdate(prefix);
                    }
                    transaction.Commit();
                }
            }
            //load item descriptions
            foreach (KmlNode knode in kdoc.SelectNodes("itemdesc"))
            {
                int Index = knode.Values[1].ValueAsInt;
                string Name = knode.Values[2].Value;

                if (!ItemDescriptions.ContainsKey(Index))
                {
                    ItemDescriptions.Add(Index, Name);
                }
            }

            //delete current items

            //load items

            using (ISession session = Database.Factory.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {

                    foreach (KmlNode knode in kdoc.SelectNodes("item"))
                    {

                        int Index = knode.SelectSingleNode("index").Values[1].ValueAsInt;
                        int NameIndex = knode.SelectSingleNode("name").Values[1].ValueAsInt;

                        //description
                        int DescIndex = -1;
                        if (knode.ContainsNode("desc"))
                        {
                            DescIndex = knode.SelectSingleNode("desc").Values[1].ValueAsInt;
                        }

                        string Icon = knode.SelectSingleNode("image").Values[1].Value;
                        string Class = knode.SelectSingleNode("class").Values[1].Value;
                        string SubClass = knode.SelectSingleNode("class").Values[2].Value;
                        int Code1 = knode.SelectSingleNode("code").Values[1].ValueAsInt;
                        int Code2 = knode.SelectSingleNode("code").Values[2].ValueAsInt;
                        int Code3 = knode.SelectSingleNode("code").Values[3].ValueAsInt;
                        int Code4 = knode.SelectSingleNode("code").Values[4].ValueAsInt;

                        byte Endurance = 0;
                        if (knode.ContainsNode("endurance"))
                        {
                            Endurance = (byte)knode.SelectSingleNode("endurance").Values[1].ValueAsInt;
                        }

                        int Grade = 0;
                        if (knode.ContainsNode("level"))
                        {
                            Grade = knode.SelectSingleNode("level").Values[1].ValueAsInt;
                        }

                        //limit
                        int ClassLimit = -1;
                        int LevelLimit = -1;
                        if (knode.ContainsNode("limit"))
                        {

                            LevelLimit = knode.SelectSingleNode("limit").Values[2].ValueAsInt;

                            switch (knode.SelectSingleNode("limit").Values[2].Value.ToLower())
                            {
                                case "knight":
                                    ClassLimit = 0;
                                    break;
                                case "archer":
                                    ClassLimit = 2;
                                    break;
                                case "mage":
                                    ClassLimit = 1;
                                    break;
                            }
                        }

                        Item item = new Item();

                        item.Index = Index;
                        if (ItemNames.ContainsKey(NameIndex))
                        {
                            item.Name = ItemNames[NameIndex];
                        }
                        if (ItemDescriptions.ContainsKey(DescIndex))
                        {
                            item.Description = ItemDescriptions[DescIndex];
                        }

                        item.Icon = Icon;
                        item.Class = Class;
                        item.SubClass = SubClass;
                        item.Code1 = Code1;
                        item.Code2 = Code2;
                        item.Code3 = Code3;
                        item.Code4 = Code4;
                        item.Grade = Grade;
                        item.LevelLimit = LevelLimit;
                        item.ClassLimit = ClassLimit;
                        item.Endurance = Endurance;

                        session.SaveOrUpdate(item);

                    }

                    transaction.Commit();
                }

            }
        }
Exemple #21
0
        private void buttonOK_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;

            Settings.Default.KmzOpenFile = this.chkOpen.Checked;

            if (this.txtKmzFile.Text == "")
            {
                return;
            }

            KmlDocument doc = new KmlDocument();

            doc.Name = this.txtName.Text;

            // create placemarks for photos (one, selectend or subdirs)
            if (this.radOneFile.Checked)
            {
                Placemark placemark = PlacemarkFromPicture(currentPicture);
                if (placemark != null)
                {
                    doc.Placemarks.Add(placemark);
                }
            }
            else if (this.radSelected.Checked)
            {
                List <string> filenames = this.getAllFilesDelegate(false);
                foreach (string filename in filenames)
                {
                    PictureMetaData pmd       = new PictureMetaData(filename);
                    Placemark       placemark = PlacemarkFromPicture(pmd);
                    if (placemark != null)
                    {
                        doc.Placemarks.Add(placemark);
                    }
                    pmd.Close();
                }
            }
            else if (this.radSubdirs.Checked)
            {
                List <string> filenames = this.getAllFilesDelegate(false);
                foreach (string filename in filenames)
                {
                    PictureMetaData pmd       = new PictureMetaData(filename);
                    Placemark       placemark = PlacemarkFromPicture(pmd);
                    if (placemark != null)
                    {
                        doc.Placemarks.Add(placemark);
                    }
                    pmd.Close();
                }

                FileInfo      fi      = new FileInfo(filenames[0]);
                DirectoryInfo startdi = fi.Directory;
                foreach (DirectoryInfo di in startdi.GetDirectories())
                {
                    doc.Folders.Add(CreateFolder(di));
                }
            }

            // create route
            if (this.chkRoute.Checked && File.Exists(this.txtRouteFile.Text))
            {
                GpsLog log = GpsLogFactory.FromFile(this.txtRouteFile.Text);

                PlacemarkLine p = new PlacemarkLine();
                p.LineWidth = Settings.Default.KmzLineWidth;
                p.LineColor = Settings.Default.KmzLineColor;
                p.Name      = "route";
                foreach (GpsLogEntry l in log)
                {
                    p.Coordinates.Add(new Coordinate(l.Longitude, l.Latitude));
                }
                doc.Placemarks.Add(p);
            }

            if (doc.IsEmpty)
            {
                this.Cursor = Cursors.Default;

                MessageBox.Show("No photos with GPS data found and no kmz-file created.", "PhotoTagStudio",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                KmzArchiv arc = new KmzArchiv(doc);
                arc.Create(this.txtKmzFile.Text);

                this.Cursor = Cursors.Default;

                if (this.chkOpen.Checked)
                {
                    System.Diagnostics.Process.Start(this.txtKmzFile.Text);
                }
            }
        }
        /// <summary>
        /// Reads the actual Kml.
        /// </summary>
        private void DoReadKml()
        {
            // seek to the beginning of the stream.
            if (_stream.CanSeek) { _stream.Seek(0, SeekOrigin.Begin); }

            // instantiate and load the gpx test document.
            XmlStreamSource source = new XmlStreamSource(_stream);
            KmlDocument document = new KmlDocument(source);
            object kml = document.Kml;

            switch (document.Version)
            {
                case KmlVersion.Kmlv2_1:
                    this.ConvertKml(kml as OsmSharp.IO.Xml.Kml.v2_1.KmlType);
                    break;
                case KmlVersion.Kmlv2_0_response:
                    this.ConvertKml(kml as OsmSharp.IO.Xml.Kml.v2_0_response.kml);
                    break;
                case KmlVersion.Kmlv2_0:
                    this.ConvertKml(kml as OsmSharp.IO.Xml.Kml.v2_0.kml);
                    break;
            }
        }
        private void FormatSyntax()
        {
            KmlDocument kdoc = new KmlDocument();

            ValidateSyntax();

            try
            {
                kdoc.LoadFromString(syntaxEdit.Text);

                this.syntaxEdit.Text = kdoc.ToString();
            }
            catch (Exception)
            {
                MessageBox.Show("Syntax must be valid before formatting.");
            }
        }
Exemple #24
0
 public virtual void addAddressToKML(Address address, KmlDocument kmlDocument)
 {
     throw new NotImplementedException();
 }
        public async Task When_going_next_the_session_is_updated()
        {
            // Arrange
            var kmlDocument = new KmlDocument {
                Folders =
                {
                    new KmlFolder("folder-1"),
                    new KmlFolder("folder-2", new[] {
                        new KmlPlacemark {
                            Name = "pm-1"
                        },
                        new KmlPlacemark {
                            Name = "pm-2"
                        }
                    }
                                  )
                }
            };
            var vm = new StepPickViewModel {
                KmlObjectsTree =
                {
                    FoldersToInclude        =
                    {
                        new KmlFolderNodeViewModel(kmlDocument.Folders[0])
                        {
                            Enabled         = false
                        },
                        new KmlFolderNodeViewModel(kmlDocument.Folders[1])
                        {
                            Enabled  = true,
                            Children =
                            {
                                new KmlPlacemarkNodeViewModel(kmlDocument.Folders[1].Placemarks[0], null)
                                {
                                    Enabled = false
                                },
                                new KmlPlacemarkNodeViewModel(kmlDocument.Folders[1].Placemarks[1], null)
                                {
                                    Enabled = true
                                }
                            }
                        }
                    }
                }
            };

            _presenter.SetupGet(x => x.ViewModel).Returns(vm);
            _presenter.Object.SetDocument(kmlDocument);
            _userSessionMock.SetupProperty(x => x.Document);

            // Act
            var result = await _presenter.Object.BeforeGoNext();

            // Verify
            Assert.IsTrue(result);
            Assert.AreEqual(kmlDocument.Title, _userSessionMock.Object.Document.Title);
            Assert.AreEqual(1, _userSessionMock.Object.Document.Folders.Count);
            Assert.AreEqual(kmlDocument.Folders[1].Name, _userSessionMock.Object.Document.Folders[0].Name);
            Assert.AreEqual(1, _userSessionMock.Object.Document.Folders[0].Placemarks.Count);
            Assert.AreEqual(kmlDocument.Folders[1].Placemarks[1].Name, _userSessionMock.Object.Document.Folders[0].Placemarks[0].Name);
        }
Exemple #26
0
 internal void SetDocument(KmlDocument kmlDocument)
 {
     _kmlDocument = kmlDocument;
 }
Exemple #27
0
        public void KmlWriteTestv2_1()
        {
            // instantiate and load the gpx test document.
            XmlStreamSource source = new XmlStreamSource(
                Assembly.GetExecutingAssembly().GetManifestResourceStream("OsmSharp.Test.Unittests.test.v2.1.kml"));
            KmlDocument document = new KmlDocument(source);
            object kml = document.Kml;

            if (kml is OsmSharp.IO.Xml.Kml.v2_1.KmlType)
            { // all ok here!

                // delete the target file.
                MemoryStream write_file = new MemoryStream();

                // create a new xml source.
                XmlStreamSource write_source = new XmlStreamSource(write_file);
                KmlDocument kml_target = new KmlDocument(write_source);

                // set the target data the same as the source document.
                kml_target.Kml = kml;

                // save the data.
                kml_target.Save();

                // close the old document.
                document.Close();
                source.Close();

                // check to see if the data was writter correctly.
                // instantiate and load the osm test document.
                source = new XmlStreamSource(write_file);
                document = new KmlDocument(source);
                kml = document.Kml;

                // check the result that was written and then read again.
                if (kml is OsmSharp.IO.Xml.Kml.v2_1.KmlType)
                { // all ok here!
                    OsmSharp.IO.Xml.Kml.v2_1.KmlType kml_type = (kml as OsmSharp.IO.Xml.Kml.v2_1.KmlType);

                    // test the gpx test file content.
                    Assert.IsNotNull(kml_type.Item, "No item was found!");
                    Assert.IsInstanceOf<OsmSharp.IO.Xml.Kml.v2_1.FolderType>(kml_type.Item, "Incorrect item type!");

                    OsmSharp.IO.Xml.Kml.v2_1.FolderType type = (kml_type.Item as OsmSharp.IO.Xml.Kml.v2_1.FolderType);
                    Assert.AreEqual(type.Items1.Length, 10, "Incorrect number of items in folder!");
                }
                else
                {
                    Assert.Fail("No kml data was read, or data was of the incorrect type!");
                }

                document.Close();
                source.Close();

            }
            else
            {
                Assert.Fail("No kml data was read, or data was of the incorrect type!");
            }

            document.Close();
            source.Close();
        }
        public static KmlDocument createKmlEarthquakes(ArrayList eqs)
        {
            KmlDocument kmlDoc = new KmlDocument("Selected Earthquake" + (eqs.Count > 1 ? "s" : (": " + ((Earthquake)eqs[0]).NameDisplayed)), 1);

            KmlFolder earthquakesFolder = kmlDoc.CreateFolder("Earthquakes");

            foreach(Earthquake eq in eqs)
            {
                KmlEarthquake kEq = new KmlEarthquake(earthquakesFolder, eq);
            }

            kmlDoc.CreateAbout();

            return kmlDoc;
        }
        private void syntaxValidator_DoWork(object sender, DoWorkEventArgs e)
        {
            string source = e.Argument as string;
            string error = "";
            bool valid = true;
            CharPosition position = new CharPosition(-1, -1, -1);

            try
            {
                KmlDocument kdoc = new KmlDocument();
                kdoc.LoadFromString(source);

            }
            catch (Exception ex)
            {
                error = ex.InnerException.Message;
                position = ex.InnerException.Data["Position"] as CharPosition;
                valid = false;
            }

            e.Result = new SyntaxValidationResult(valid,error,position);
        }
Exemple #30
0
        public static void runTrack(Track trk)
        {
            KmlDocument kmlDoc = createKmlTrack(trk);

            kmlDoc.run();
        }
        public static KmlDocument createKmlWaypoints(ArrayList wpts)
        {
            KmlDocument kmlDoc = new KmlDocument("Selected Waypoint" + (wpts.Count > 1 ? "s" : (": " + ((Waypoint)wpts[0]).NameDisplayed)), 1);

            KmlFolder waypointsFolder = kmlDoc.CreateFolder("Waypoints");

            foreach(Waypoint wpt in wpts)
            {
                KmlWaypoint kWpt = new KmlWaypoint(waypointsFolder, wpt);
            }

            kmlDoc.CreateAbout();

            return kmlDoc;
        }
Exemple #32
0
 public void HandleActivated(KmlDocument kmlDocument, CancellationToken cancellationToken)
 {
     ReadKmlDocumentIntoViewModel(kmlDocument);
 }
 protected virtual GeoJsonFeatureCollection[] ConvertDocument(KmlDocument document)
 {
     return(ConvertDocument(document, default));
 }
Exemple #34
0
        public void KmlWriteTestv2_1()
        {
            // instantiate and load the gpx test document.
            XmlStreamSource source = new XmlStreamSource(
                Assembly.GetExecutingAssembly().GetManifestResourceStream("OsmSharp.UnitTests.test.v2.1.kml"));
            KmlDocument document = new KmlDocument(source);
            object      kml      = document.Kml;

            if (kml is OsmSharp.Xml.Kml.v2_1.KmlType)
            { // all ok here!
                // delete the target file.
                MemoryStream write_file = new MemoryStream();

                // create a new xml source.
                XmlStreamSource write_source = new XmlStreamSource(write_file);
                KmlDocument     kml_target   = new KmlDocument(write_source);

                // set the target data the same as the source document.
                kml_target.Kml = kml;

                // save the data.
                kml_target.Save();

                // close the old document.
                document.Close();
                source.Close();

                // check to see if the data was writter correctly.
                // instantiate and load the osm test document.
                source   = new XmlStreamSource(write_file);
                document = new KmlDocument(source);
                kml      = document.Kml;

                // check the result that was written and then read again.
                if (kml is OsmSharp.Xml.Kml.v2_1.KmlType)
                { // all ok here!
                    OsmSharp.Xml.Kml.v2_1.KmlType kml_type = (kml as OsmSharp.Xml.Kml.v2_1.KmlType);

                    // test the gpx test file content.
                    Assert.IsNotNull(kml_type.Item, "No item was found!");
                    Assert.IsInstanceOf <OsmSharp.Xml.Kml.v2_1.FolderType>(kml_type.Item, "Incorrect item type!");

                    OsmSharp.Xml.Kml.v2_1.FolderType type = (kml_type.Item as OsmSharp.Xml.Kml.v2_1.FolderType);
                    Assert.AreEqual(type.Items1.Length, 10, "Incorrect number of items in folder!");
                }
                else
                {
                    Assert.Fail("No kml data was read, or data was of the incorrect type!");
                }

                document.Close();
                source.Close();
            }
            else
            {
                Assert.Fail("No kml data was read, or data was of the incorrect type!");
            }

            document.Close();
            source.Close();
        }
        protected virtual GeoJsonFeatureCollection[] ConvertDocument(KmlDocument document, IStyleProvider provider)
        {
            // Use the style provider of the document if not explicitly specified
            provider = provider ?? document.StyleSelectors;

            // Initialize a new list of collections
            List <GeoJsonFeatureCollection> collections = new List <GeoJsonFeatureCollection>();

            if (document.Features.Any(x => x is KmlFolder))
            {
                GeoJsonFeatureCollection defaultCollection = null;

                foreach (KmlFeature feature in document.Features)
                {
                    switch (feature)
                    {
                    case KmlDocument _:
                        throw new KmlException("Weird place for a <Document>, huh?");

                    case KmlFolder folder:
                        collections.Add(ConvertFolder(folder, provider));
                        break;

                    case KmlPlacemark placemark:

                        // Make sure the default feature collection is initialized
                        if (defaultCollection == null)
                        {
                            collections.Add(defaultCollection = new GeoJsonFeatureCollection());
                        }

                        // As the placemark isn't located inside a folder, we should append it to a "default" feature collection"
                        defaultCollection.Add(ConvertPlacemark(placemark, provider));

                        break;

                    default:
                        throw new KmlException("Unsupported feature " + feature.GetType());
                    }
                }
            }
            else
            {
                GeoJsonFeatureCollection features = new GeoJsonFeatureCollection();

                foreach (KmlFeature feature in document.Features)
                {
                    switch (feature)
                    {
                    case KmlDocument _:
                        throw new KmlException("Weird place for a <Document>, huh?");

                    case KmlPlacemark placemark:
                        features.Add(ConvertPlacemark(placemark, provider));
                        break;

                    default:
                        throw new KmlException("Unsupported feature " + feature.GetType());
                    }
                }

                collections.Add(features);
            }

            return(collections.ToArray());
        }
        public static KmlDocument createKmlTrack(Track trk)
        {
            KmlDocument kmlDoc = new KmlDocument(trk.Name, 1);

            KmlFolder waypointsFolder = kmlDoc.CreateFolder("Waypoints");

            KmlFolder tracksFolder = kmlDoc.CreateFolder("Tracks");

            KmlTrack kTrack = new KmlTrack(tracksFolder, trk);

            kmlDoc.CreateAbout();

            return kmlDoc;
        }
Exemple #37
0
        private void AddFeatureToDisplay(KmlFeature feature, bool sky)
        {
            KmlDocument doc = feature as KmlDocument;

            if (doc != null)
            {
                sky = doc.sky;
            }
            if (!(feature is KmlNetworkLink))
            {
                if (feature.visibility == false)
                {
                    return;
                }
                else if (feature is KmlPlacemark)
                {
                    KmlPlacemark placemark = (KmlPlacemark)feature;
                    KmlStyle     style     = placemark.Style.GetStyle(placemark.Selected);
                    Color        lineColor = Color.White;
                    if (style != null)
                    {
                        lineColor = style.LineStyle.Color;
                    }
                    if (placemark.geometry is KmlPoint)
                    {
                        placemark.Point = (KmlPoint)placemark.geometry;
                        AddPlacemark(placemark);
                    }
                    else if (placemark.geometry is KmlMultiGeometry)
                    {
                        KmlMultiGeometry geo = (KmlMultiGeometry)placemark.geometry;
                        AddMultiGeometry(sky, placemark, (float)style.LineStyle.Width, style.PolyStyle.Color, lineColor, geo);
                    }
                    else if (placemark.geometry is KmlPolygon)
                    {
                        KmlPolygon geo = (KmlPolygon)placemark.geometry;
                        if (geo.OuterBoundary != null)
                        {
                            AddLines(sky, geo.OuterBoundary as KmlLineList, (float)style.LineStyle.Width, style.PolyStyle.Color, lineColor, geo.extrude);
                            // to do 3d work and subtract inner rings
                        }
                    }
                    else if (placemark.geometry is KmlLineString)
                    {
                        KmlLineString geo = (KmlLineString)placemark.geometry;

                        List <Vector3d> vertexList = new List <Vector3d>();
                        for (int i = 0; i < (geo.PointList.Count); i++)
                        {
                            vertexList.Add(Coordinates.GeoTo3dDouble(geo.PointList[i].Lat, geo.PointList[i].Lng, 1 + (geo.PointList[i].Alt / geo.MeanRadius)));
                        }
                        for (int i = 0; i < (geo.PointList.Count - 1); i++)
                        {
                            if (sky)
                            {
                                lines.AddLine(Coordinates.RADecTo3d(-(180.0 - geo.PointList[i].Lng) / 15 + 12, geo.PointList[i].Lat, 1), Coordinates.RADecTo3d(-(180.0 - geo.PointList[i + 1].Lng) / 15 + 12, geo.PointList[i + 1].Lat, 1), lineColor, new Dates());
                            }
                            else
                            {
                                lines.AddLine(vertexList[i], vertexList[i + 1], lineColor, new Dates());
                            }
                        }
                    }
                }
                if (feature is KmlGroundOverlay && feature.visibility)
                {
                    AddGroundOverlay(feature as KmlGroundOverlay);
                }

                if (feature is KmlScreenOverlay && feature.visibility)
                {
                    AddScreenOverlay(feature as KmlScreenOverlay);
                }
            }
            if (feature.visibility)
            {
                if (feature is KmlContainer)
                {
                    KmlContainer container = (KmlContainer)feature;
                    if (container.children != null)
                    {
                        foreach (KmlFeature child in container.children)
                        {
                            AddFeatureToDisplay(child, sky);
                        }
                    }
                }
                else
                {
                    if (feature is KmlNetworkLink)
                    {
                        KmlNetworkLink netLink = (KmlNetworkLink)feature;
                        if (netLink.LinkRoot != null)
                        {
                            foreach (KmlFeature child in netLink.LinkRoot.children)
                            {
                                AddFeatureToDisplay(child, sky);
                            }
                        }
                    }
                }
            }
        }
        public static KmlDocument createKmlTracks(ArrayList trks)
        {
            KmlDocument kmlDoc = new KmlDocument("Selected Track" + (trks.Count > 1 ? "s" : (": " + ((Track)trks[0]).Name)), 1);

            KmlFolder waypointsFolder = kmlDoc.CreateFolder("Waypoints");

            KmlFolder tracksFolder = kmlDoc.CreateFolder("Tracks");

            foreach(Track trk in trks)
            {
                KmlTrack kTrack = new KmlTrack(tracksFolder, trk);
            }

            kmlDoc.CreateAbout();

            return kmlDoc;
        }
        public static void saveTracksWaypoints(string filename, string name, ArrayList tracks, bool saveTracks,
													ArrayList wpts, bool saveWaypoints,
													out int waypointCount, out int trkpointCount)
        {
            waypointCount = 0;
            trkpointCount = 0;

            KmlDocument kmlDoc = new KmlDocument(name, 1);

            if(saveWaypoints)
            {
                KmlFolder waypointsFolder = kmlDoc.CreateFolder("Waypoints");

                foreach(Waypoint wpt in wpts)
                {
                    waypointCount++;
                    KmlWaypoint kWaypoint = new KmlWaypoint(waypointsFolder, wpt);
                }
            }

            if(saveTracks)
            {
                KmlFolder tracksFolder = kmlDoc.CreateFolder("Tracks");

                foreach(Track trk in tracks)
                {
                    trkpointCount += trk.Trackpoints.Count;
                    KmlTrack kTrack = new KmlTrack(tracksFolder, trk);
                }
            }

            kmlDoc.CreateAbout();

            kmlDoc.SaveToKmz(filename, false);
        }
Exemple #40
0
        private void CalculateImageAndTransformationMatrix(string fileName)
        {
            var zipFile = new Ionic.Zip.ZipFile(fileName);
            var mapSize = new Size();

            Transformation = new Transformation();

            // get entry for kml file and image file
            KmlDocument kmlDocument = null;

            foreach (var entry in zipFile)
            {
                if (entry.FileName == entry.LocalFileName && Path.GetExtension(entry.FileName) == ".kml")
                {
                    using (var kmlStream = new MemoryStream())
                    {
                        entry.Extract(kmlStream);
                        kmlStream.Position = 0;
                        kmlDocument        = new KmlDocument(kmlStream);
                    }
                    break;
                }
            }

            if (kmlDocument != null)
            {
                // we have got a kml document, get map image file stream from it
                foreach (var entry in zipFile)
                {
                    if (entry.FileName == kmlDocument.ImageFileName)
                    {
                        ImageStream = new MemoryStream();
                        entry.Extract(ImageStream);
                        ImageStream.Position = 0;
                        // check if image is QR jpeg
                        var ed = QuickRouteJpegExtensionData.FromStream(ImageStream);
                        if (ed != null)
                        {
                            // get transformation matrix from QR jpeg metadata
                            Transformation       = ed.Sessions.CalculateAverageTransformation();
                            ImageStream.Position = 0;
                            return;
                        }
                        else
                        {
                            // it is not, use normal image bounds
                            ImageStream.Position = 0;
                            mapSize = Image.FromStream(ImageStream).Size; // need to get image object to get image size
                        }
                        ImageStream.Position = 0;
                        break;
                    }
                }
            }

            if (kmlDocument != null && ImageStream != null)
            {
                // finally, calculate the transformation
                Transformation = new Transformation(kmlDocument.LongLatBox, mapSize);
            }
        }
Exemple #41
0
 public virtual void addAddressToKML(Address address, KmlDocument kmlDocument)
 {
     throw new NotImplementedException();
 }