コード例 #1
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();
            }
        }
コード例 #2
0
ファイル: KmzFileTest.cs プロジェクト: dahlbyk/SharpKml
        public void TestBasicOpen()
        {
            // Try a valid archive
            using (var stream = SampleData.CreateStream("Engine.Data.Doc.kmz"))
                using (var file = KmzFile.Open(stream))
                {
                    Assert.That(file, Is.Not.Null);
                    var kml = file.ReadKml();
                    Assert.That(kml, Is.Not.Null.Or.Empty);
                }

            // Now try a valid archive with no Kml information
            using (var stream = SampleData.CreateStream("Engine.Data.NoKml.kmz"))
                using (var file = KmzFile.Open(stream))
                {
                    var kml = file.ReadKml();
                    Assert.That(kml, Is.Null);
                }

            // Now try an invalid archive (i.e. something that isn't a zip)
            using (var stream = SampleData.CreateStream("Engine.Data.Bounds.kml"))
            {
#if SILVERLIGHT
                var exception = typeof(IOException);
#else
                var exception = typeof(InvalidDataException);
#endif
                Assert.That((TestDelegate)(() => KmzFile.Open(stream)),
                            Throws.TypeOf(exception));
            }
        }
コード例 #3
0
ファイル: KmzFileTest.cs プロジェクト: dahlbyk/SharpKml
        public void TestSave()
        {
            // Create the Kml data
            const string Xml    = "<Placemark xmlns='http://www.opengis.net/kml/2.2'><name>tmp kml</name></Placemark>";
            var          parser = new Parser();

            parser.ParseString(Xml, true);
            var kml = KmlFile.Create(parser.Root, false);

            using (var stream = new MemoryStream())
            {
                // Create and save the archive
                using (var file = KmzFile.Create(kml))
                {
                    file.Save(stream);
                }

                // Try to open the saved archive, rewinding the stream
                stream.Position = 0;
                using (var file = KmzFile.Open(stream))
                {
                    // Make sure it's the same as what we saved
                    parser.ParseString(file.ReadKml(), true);
                    SampleData.CompareElements(kml.Root, parser.Root);
                }
            }
        }
コード例 #4
0
ファイル: KmzFileTest.cs プロジェクト: dahlbyk/SharpKml
        public void TestSave()
        {
            // Create the Kml data
            const string Xml    = "<Placemark xmlns='http://www.opengis.net/kml/2.2'><name>tmp kml</name></Placemark>";
            var          parser = new Parser();

            parser.ParseString(Xml, true);
            var kml = KmlFile.Create(parser.Root, false);

            // This will be where we temporary save the archive to
            string tempFile = Path.GetTempFileName();

            try
            {
                // Create and save the archive
                using (var file = KmzFile.Create(kml))
                {
                    file.Save(tempFile);
                }

                // Try to open the saved archive
                using (var file = KmzFile.Open(tempFile))
                {
                    // Make sure it's the same as what we saved
                    parser.ParseString(file.ReadKml(), true);
                    SampleData.CompareElements(kml.Root, parser.Root);
                }
            }
            finally
            {
                File.Delete(tempFile);
            }
        }
コード例 #5
0
ファイル: AdminController.cs プロジェクト: Tylland/altidude
        public ActionResult Upload()
        {
            if (Request.Files.Count > 0)
            {
                var file = Request.Files[0];

                if (file != null && file.ContentLength > 0)
                {
                    var kmzFile   = KmzFile.Open(file.InputStream);
                    var kmlString = kmzFile.ReadKml();

                    Parser parser = new Parser();
                    parser.ParseString(kmlString, false);

                    Kml kml    = parser.Root as Kml;
                    var places = new Dictionary <string, Place>();

                    ExtractPlaces(kml.Feature as Feature, "", places);

                    var placeRepository = new OrmLitePlaceRepository(ApplicationManager.OpenConnection());

                    foreach (var place in places.Values)
                    {
                        place.UsageLevel = PlaceUsageLevel.Public;
                        placeRepository.Add(place);
                    }
                }
            }

            return(View("Import"));
        }
