예제 #1
11
        public string Write(Guid listGuid)
        {
            string kml = string.Empty;
            Serializer serializer = new Serializer();
            Kml _kml = new Kml();
            Folder folder = new Folder();
            UseWeb(spWeb =>
            {
                SPList list = spWeb.Lists.GetList(listGuid, true);
                SPField field = list.GetGeoField();
                if (field != null)
                {

                    foreach (SPListItem item in list.Items)
                    {
                        string wkt = item[field.Id] as string;
                        SimpleWKTReader wktReader = new SimpleWKTReader();
                        var simpleGeometry = wktReader.Parse(wkt);

                        if (simpleGeometry.GeometryType == GeometryTypes.Point)
                        {
                            var _point = (OpenSMIL.Server.SimpleFeature.GeomtryTypes.Point)simpleGeometry;
                            SharpKml.Dom.Point point = new SharpKml.Dom.Point();
                            point.Coordinate = new Vector(_point.Lat, _point.Lon);

                            Placemark placemark = CreatePlaceMark(item.Title, point);
                            folder.AddFeature(placemark);
                        }
                        else if (simpleGeometry.GeometryType == GeometryTypes.LineString)
                        {
                            var _lineString = (OpenSMIL.Server.SimpleFeature.GeomtryTypes.LineString)simpleGeometry;
                            SharpKml.Dom.LineString line = new SharpKml.Dom.LineString();
                            line.Coordinates = CreateCoordinateCollection(_lineString.Points);
                            Placemark placeMark = CreatePlaceMark(item.Title, line);
                            folder.AddFeature(placeMark);

                        }
                        else if (simpleGeometry.GeometryType == GeometryTypes.Polygon)
                        {
                            var _polygon = (OpenSMIL.Server.SimpleFeature.GeomtryTypes.Polygon)simpleGeometry;
                            OuterBoundary outerBoundary = new OuterBoundary();
                            outerBoundary.LinearRing = new LinearRing();
                            outerBoundary.LinearRing.Coordinates = CreateCoordinateCollection(_polygon.Points);

                            SharpKml.Dom.Polygon polygon = new SharpKml.Dom.Polygon();
                            polygon.OuterBoundary = outerBoundary;
                            polygon.Extrude = true;

                            Placemark placeMark = CreatePlaceMark(item.Title, polygon);
                            folder.AddFeature(placeMark);
                        }

                    }
                    _kml.Feature = folder;
                }
            });
            serializer.Serialize(_kml);
            return serializer.Xml;
        }
예제 #2
2
        public static Folder PlacemarkFolder(IQueryable<Cave> caves)
        {
            //List<Placemark> cavePlacemarkList = new List<Placemark>();
            Folder caveFolder = new Folder();
            caveFolder.Name = "Cave Folder";
            foreach (Cave cave in caves)
            {
                foreach (var entrance in cave.Entrances)
                {
                    Placemark placemark = new Placemark();
                    placemark.Name = cave.Name + " (E" + entrance.Name + ")";
                    placemark.Description = new Description() { Text = cave.Description };

                    Point point = new Point();
                    point.Coordinate = new Vector(entrance.GeoLocation.Latitude ?? 0, entrance.GeoLocation.Longitude ?? 0, entrance.GeoLocation.Elevation ?? 0);

                    placemark.Geometry = point;

                    caveFolder.AddFeature(placemark);
                }

            }

            return caveFolder;
        }