コード例 #6
0
ファイル: CreateKmz.cs プロジェクト: pxg414/sharpkml
        public static void Run()
        {
            const string OutputPath = "output.kmz";
            string       input      = Program.GetInputFile("Enter a file to convert to Kmz:", "Data/doc.kml");

            try
            {
                KmlFile kml = LoadKml(input);

                using (KmzFile kmz = SaveKmlAndLinkedContentIntoAKmzArchive(kml, input))
                    using (Stream output = File.Create(OutputPath))
                    {
                        kmz.Save(output);
                        Console.WriteLine("Saved to '{0}'.", OutputPath);
                    }

                // Now open the file we saved and list the contents
                using (Stream file = File.OpenRead(OutputPath))
                    using (KmzFile kmz = KmzFile.Open(file))
                    {
                        Console.WriteLine("Contents:");
                        foreach (string name in kmz.Files)
                        {
                            Console.WriteLine(name);
                        }
                    }
            }
            catch (Exception ex)
            {
                Program.DisplayError(ex.GetType() + "\n" + ex.Message);
            }
        }
コード例 #7
0
        /// Read file in KMZ and KML format
        private void ReadGISFile()
        {
            string pathToimage = null;

            using (FileStream reader = new FileStream(path, FileMode.Open))
                using (KmzFile kmzFile = KmzFile.Open(reader))
                {
                    KmlFile kmlFile = kmzFile.GetDefaultKmlFile();
                    var     image   = kmlFile.Root.Flatten().OfType <GroundOverlay>().FirstOrDefault();
                    if (image != null)
                    {
                        pathToimage = image.Icon.Href.ToString();
                    }
                    var latLonBox = kmlFile.Root.Flatten().OfType <LatLonBox>().FirstOrDefault();
                    if (latLonBox != null)
                    {
                        var coorners = GetMapCorners(latLonBox);
                        map = new Map()
                        {
                            MapCorners = coorners,
                            Rotation   = latLonBox.Rotation,
                            Name       = kmlFile.Root.Flatten().OfType <Folder>().FirstOrDefault().Name
                        };
                    }
                }

            ReadArchiveAndExport(pathToimage);
        }
コード例 #8
0
ファイル: KmzFileTest.cs プロジェクト: dahlbyk/SharpKml
        public void TestReadFile()
        {
            // NoKml.kmz has a file called foo.txt in a folder called foo.
            using (var stream = SampleData.CreateStream("Engine.Data.NoKml.kmz"))
                using (var file = KmzFile.Open(stream))
                {
                    byte[] data = file.ReadFile("foo/foo.txt");
                    Assert.That(data, Is.Not.Null);

                    // The archive does not have a file called bar.txt in that folder
                    byte[] invalid = file.ReadFile("foo/bar.txt");
                    Assert.That(invalid, Is.Null);
                }
        }
コード例 #9
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</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)));
            }
        }
コード例 #10
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)));
            }
        }
コード例 #11
0
        public static KmlFile OpenFile(String filePath)
        {
            string fileExtension = System.IO.Path.GetExtension(filePath);

            using (FileStream fileStream = File.OpenRead(filePath))
            {
                if (fileExtension.Equals(".kmz", StringComparison.OrdinalIgnoreCase))
                {
                    KmzFile kmzFile       = KmzFile.Open(fileStream);
                    string  kmlFileString = kmzFile.ReadKml();
                    using (StringReader stringReader = new StringReader(kmlFileString))
                    {
                        return(KmlFile.Load(stringReader));
                    }
                }
                else
                {
                    return(KmlFile.Load(fileStream));
                }
            }
        }
コード例 #12
0
ファイル: KmzFileTest.cs プロジェクト: dahlbyk/SharpKml
        public void TestList()
        {
            // Make sure Files returns the entries in the correct order
            string[] expected =
            {
                "z/c.kml",
                "b.kml",
                "a/a.kml"
            };

            using (var stream = SampleData.CreateStream("Engine.Data.MultiKml.kmz"))
                using (var file = KmzFile.Open(stream))
                {
                    Assert.That(file.Files.Count(), Is.EqualTo(expected.Length));

                    int index = 0;
                    foreach (var name in file.Files)
                    {
                        Assert.That(name, Is.EqualTo(expected[index++]));
                    }
                }
        }
コード例 #13
0
ファイル: KmlProvider.cs プロジェクト: mrpastewart/Core
        public List <Coordinates> ImportFile(Stream input, bool isKmz)
        {
            var coordinates = new List <Coordinates>();

            try
            {
                KmlFile file;
                if (isKmz)
                {
                    var kmz = KmzFile.Open(input);
                    file = kmz.GetDefaultKmlFile();
                }
                else
                {
                    file = KmlFile.Load(input);
                }


                Kml kml = file.Root as Kml;
                if (kml != null)
                {
                    foreach (var placemark in kml.Flatten().OfType <Placemark>())
                    {
                        Console.WriteLine(placemark.Name);

                        var coords = new Coordinates();
                        coords.Latitude  = placemark.CalculateBounds().Center.Latitude;
                        coords.Longitude = placemark.CalculateBounds().Center.Longitude;

                        coordinates.Add(coords);
                    }
                }
            }
            catch
            {
            }

            return(coordinates);
        }