예제 #3
1
        private void writeKML(string filename)
        {
            Color[] colours = { Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Blue, Color.Indigo, Color.Violet, Color.Pink };

            Document kml = new Document();

            Tour tour = new Tour();
            tour.Name = "First Person View";
            Playlist tourplaylist = new Playlist();

            AddNamespace(kml, "gx", "http://www.google.com/kml/ext/2.2");

            Style style = new Style();
            style.Id = "yellowLineGreenPoly";
            style.Line = new LineStyle(new Color32(HexStringToColor("7f00ffff")), 4);

            PolygonStyle pstyle = new PolygonStyle();
            pstyle.Color = new Color32(HexStringToColor("7f00ff00"));
            style.Polygon = pstyle;

            kml.AddStyle(style);

            // create sub folders
            Folder planes = new Folder();
            planes.Name = "Planes";
            kml.AddFeature(planes);

            // coords for line string
            CoordinateCollection coords = new CoordinateCollection();

            int a = 1;
            int c = -1;
            DateTime lasttime = DateTime.MaxValue;
            DateTime starttime = DateTime.MinValue;
            Color stylecolor = Color.AliceBlue;
            string mode = "";
            if (flightdata.Count > 0)
            {
                mode = flightdata[0].mode;
            }
            foreach (CurrentState cs in flightdata)
            {
                progressBar1.Value = 50 + (int)((float)a / (float)flightdata.Count * 100.0f / 2.0f);
                progressBar1.Refresh();

                if (starttime == DateTime.MinValue)
                {
                    starttime = cs.datetime;
                    lasttime = cs.datetime;
                }

                if (mode != cs.mode || flightdata.Count == a)
                {
                    c++;

                    LineString ls = new LineString();
                    ls.AltitudeMode = SharpKml.Dom.AltitudeMode.Absolute;
                    ls.Extrude = true;

                    ls.Coordinates = coords;

                    Placemark pm = new Placemark();

                    pm.Name = c + " Flight Path " + mode;
                    pm.StyleUrl = new Uri("#yellowLineGreenPoly", UriKind.Relative);
                    pm.Geometry = ls;

                    SharpKml.Dom.TimeSpan ts = new SharpKml.Dom.TimeSpan();
                    ts.Begin = starttime;
                    ts.End = cs.datetime;

                    pm.Time = ts;

                    // setup for next line
                    mode = cs.mode;
                    starttime = cs.datetime;

                    stylecolor = colours[c % (colours.Length - 1)];

                    Style style2 = new Style();
                    style2.Line = new LineStyle(new Color32(stylecolor), 4);

                    pm.StyleSelector = style2;

                    kml.AddFeature(pm);

                    coords = new CoordinateCollection();
                }

                coords.Add(new Vector(cs.lat, cs.lng, cs.alt));

                SharpKml.Dom.Timestamp tstamp = new SharpKml.Dom.Timestamp();
                tstamp.When = cs.datetime;

                FlyTo flyto = new FlyTo();

                flyto.Duration = (cs.datetime - lasttime).TotalMilliseconds / 1000.0;

                flyto.Mode = FlyToMode.Smooth;
                SharpKml.Dom.Camera cam = new SharpKml.Dom.Camera();
                cam.AltitudeMode = SharpKml.Dom.AltitudeMode.Absolute;
                cam.Latitude = cs.lat;
                cam.Longitude = cs.lng;
                cam.Altitude = cs.alt;
                cam.Heading = cs.yaw;
                cam.Roll = -cs.roll;
                cam.Tilt = (90 - (cs.pitch * -1));

                cam.GXTimePrimitive = tstamp;

                flyto.View = cam;
                //if (Math.Abs(flyto.Duration.Value) > 0.1)
                {
                    tourplaylist.AddTourPrimitive(flyto);
                    lasttime = cs.datetime;
                }

                Placemark pmplane = new Placemark();
                pmplane.Name = "Plane " + a;

                pmplane.Time = tstamp;

                pmplane.Visibility = false;

                SharpKml.Dom.Location loc = new SharpKml.Dom.Location();
                loc.Latitude = cs.lat;
                loc.Longitude = cs.lng;
                loc.Altitude = cs.alt;

                SharpKml.Dom.Orientation ori = new SharpKml.Dom.Orientation();
                ori.Heading = cs.yaw;
                ori.Roll = -cs.roll;
                ori.Tilt = -cs.pitch;

                SharpKml.Dom.Scale sca = new SharpKml.Dom.Scale();

                sca.X = 2;
                sca.Y = 2;
                sca.Z = 2;

                Model model = new Model();
                model.Location = loc;
                model.Orientation = ori;
                model.AltitudeMode = SharpKml.Dom.AltitudeMode.Absolute;
                model.Scale = sca;

                try
                {
                    Description desc = new Description();
                    desc.Text = @"<![CDATA[
              <table>
                <tr><td>Roll: " + model.Orientation.Roll + @" </td></tr>
                <tr><td>Pitch: " + model.Orientation.Tilt + @" </td></tr>
                <tr><td>Yaw: " + model.Orientation.Heading + @" </td></tr>

              </table>
            ]]>";

                    pmplane.Description = desc;
                }
                catch { }

                Link link = new Link();
                link.Href = new Uri("block_plane_0.dae", UriKind.Relative);

                model.Link = link;

                pmplane.Geometry = model;

                planes.AddFeature(pmplane);

                a++;
            }

            tour.Playlist = tourplaylist;

            kml.AddFeature(tour);

            Serializer serializer = new Serializer();
            serializer.Serialize(kml);

            //Console.WriteLine(serializer.Xml);

            StreamWriter sw = new StreamWriter(filename);
            sw.Write(serializer.Xml);
            sw.Close();

            // create kmz - aka zip file

            FileStream fs = File.Open(filename.Replace(Path.GetExtension(filename), ".kmz"), FileMode.Create);
            ZipOutputStream zipStream = new ZipOutputStream(fs);
            zipStream.SetLevel(9); //0-9, 9 being the highest level of compression
            zipStream.UseZip64 = UseZip64.Off; // older zipfile

            // entry 1
            string entryName = ZipEntry.CleanName(Path.GetFileName(filename)); // Removes drive from name and fixes slash direction
            ZipEntry newEntry = new ZipEntry(entryName);
            newEntry.DateTime = DateTime.Now;

            zipStream.PutNextEntry(newEntry);

            // Zip the file in buffered chunks
            // the "using" will close the stream even if an exception occurs
            byte[] buffer = new byte[4096];
            using (FileStream streamReader = File.Open(filename,FileMode.Open,FileAccess.Read,FileShare.ReadWrite))
            {
                StreamUtils.Copy(streamReader, zipStream, buffer);
            }
            zipStream.CloseEntry();

            filename = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + "block_plane_0.dae";

            // entry 2
            entryName = ZipEntry.CleanName(Path.GetFileName(filename)); // Removes drive from name and fixes slash direction
            newEntry = new ZipEntry(entryName);
            newEntry.DateTime = DateTime.Now;

            zipStream.PutNextEntry(newEntry);

            // Zip the file in buffered chunks
            // the "using" will close the stream even if an exception occurs
            buffer = new byte[4096];
            using (FileStream streamReader = File.OpenRead(filename))
            {
                StreamUtils.Copy(streamReader, zipStream, buffer);
            }
            zipStream.CloseEntry();

            zipStream.IsStreamOwner = true;	// Makes the Close also Close the underlying stream
            zipStream.Close();

            File.Delete(filename);

            flightdata.Clear();
        }
예제 #4
0
        public void TestClone()
        {
            Placemark placemark = null;
            Assert.That(() => placemark.Clone(),
                        Throws.TypeOf<ArgumentNullException>());

            placemark = new Placemark();
            placemark.Id = "ID";
            placemark.Geometry = new Point();
            var clone = placemark.Clone();

            Assert.That(clone, Is.Not.SameAs(placemark));
            Assert.That(clone.Id, Is.EqualTo(placemark.Id));  // Test attribute
            Assert.That(clone.Geometry, Is.Not.Null); // Test element

            // Make sure as we change one the other doesn't
            ((Point)clone.Geometry).Extrude = true;
            Assert.That(((Point)clone.Geometry).Extrude,
                       Is.Not.EqualTo(((Point)placemark.Geometry).Extrude));

            Folder folder = new Folder();
            folder.AddFeature(placemark);
            folder.AddFeature(new Document());

            var copy = folder.Clone();
            Assert.That(copy.Features.Count(), Is.EqualTo(folder.Features.Count()));
            placemark.Id = "changed";
            Assert.That(folder.FindFeature(placemark.Id), Is.Not.Null);
            Assert.That(copy.FindFeature(placemark.Id), Is.Null);
        }
예제 #5
0
        public static void Run()
        {
            var point = new sd.Point
            {
                Coordinate = new sb.Vector(37.42052549, -122.0816695)
            };

            var placemark = new sd.Placemark
            {
                Name     = "Да круто",
                Geometry = point
            };

            var point1 = new sd.Point
            {
                Coordinate = new sb.Vector(37.419837, -122.078902)
            };

            var placemark1 = new sd.Placemark
            {
                Name     = "Да круто",
                Geometry = point1
            };

            var document = new sd.Document
            {
                Description = new sd.Description {
                    Text = "Документ"
                }
            };

            var kml = new sd.Kml
            {
                Feature = document
            };

            var folder = new sd.Folder
            {
                Description = new sd.Description {
                    Text = "Светофоры"
                },
                Name = "СО"
            };

            folder.AddFeature(placemark);
            document.AddFeature(folder);
            document.AddFeature(placemark1);

            //var serializer = new sb.Serializer();

            //using FileStream fileStream = new FileStream("kmlTest.kml", FileMode.OpenOrCreate);
            //serializer.Serialize(kml, fileStream);
            var kmlFile = KmlFile.Create(kml, true);

            //using KmzFile kmz = SaveKmlAndLinkedContentIntoAKmzArchive(kmlFile, OutputPath);
            //using Stream output = File.Create(OutputPath);
            //kmz.Save(output);
            //Console.WriteLine("Saved to '{0}'.", OutputPath);
            //Console.ReadKey();
        }
예제 #6
0
        public void TestAddChild()
        {
            var child = new Placemark();
            var parent1 = new Folder();
            var parent2 = new Folder();

            parent1.AddFeature(child);

            // child belongs to another element, should throw
            Assert.That(() => parent2.AddFeature(child),
                        Throws.TypeOf<InvalidOperationException>());

            // child has already been added once
            Assert.That(() => parent1.AddFeature(child),
                        Throws.TypeOf<InvalidOperationException>());
        }
예제 #7
0
파일: Change.cs 프로젝트: karun10/KML2SQL
        public static void Run()
        {
            // Create our Kml
            var folder = new Folder();
            folder.Id = "f0";
            folder.Name = "Folder 0";

            var placemark = new Placemark();
            placemark.Id = "pm0";
            placemark.Name = "Placemark 0";
            folder.AddFeature(placemark);

            placemark = new Placemark();
            placemark.Id = "pm1";
            placemark.Name = "Placemark 1";
            folder.AddFeature(placemark);

            var kml = new Kml();
            kml.Feature = folder;

            // Display to the user
            var serializer = new Serializer();
            serializer.Serialize(kml);
            Console.WriteLine("Original Kml:\n" + serializer.Xml);

            // This is what we're going to change to
            placemark = new Placemark();
            placemark.Geometry = new Point { Coordinate = new Vector(38, -120) };
            placemark.Name = "new name";
            placemark.TargetId = "pm0";

            var update = new Update();
            update.AddUpdate(new ChangeCollection() { placemark });

            serializer.Serialize(update);
            Console.WriteLine("\nUpdate:\n" + serializer.Xml);

            // Run the update
            var file = KmlFile.Create(kml, false);
            update.Process(file);

            serializer.Serialize(kml);
            Console.WriteLine("\nUpdated Kml:\n" + serializer.Xml);
        }
예제 #8
0
        /// <summary>
        /// Assembles location to folder.
        /// </summary>
        /// <param name="dbLocation">The database location.</param>
        /// <returns>Dom.Folder.</returns>
        private static Dom.Folder AssembleToFolder(FormationMatcher dbLocation)
        {
            Dom.Folder locationGroup = new Dom.Folder {
                Name = dbLocation.FormationName
            };
            if (!string.IsNullOrWhiteSpace(dbLocation.SubFormationName))
            {
                locationGroup.Name += " (" + dbLocation.SubFormationName + ")";
            }
            Location location = dbLocation.MatchedLocation;

            if (location == null)
            {
                return(locationGroup);
            }

            // This will be used for the placemark
            Dom.Point point = new Dom.Point {
                Coordinate = new Vector(location.Latitude, location.Longitude)
            };

            Dom.Placemark placemark = new Dom.Placemark {
                Name = location.Name
            };
            if (!string.IsNullOrWhiteSpace(location.OtherName))
            {
                placemark.Name += " (" + location.OtherName + ")";
            }
            placemark.Geometry = point;

            locationGroup.AddFeature(placemark);
            //foreach (PeakbaggerLocation location in dbLocation.PossibleLocations)
            //{
            //    // This will be used for the placemark
            //    Dom.Point point = new Dom.Point {Coordinate = new Vector(location.Latitude, location.Longitude)};

            //    Dom.Placemark placemark = new Dom.Placemark {Name = location.Name};
            //    if (!string.IsNullOrWhiteSpace(location.OtherName))
            //    {
            //        placemark.Name += " (" + location.OtherName + ")";
            //    }
            //    placemark.Geometry = point;

            //    locationGroup.AddFeature(placemark);
            //}
            return(locationGroup);

            // Add to the root
            //kml.Feature = locationGroup;

            //WriteToKml(filePath, kml);
            //Console.WriteLine(serializer.Xml);
        }
예제 #9
0
        /// <summary>
        /// Assembles list of regions to folder.
        /// </summary>
        /// <param name="dbRegions">The database regions.</param>
        /// <returns>Dom.Folder.</returns>
        private static Dom.Folder AssembleToFolder(List <Region> dbRegions)
        {
            Dom.Folder regions = new Dom.Folder {
                Name = "Regions"
            };

            foreach (Region region in dbRegions)
            {
                Dom.Folder regionFolder = AssembleToFolder(region);
                regions.AddFeature(regionFolder);
            }
            return(regions);
        }