コード例 #14
0
ファイル: KmzFileTest.cs プロジェクト: dahlbyk/SharpKml
        public void TestReadKml()
        {
            // Doc.kmz has two Kml files at the root level, a.kml and doc.kml,
            // which were added to the archive in that order. Assert that a.kml
            // is read instead of doc.kml.
            using (var stream = SampleData.CreateStream("Engine.Data.Doc.kmz"))
                using (var file = KmzFile.Open(stream))
                {
                    var kml = file.ReadKml();
                    Assert.That(kml.IndexOf("a.kml"), Is.Not.EqualTo(-1)); // Make sure the right file was found
                }

            // MultiKml.kmz has three Kml files added in the following order:
            // - z/c.kml
            // - b.kml
            // - a/a.kml
            // Each file has a placemark whose <name> is the archived filename.
            using (var stream = SampleData.CreateStream("Engine.Data.MultiKml.kmz"))
                using (var file = KmzFile.Open(stream))
                {
                    var kml = file.ReadKml();
                    Assert.That(kml.IndexOf("c.kml"), Is.Not.EqualTo(-1)); // Make sure z/c.kml was read
                }
        }
コード例 #15
0
 private Element ExtractElementFromFile(Stream stream, bool isKmz)
 {
     return(isKmz ?
            KmzFile.Open(stream).GetDefaultKmlFile()?.Root :
            KmlFile.Load(stream)?.Root);
 }
コード例 #16
0
        private void OpenFileButton_Click(object sender, RoutedEventArgs e)
        {
            // Create an instance of the open file dialog box.
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            // Set filter options and filter index.
            openFileDialog1.Filter      = "Google Earth (.kml .kmz)|*.kml;*.kmz";
            openFileDialog1.FilterIndex = 1;

            openFileDialog1.Multiselect = true;

            // Call the ShowDialog method to show the dialog box.
            bool?userClickedOK = openFileDialog1.ShowDialog();

            // Process input if the user clicked OK.
            if (userClickedOK == true)
            {
                KmlFile kmlFile  = null;
                string  fileName = openFileDialog1.FileName;

                string fileExtension = System.IO.Path.GetExtension(fileName);
                if (fileExtension.Equals(".kmz", StringComparison.OrdinalIgnoreCase))
                {
                    try {
                        using (Stream fileStream = File.OpenRead(fileName)) {
                            KmzFile kmzFile       = KmzFile.Open(fileStream);
                            string  kmlFileString = kmzFile.ReadKml();
                            using (StringReader stringReader = new StringReader(kmlFileString))
                            {
                                kmlFile = KmlFile.Load(stringReader);
                            }
                        };
                    } catch (Exception ex) {
                        MessageBox.Show(ex.Message, "Failed to open a KMZ file", MessageBoxButton.OK, MessageBoxImage.Error);
                        return;
                    }
                }
                else
                {
                    try {
                        using (Stream fileStream = File.OpenRead(fileName)) {
                            kmlFile = KmlFile.Load(fileStream);
                        };
                    } catch (Exception ex) {
                        MessageBox.Show(ex.Message, "Failed to open a KML file", MessageBoxButton.OK, MessageBoxImage.Error);
                        return;
                    }
                }
                KmlTreeViewController kmlTreeViewController = new KmlTreeViewController();
                kmlTreeViewController.SetTreeView(this.KmlItemsTreeView);
                kmlTreeViewController.SetKML(kmlFile);
                kmlTreeViewController.ProcessKml();
                kmlTreeViewController.TreeViewSelectionChanged += c_TreeViewSelectionChanged;

                KmlSchemaNameComboBoxController kmlSchemaComboBoxController = new KmlSchemaNameComboBoxController();
                kmlSchemaComboBoxController.SetComboBox(this.SchemaListComboBox);
                kmlSchemaComboBoxController.SetKML(kmlFile);
                kmlSchemaComboBoxController.ProcessKml();
                kmlSchemaComboBoxController.ComboBoxSelectionChanged += PropertySchemaSelectionChanged;

                kmlSchemaListViewController.SetListView(this.SchemaListView);
                kmlFeatureSchemaListViewController.SetListView(this.PropertySchemaListView);
            }
        }