예제 #10
0
        /// <summary>
        /// Assembles region folder with locations.
        /// </summary>
        /// <param name="dbRegion">The database region.</param>
        /// <returns>Dom.Folder.</returns>
        private static Dom.Folder AssembleToFolder(Region dbRegion)
        {
            Dom.Folder region = new Dom.Folder {
                Name = dbRegion.Name
            };

            foreach (FormationMatcher location in dbRegion.Locations)
            {
                Dom.Folder locationFolder = AssembleToFolder(location);
                region.AddFeature(locationFolder);
            }
            return(region);
        }
예제 #11
0
        public void TestWalkChildren()
        {
            const int Depth = 50;

            Folder parent = new Folder();
            Folder root = parent;
            for (int i = 0; i < Depth; ++i)
            {
                Folder child = new Folder();
                parent.AddFeature(child); // Added to the Children collection
                parent = child;
            }

            Assert.That(ElementWalker.Walk(root).Count(), Is.EqualTo(Depth + 1)); // Depth + 1 to allow for root itself
        }
예제 #12
0
        public void TestGetParent()
        {
            Placemark placemark = null;
            Assert.That(() => placemark.GetParent<Folder>(),
                        Throws.TypeOf<ArgumentNullException>());

            placemark = new Placemark();
            Assert.That(placemark.GetParent<Folder>(), Is.Null);

            var folder = new Folder();
            folder.AddFeature(placemark);
            Assert.That(placemark.GetParent<Folder>(), Is.SameAs(folder));
            Assert.That(placemark.GetParent<Kml>(), Is.Null);

            var kml = new Kml();
            kml.Feature = folder;
            Assert.That(placemark.GetParent<Kml>(), Is.SameAs(kml));
        }
예제 #13
0
        public void TestManyDeletes()
        {
            const int NumberOfFolders = 100;

            var folder = new Folder();
            for (int i = 0; i < NumberOfFolders; ++i)
            {
                folder.AddFeature(CreateFeature(i, true)); // Add the features with their Id set
            }
            Assert.That(folder.Features.Count(), Is.EqualTo(NumberOfFolders));

            KmlFile file = KmlFile.Create(folder, false);
            var update = new Update();
            for (int i = 0; i < NumberOfFolders; ++i)
            {
                var delete = new DeleteCollection();
                delete.Add(CreateFeature(i, false)); // This time set the TargetId
                update.AddUpdate(delete);
            }
            update.Process(file);
            Assert.That(folder.Features.Count(), Is.EqualTo(0));
        }
예제 #14
0
        public void AddPoint(Point point, string idStyle, Dictionary <string, string> dicData, sd.Folder folder = null)
        {
            var pointDoc = new sd.Point
            {
                Coordinate = new sb.Vector(point.Lat, point.Lon)
            };

            var placemark = new sd.Placemark
            {
                Name         = point.Name,
                Geometry     = pointDoc,
                StyleUrl     = new Uri($"#{idStyle}", UriKind.Relative),
                ExtendedData = ExtendedData(dicData)
            };

            if (folder == null)
            {
                Document.AddFeature(placemark);
            }
            else
            {
                folder.AddFeature(placemark);
            }
        }
예제 #15
0
        public void AddPoint(Point point, string idStyle, Dictionary <string, string> dicData, sd.Folder folder = null)
        {
            var pointDoc = new sd.Point
            {
                Coordinate = new sb.Vector(point.Lon, point.Lat)
            };

            var exdata = new sd.ExtendedData();

            foreach (var data in dicData)
            {
                var dataDoc = new sd.Data
                {
                    Name  = data.Key,
                    Value = data.Value
                };
                exdata.AddData(dataDoc);
            }

            var placemark = new sd.Placemark
            {
                Name         = point.Name,
                Geometry     = pointDoc,
                StyleUrl     = new Uri($"#{idStyle}"),
                ExtendedData = exdata
            };

            if (folder == null)
            {
                Document.AddFeature(placemark);
            }
            else
            {
                folder.AddFeature(placemark);
            }
        }
예제 #16
0
        static void GenerateKML(int stav, IEnumerable <Most> data)
        {
            int page = 1;

            Kml kml = new Kml();

            var style0 = new Style();

            style0.Id             = "stav0"; style0.Icon = new IconStyle();
            style0.Icon.Color     = new SharpKml.Base.Color32(255, 00, 200, 0); //yell
            style0.Icon.ColorMode = ColorMode.Normal; style0.Icon.Scale = 1.0;

            var style5 = new Style();

            style5.Id             = "stav5"; style5.Icon = new IconStyle();
            style5.Icon.Color     = new SharpKml.Base.Color32(255, 66, 191, 244); //yell
            style5.Icon.ColorMode = ColorMode.Normal; style5.Icon.Scale = 1.0;

            var style6 = new Style();

            style6.Id             = "stav6"; style6.Icon = new IconStyle();
            style6.Icon.Color     = new SharpKml.Base.Color32(255, 66, 134, 244); //ORAnGE
            style6.Icon.ColorMode = ColorMode.Normal; style6.Icon.Scale = 1.0;

            var style7 = new Style();

            style7.Id             = "stav7"; style7.Icon = new IconStyle();
            style7.Icon.Color     = new SharpKml.Base.Color32(255, 0, 0, 255); //red
            style7.Icon.ColorMode = ColorMode.Normal; style7.Icon.Scale = 1.0;

            var document = new Document();

            document.AddStyle(style0); document.AddStyle(style5);
            document.AddStyle(style6); document.AddStyle(style7);

            var fdata = new SharpKml.Dom.Folder();

            fdata.Name = "Stav " + stav;
            foreach (var m in data.Where(m => m.Stav == stav))
            {
                Point point = new Point();
                point.Coordinate = new SharpKml.Base.Vector(m.GPS_Lat, m.GPS_Lng);

                Placemark placemark = new Placemark();
                placemark.Id          = m.Id;
                placemark.Name        = m.Jmeno;
                placemark.Description = new Description()
                {
                    Text = $"{m.MistniNazev}. Stav {m.PopisStavu}. Poslední kontrola: {m.ProhlidkaPopis}"
                };

                var style = "#stav";
                if (m.Stav > 4)
                {
                    style = style + m.Stav;
                }
                else
                {
                    style = style + "0";
                }

                placemark.StyleUrl     = new Uri(style, UriKind.Relative);
                placemark.ExtendedData = new ExtendedData();
                placemark.ExtendedData.AddData(new Data()
                {
                    Value = m.MistniNazev, Name = "Mistni nazev"
                });
                placemark.ExtendedData.AddData(new Data()
                {
                    Value = m.Oznaceni, Name = "Označení"
                });
                placemark.ExtendedData.AddData(new Data()
                {
                    Value = m.PopisStavu, Name = "Stav"
                });
                placemark.ExtendedData.AddData(new Data()
                {
                    Value = m.ProhlidkaPopis, Name = "Poslední prohlídka"
                });
                placemark.ExtendedData.AddData(new Data()
                {
                    Value = m.SpravaOrganizace, Name = "Spravující organizace"
                });
                placemark.ExtendedData.AddData(new Data()
                {
                    Value = m.SpravaProvozniUsek, Name = "Spravující provozní úsek"
                });
                placemark.ExtendedData.AddData(new Data()
                {
                    Value = m.SpravaStredisko, Name = "Spravující středisko"
                });
                placemark.Geometry = point;
                fdata.AddFeature(placemark);
                //fdata.AddChild(placemark);
            }

            document.AddFeature(fdata);



            kml.Feature = document;
            //kml.AddChild(document);
            SharpKml.Base.Serializer serializer = new SharpKml.Base.Serializer();
            serializer.Serialize(kml);
            System.IO.File.WriteAllText($"mosty_{stav}.kml", serializer.Xml);
        }
예제 #17
0
        private void CreateReportFiles(Dictionary<string, PictureInformation> listPhotosWithInfo, string dirWithImages,
            float offset)
        {
            // Write report files
            Document kmlroot = new Document();
            Folder kml = new Folder("Pins");

            Folder overlayfolder = new Folder("Overlay");

            // add root folder to document
            kmlroot.AddFeature(kml);
            kmlroot.AddFeature(overlayfolder);

            // Clear Stations IDs
            JXL_StationIDs.Clear();

            using (
                StreamWriter swlogloccsv =
                    new StreamWriter(dirWithImages + Path.DirectorySeparatorChar + "loglocation.csv"))
            using (
                StreamWriter swlockml = new StreamWriter(dirWithImages + Path.DirectorySeparatorChar + "location.kml"))
            using (
                StreamWriter swloctxt = new StreamWriter(dirWithImages + Path.DirectorySeparatorChar + "location.txt"))
            using (
                StreamWriter swloctel = new StreamWriter(dirWithImages + Path.DirectorySeparatorChar + "location.tel"))
            using (
                XmlTextWriter swloctrim = new XmlTextWriter(
                    dirWithImages + Path.DirectorySeparatorChar + "location.jxl", Encoding.ASCII))
            {
                swloctrim.Formatting = Formatting.Indented;
                swloctrim.WriteStartDocument(false);
                swloctrim.WriteStartElement("JOBFile");
                swloctrim.WriteAttributeString("jobName", "MPGeoRef");
                swloctrim.WriteAttributeString("product", "Gatewing");
                swloctrim.WriteAttributeString("productVersion", "1.0");
                swloctrim.WriteAttributeString("version", "5.6");
                // enviro
                swloctrim.WriteStartElement("Environment");
                swloctrim.WriteStartElement("CoordinateSystem");
                swloctrim.WriteElementString("SystemName", "Default");
                swloctrim.WriteElementString("ZoneName", "Default");
                swloctrim.WriteElementString("DatumName", "WGS 1984");
                swloctrim.WriteStartElement("Ellipsoid");
                swloctrim.WriteElementString("EarthRadius", "6378137");
                swloctrim.WriteElementString("Flattening", "0.00335281067183");
                swloctrim.WriteEndElement();
                swloctrim.WriteStartElement("Projection");
                swloctrim.WriteElementString("Type", "NoProjection");
                swloctrim.WriteElementString("Scale", "1");
                swloctrim.WriteElementString("GridOrientation", "IncreasingNorthEast");
                swloctrim.WriteElementString("SouthAzimuth", "false");
                swloctrim.WriteElementString("ApplySeaLevelCorrection", "true");
                swloctrim.WriteEndElement();
                swloctrim.WriteStartElement("LocalSite");
                swloctrim.WriteElementString("Type", "Grid");
                swloctrim.WriteElementString("ProjectLocationLatitude", "");
                swloctrim.WriteElementString("ProjectLocationLongitude", "");
                swloctrim.WriteElementString("ProjectLocationHeight", "");
                swloctrim.WriteEndElement();
                swloctrim.WriteStartElement("Datum");
                swloctrim.WriteElementString("Type", "ThreeParameter");
                swloctrim.WriteElementString("GridName", "WGS 1984");
                swloctrim.WriteElementString("Direction", "WGS84ToLocal");
                swloctrim.WriteElementString("EarthRadius", "6378137");
                swloctrim.WriteElementString("Flattening", "0.00335281067183");
                swloctrim.WriteElementString("TranslationX", "0");
                swloctrim.WriteElementString("TranslationY", "0");
                swloctrim.WriteElementString("TranslationZ", "0");
                swloctrim.WriteEndElement();
                swloctrim.WriteStartElement("HorizontalAdjustment");
                swloctrim.WriteElementString("Type", "NoAdjustment");
                swloctrim.WriteEndElement();
                swloctrim.WriteStartElement("VerticalAdjustment");
                swloctrim.WriteElementString("Type", "NoAdjustment");
                swloctrim.WriteEndElement();
                swloctrim.WriteStartElement("CombinedScaleFactor");
                swloctrim.WriteStartElement("Location");
                swloctrim.WriteElementString("Latitude", "");
                swloctrim.WriteElementString("Longitude", "");
                swloctrim.WriteElementString("Height", "");
                swloctrim.WriteEndElement();
                swloctrim.WriteElementString("Scale", "");
                swloctrim.WriteEndElement();

                swloctrim.WriteEndElement();
                swloctrim.WriteEndElement();

                // fieldbook
                swloctrim.WriteStartElement("FieldBook");

                swloctrim.WriteRaw(@"   <CameraDesignRecord ID='00000001'>
                                      <Type>GoPro   </Type>
                                      <HeightPixels>2400</HeightPixels>
                                      <WidthPixels>3200</WidthPixels>
                                      <PixelSize>0.0000022</PixelSize>
                                      <LensModel>Rectilinear</LensModel>
                                      <NominalFocalLength>0.002</NominalFocalLength>
                                    </CameraDesignRecord>
                                    <CameraRecord2 ID='00000002'>
                                      <CameraDesignID>00000001</CameraDesignID>
                                      <CameraPosition>01</CameraPosition>
                                      <Optics>
                                        <IdealAngularMagnification>1.0</IdealAngularMagnification>
                                        <AngleSymmetricDistortion>
                                          <Order3>-0.35</Order3>
                                          <Order5>0.15</Order5>
                                          <Order7>-0.033</Order7>
                                          <Order9> 0</Order9>
                                        </AngleSymmetricDistortion>
                                        <AngleDecenteringDistortion>
                                          <Column>0</Column>
                                          <Row>0</Row>
                                        </AngleDecenteringDistortion>
                                      </Optics>
                                      <Geometry>
                                        <PerspectiveCenterPixels>
                                          <PrincipalPointColumn>-1615.5</PrincipalPointColumn>
                                          <PrincipalPointRow>-1187.5</PrincipalPointRow>
                                          <PrincipalDistance>-2102</PrincipalDistance>
                                        </PerspectiveCenterPixels>
                                        <VectorOffset>
                                          <X>0</X>
                                          <Y>0</Y>
                                          <Z>0</Z>
                                        </VectorOffset>
                                        <BiVectorAngle>
                                          <XX>0</XX>
                                          <YY>0</YY>
                                          <ZZ>-1.5707963268</ZZ>
                                        </BiVectorAngle>
                                      </Geometry>
                                    </CameraRecord2>");

                // 2mm fl
                // res 2400 * 3200 = 7,680,000
                // sensor size = 1/2.5" - 5.70 × 4.28 mm
                // 2.2 μm
                // fl in pixels = fl in mm * res / sensor size

                swloctrim.WriteStartElement("PhotoInstrumentRecord");
                swloctrim.WriteAttributeString("ID", "0000000E");
                swloctrim.WriteElementString("Type", "Aerial");
                swloctrim.WriteElementString("Model", "X100");
                swloctrim.WriteElementString("Serial", "000-000");
                swloctrim.WriteElementString("FirmwareVersion", "v0.0");
                swloctrim.WriteElementString("UserDefinedName", "Prototype");
                swloctrim.WriteEndElement();

                swloctrim.WriteStartElement("AtmosphereRecord");
                swloctrim.WriteAttributeString("ID", "0000000F");
                swloctrim.WriteElementString("Pressure", "");
                swloctrim.WriteElementString("Temperature", "");
                swloctrim.WriteElementString("PPM", "");
                swloctrim.WriteElementString("ApplyEarthCurvatureCorrection", "false");
                swloctrim.WriteElementString("ApplyRefractionCorrection", "false");
                swloctrim.WriteElementString("RefractionCoefficient", "0");
                swloctrim.WriteElementString("PressureInputMethod", "ReadFromInstrument");
                swloctrim.WriteEndElement();

                swloctel.WriteLine("version=1");

                swloctel.WriteLine("#seconds offset - " + offset);
                swloctel.WriteLine("#longitude and latitude - in degrees");
                swloctel.WriteLine("#name	utc	longitude	latitude	height");

                swloctxt.WriteLine("#name latitude/Y longitude/X height/Z yaw pitch roll");

                TXT_outputlog.AppendText("Start Processing\n");

                // Dont know why but it was 10 in the past so let it be. Used to generate jxl file simulating x100 from trimble
                int lastRecordN = JXL_ID_OFFSET;

                // path
                CoordinateCollection coords = new CoordinateCollection();

                foreach (var item in vehicleLocations.Values)
                {
                    if (item != null)
                        coords.Add(new SharpKml.Base.Vector(item.Lat, item.Lon, item.AltAMSL));
                }

                var ls = new LineString() {Coordinates = coords, AltitudeMode = AltitudeMode.Absolute};

                SharpKml.Dom.Placemark pm = new SharpKml.Dom.Placemark() {Geometry = ls, Name = "path"};

                kml.AddFeature(pm);

                foreach (PictureInformation picInfo in listPhotosWithInfo.Values)
                {
                    string filename = Path.GetFileName(picInfo.Path);
                    string filenameWithoutExt = Path.GetFileNameWithoutExtension(picInfo.Path);

                    SharpKml.Dom.Timestamp tstamp = new SharpKml.Dom.Timestamp();

                    tstamp.When = picInfo.Time;

                    kml.AddFeature(
                        new Placemark()
                        {
                            Time = tstamp,
                            Visibility = true,
                            Name = filenameWithoutExt,
                            Geometry = new SharpKml.Dom.Point()
                            {
                                Coordinate = new Vector(picInfo.Lat, picInfo.Lon, picInfo.AltAMSL),
                                AltitudeMode = AltitudeMode.Absolute
                            },
                            Description = new Description()
                            {
                                Text =
                                    "<table><tr><td><img src=\"" + filename.ToLower() +
                                    "\" width=500 /></td></tr></table>"
                            },
                            StyleSelector = new Style()
                            {
                                Balloon = new BalloonStyle() {Text = "$[name]<br>$[description]"}
                            }
                        }
                        );

                    double lat = picInfo.Lat;
                    double lng = picInfo.Lon;
                    double alpha = picInfo.Yaw + (double) num_camerarotation.Value;

                    RectangleF rect = getboundingbox(lat, lng, alpha, (double) num_hfov.Value, (double) num_vfov.Value);

                    Console.WriteLine(rect);

                    //http://en.wikipedia.org/wiki/World_file
                    /* using (StreamWriter swjpw = new StreamWriter(dirWithImages + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(filename) + ".jgw"))
                        {
                            swjpw.WriteLine((rect.Height / 2448.0).ToString("0.00000000000000000"));
                            swjpw.WriteLine((0).ToString("0.00000000000000000")); // 
                            swjpw.WriteLine((0).ToString("0.00000000000000000")); //
                            swjpw.WriteLine((rect.Width / -3264.0).ToString("0.00000000000000000")); // distance per pixel
                            swjpw.WriteLine((rect.Left).ToString("0.00000000000000000"));
                            swjpw.WriteLine((rect.Top).ToString("0.00000000000000000"));

                            swjpw.Close();
                        }*/

                    overlayfolder.AddFeature(
                        new GroundOverlay()
                        {
                            Name = filenameWithoutExt,
                            Visibility = false,
                            Time = tstamp,
                            AltitudeMode = AltitudeMode.ClampToGround,
                            Bounds = new LatLonBox()
                            {
                                Rotation = -alpha%360,
                                North = rect.Bottom,
                                East = rect.Right,
                                West = rect.Left,
                                South = rect.Top,
                            },
                            Icon = new SharpKml.Dom.Icon()
                            {
                                Href = new Uri(filename.ToLower(), UriKind.Relative),
                            },
                        }
                        );

                    swloctxt.WriteLine(filename + " " + picInfo.Lat + " " + picInfo.Lon + " " +
                                       picInfo.getAltitude(useAMSLAlt) + " " + picInfo.Yaw + " " + picInfo.Pitch + " " +
                                       picInfo.Roll);


                    swloctel.WriteLine(filename + "\t" + picInfo.Time.ToString("yyyy:MM:dd HH:mm:ss") + "\t" +
                                       picInfo.Lon + "\t" + picInfo.Lat + "\t" + picInfo.getAltitude(useAMSLAlt));
                    swloctel.Flush();
                    swloctxt.Flush();

                    lastRecordN = GenPhotoStationRecord(swloctrim, picInfo.Path, picInfo.Lat, picInfo.Lon,
                        picInfo.getAltitude(useAMSLAlt), 0, 0, picInfo.Yaw, picInfo.Width, picInfo.Height, lastRecordN);

                    log.InfoFormat(filename + " " + picInfo.Lon + " " + picInfo.Lat + " " +
                                   picInfo.getAltitude(useAMSLAlt) + "           ");
                }

                Serializer serializer = new Serializer();
                serializer.Serialize(kmlroot);
                swlockml.Write(serializer.Xml);

                Utilities.httpserver.georefkml = serializer.Xml;
                Utilities.httpserver.georefimagepath = dirWithImages + Path.DirectorySeparatorChar;

                writeGPX(dirWithImages + Path.DirectorySeparatorChar + "location.gpx", listPhotosWithInfo);

                // flightmission
                GenFlightMission(swloctrim, lastRecordN);

                swloctrim.WriteEndElement(); // fieldbook
                swloctrim.WriteEndElement(); // job
                swloctrim.WriteEndDocument();

                TXT_outputlog.AppendText("Done \n\n");
            }
        }
예제 #18
0
        /// <summary>
        /// Converts a dictionary representing JSON layer definitions to KML.
        /// </summary>
        /// <param name="layers">A dictionary representing ArcGIS JSON Layers.</param>
        /// <returns><see cref="Kml"/></returns>
        public static Kml LayersDictionaryToKml(this Dictionary<string, object> layers)
        {
            var kmlDocument = new SharpKml.Dom.Document();

            foreach (var kvp in layers)
            {
                var folder = new Folder { Name = kvp.Key };
                kmlDocument.AddFeature(folder);
                var graphics = kvp.Value as ArrayList;
                foreach (Dictionary<string, object> graphic in graphics)
                {
                    var placemark = new Placemark();
                    folder.AddFeature(placemark);
                    placemark.Geometry = JsonToKmlGeometry(graphic["geometry"] as Dictionary<string, object>);
                    var attributesJson = (Dictionary<string, object>)graphic["attributes"];
                    attributesJson.Remove("RouteGeometry");
                    placemark.ExtendedData = ToExtendedData(attributesJson);
                }
            }

            var kml = new Kml();
            kml.Feature = kmlDocument;
            return kml;
        }
예제 #19
0
        public void TestIsChildOf()
        {
            Placemark placemark = null;
            Assert.That(() => placemark.IsChildOf<Folder>(),
                        Throws.TypeOf<ArgumentNullException>());

            placemark = new Placemark();
            Assert.False(placemark.IsChildOf<Folder>());

            var folder = new Folder();
            folder.AddFeature(placemark);
            Assert.True(placemark.IsChildOf<Folder>());
            Assert.False(placemark.IsChildOf<Kml>());

            var kml = new Kml();
            kml.Feature = folder;
            Assert.True(placemark.IsChildOf<Kml>());
        }
예제 #20
0
        public void TestMergeChildren()
        {
            var source = new Folder();
            source.AddFeature(new Folder { Id = "SubFolder1" });
            source.AddFeature(new Folder { Id = "SubFolder2" });

            var target = new Folder();
            target.AddFeature(new Placemark { Id = "Placemark1" });
            target.AddFeature(new Placemark { Id = "Placemark2" });

            target.Merge(source);
            Assert.That(target.Features.Count(), Is.EqualTo(4));
            Assert.That(target.Features.ElementAt(3).Id, Is.EqualTo("SubFolder2"));
        }
예제 #21
0
        public void TestCalculateLookAtFolder()
        {
            Location location = new Location();
            location.Latitude = 0;
            location.Longitude = 0;

            Model model = new Model();
            model.Location = location;

            Placemark placemark = new Placemark();
            placemark.Geometry = model;

            Folder folder = new Folder();
            folder.AddFeature(placemark);

            var lookat = folder.CalculateLookAt();
            Assert.That(lookat.Latitude, Is.EqualTo(0.0));
            Assert.That(lookat.Longitude, Is.EqualTo(0.0));
            Assert.That(lookat.Range, Is.EqualTo(1000.0));

            Point point = new Point();
            point.Coordinate = new Vector(10, 10);

            PhotoOverlay overlay = new PhotoOverlay();
            overlay.Location = point;

            folder.AddFeature(overlay);
            lookat = folder.CalculateLookAt();
            Assert.That(lookat.Latitude, Is.EqualTo(5.0));
            Assert.That(lookat.Longitude, Is.EqualTo(5.0));
            Assert.That(lookat.Range, Is.EqualTo(1494183.4444).Within(0.0001));
        }
예제 #22
0
파일: KmlExport.cs 프로젝트: bouvet/BBR2015
        public string GetKml()
        {
            var matchId = _currentMatchProvider.GetMatchId();

            SharpKml.Dom.Kml kml = new SharpKml.Dom.Kml();

            var document = new Document();
            kml.Feature = document;

            var c = System.Drawing.ColorTranslator.FromHtml("#33FF33");
            var postStyle = new Style();
            postStyle.Id = "post_vanlig";
            postStyle.Icon = new IconStyle
            {
                Color = new Color32(c.A, c.R, c.G, c.B),
                Icon = new IconStyle.IconLink(new Uri("http://maps.google.com/mapfiles/kml/paddle/wht-blank.png")),
                Scale = 0.5
            };

            document.AddStyle(postStyle);

            var lagFolder = new Folder { Name = "Lag" };
            var postFolder = new Folder { Name = "Poster" };

            document.AddFeature(lagFolder);
            document.AddFeature(postFolder);

            using (var context = _dataContextFactory.Create())
            {
                var match = context.Matcher.Single(x => x.MatchId == matchId);

                var maxLat = match.GeoboxNWLatitude.GetValueOrDefault();
                var minLat = match.GeoboxSELatitude.GetValueOrDefault();
                var minLon = match.GeoboxNWLongitude.GetValueOrDefault();
                var maxLon = match.GeoboxSELongitude.GetValueOrDefault();

                var poster = (from pim in context.PosterIMatch
                              where pim.Match.MatchId == matchId
                              select
                                  new
                                  {
                                      pim.SynligFraTid,
                                      pim.SynligTilTid,
                                      pim.Post.Navn,
                                      pim.Post.Latitude,
                                      pim.Post.Longitude
                                  }).ToList();

                foreach (var p in poster)
                {
                    var placemark = new Placemark();
                    placemark.StyleUrl = new Uri("#post_vanlig", UriKind.Relative);
                    placemark.Time = new TimeSpan { Begin = p.SynligFraTid, End = p.SynligTilTid };
                    placemark.Name = p.Navn;
                    placemark.Geometry = new Point { Coordinate = new Vector(p.Latitude, p.Longitude) };

                    postFolder.AddFeature(placemark);
                }

                var lag = context.Lag.ToList();

                var lagDictionary = new Dictionary<string, Folder>();

                foreach (var lag1 in lag)
                {
                    var color = System.Drawing.ColorTranslator.FromHtml("#" + lag1.Farge);
                    var style = new Style();
                    style.Id = LagStyleKey(lag1.LagId);
                    style.Icon = new IconStyle
                    {
                        Color = new Color32(color.A, color.R, color.G, color.B),
                        Icon = new IconStyle.IconLink(new Uri("http://maps.google.com/mapfiles/kml/paddle/wht-blank-lv.png")),
                        Scale = 0.3
                    };

                    document.AddStyle(style);
                    var folder = new Folder { Name = lag1.Navn };
                    lagDictionary.Add(lag1.LagId, folder);
                    lagFolder.AddFeature(folder);
                }

                var førsteRegistering = (from r in context.PostRegisteringer
                                         select r.RegistertTidspunkt).Min().AddMinutes(-5);

                var avsluttet = (from r in poster
                                    select r.SynligTilTid).Min().AddMinutes(5);

                var deltakerPosisjoner = (from p in context.DeltakerPosisjoner
                                          join d in context.Deltakere on p.DeltakerId equals d.DeltakerId
                                          where førsteRegistering < p.Tidspunkt && p.Tidspunkt < avsluttet
                                          select new
                                          {
                                              p.Latitude,
                                              p.Longitude,
                                              p.DeltakerId,
                                              d.Navn,
                                              d.Lag.Farge,
                                              d.Lag.LagId,
                                              p.Tidspunkt
                                          }).GroupBy(x => x.DeltakerId).ToDictionary(x => x.Key, y => y);

                foreach (var deltaker in deltakerPosisjoner)
                {
                    //if (deltaker.Key != "MS_3-2")

                    //    continue;
                    var førstePosisjon = deltaker.Value.FirstOrDefault();
                    var placemark = new Placemark();
                    placemark.StyleUrl = new Uri("#" + LagStyleKey(førstePosisjon.LagId), UriKind.Relative);
                    placemark.Name = førstePosisjon.Navn;

                    var posisjoner = deltaker.Value.OrderBy(x => x.Tidspunkt).ToList();

                    var track = new Track();

                    var forrigePosisjon = førstePosisjon;
                    foreach (var pos in posisjoner)
                    {
                        // Utafor boksen
                        if (pos.Latitude > maxLat || pos.Latitude < minLat || pos.Longitude > maxLon || pos.Longitude < minLon)
                        {
                            continue;
                        }

                        var meter = DistanseKalkulator.MeterMellom(forrigePosisjon.Latitude, forrigePosisjon.Longitude, pos.Latitude, pos.Longitude);
                        var sekunder = pos.Tidspunkt.Subtract(forrigePosisjon.Tidspunkt).TotalSeconds;

                        if (sekunder > 0)
                        {
                            var fart = meter / sekunder;
                            if (fart > 8.333) // raskere enn 12 blank på 100m
                            {
                                continue;
                            }
                        }

                        track.AddWhen(pos.Tidspunkt);
                        track.AddCoordinate(new Vector(pos.Latitude, pos.Longitude));
                        forrigePosisjon = pos;
                    }

                    placemark.Geometry = track;

                    lagDictionary[førstePosisjon.LagId].AddFeature(placemark);
                }

            }

            Serializer serializer = new Serializer();
            serializer.Serialize(kml);

            return serializer.Xml;
        }