예제 #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
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();
        }
예제 #3
0
        /// <summary>
        /// Writes location to a KML file.
        /// </summary>
        /// <param name="filePath">The file path.</param>
        /// <param name="dbLocation">The database location.</param>
        public static void WriteToKml(string filePath, FormationMatcher dbLocation)
        {
            // This is the root element of the file
            Dom.Kml kml = AssembleToKml(dbLocation);

            WriteToKml(filePath, kml);
        }
예제 #4
0
        public void TestWalkProperties()
        {
            Kml kml = new Kml();
            kml.Feature = new Folder(); // This will not be added to the Children collection

            Assert.That(ElementWalker.Walk(kml).Count(), Is.EqualTo(2));
        }
예제 #5
0
        // WriteMatchesToKml
        /// <summary>
        /// Writes the list of regions to a KML file.
        /// </summary>
        /// <param name="filePath">The file path.</param>
        /// <param name="dbRegions">The database regions.</param>
        public static void WriteToKml(string filePath, List <Region> dbRegions)
        {
            // This is the root element of the file
            Dom.Kml kml = AssembleToKml(dbRegions);

            WriteToKml(filePath, kml);
        }
예제 #6
0
파일: AtomTest.cs 프로젝트: karun10/KML2SQL
        public void TestSerialize()
        {
            const string Expected =
                "<kml xmlns:atom=\"http://www.w3.org/2005/Atom\" xmlns=\"http://www.opengis.net/kml/2.2\">" +
                "<Document>" +
                "<atom:author>" +
                "<atom:name>Name</atom:name>" +
                "</atom:author>" +
                "<atom:link href=\"http://www.example.com/\" />" +
                "</Document>" +
                "</kml>";

            Document document = new Document();
            document.AtomAuthor = new Author { Name = "Name" };
            document.AtomLink = new SharpKml.Dom.Atom.Link { Href = new Uri("http://www.example.com") };

            Kml root = new Kml();
            root.AddNamespacePrefix(KmlNamespaces.AtomPrefix, KmlNamespaces.AtomNamespace);
            root.Feature = document;

            Serializer serializer = new Serializer();
            serializer.SerializeRaw(root);

            Assert.That(serializer.Xml, Is.EqualTo(Expected));
        }
예제 #7
0
        public static void Run()
        {
            Console.WriteLine("Creating a point at 37.42052549 latitude and -122.0816695 longitude.\n");

            // This will be used for the placemark
            Point point = new Point();
            point.Coordinate = new Vector(37.42052549, -122.0816695);

            Placemark placemark = new Placemark();
            placemark.Name = "Cool Statue";
            placemark.Geometry = point;

            // This is the root element of the file
            Kml kml = new Kml();
            kml.Feature = placemark;

            Serializer serializer = new Serializer();
            serializer.Serialize(kml);
            Console.WriteLine(serializer.Xml);

            Console.WriteLine("\nReading Xml...");

            Parser parser = new Parser();
            parser.ParseString(serializer.Xml, true);

            kml = (Kml)parser.Root;
            placemark = (Placemark)kml.Feature;
            point = (Point)placemark.Geometry;

            Console.WriteLine("Latitude:{0} Longitude:{1}", point.Coordinate.Latitude, point.Coordinate.Longitude);
        }
예제 #8
0
 /// <summary>
 /// Writes the KML to a KML file.
 /// </summary>
 /// <param name="filePath">The file path.</param>
 /// <param name="kml">The KML object.</param>
 public static void WriteToKml(string filePath, Dom.Kml kml)
 {
     using (FileStream file = File.Create(filePath))
     {
         Serializer serializer = new Serializer();
         serializer.Serialize(kml, file);
     }
 }
예제 #9
0
        /// <summary>
        /// Assembles region folder with locations to a KML file.
        /// </summary>
        /// <param name="dbRegion">The database region.</param>
        /// <returns>Dom.Kml.</returns>
        public static Dom.Kml AssembleToKml(Region dbRegion)
        {
            // This is the root element of the file
            Dom.Kml kml = new Dom.Kml {
                Feature = AssembleToFolder(dbRegion)
            };

            return(kml);
        }
예제 #10
0
        /// <summary>
        /// Assembles location to KML.
        /// </summary>
        /// <param name="dbLocation">The database location.</param>
        /// <returns>Dom.Kml.</returns>
        public static Dom.Kml AssembleToKml(FormationMatcher dbLocation)
        {
            // This is the root element of the file
            Dom.Kml kml = new Dom.Kml {
                Feature = AssembleToFolder(dbLocation)
            };

            return(kml);
        }
예제 #11
0
 private static IEnumerable<MapFeature> GetPlacemarks(Kml kml)
 {
     int id = 1;
     foreach (var placemark in kml.Flatten().OfType<Placemark>())
     {
         MapFeature mapFeature = new MapFeature(placemark, id);
         id++;
         yield return mapFeature;
     }
 }
예제 #12
0
        public override void saveKmlDocument(Document kmlDoc)
        {
            // This allows us to save and Element easily.
               var kml = new Kml();

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

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

               kmlF.Save(@"mykmlFile.kml");
        }
예제 #13
0
        public static MemoryStream ExportCaveRegister(MemoryStream stream, Folder folder)
        {
            Kml kml = new Kml();
            kml.Feature = folder;
            KmlFile kmlFile = KmlFile.Create(kml, false);

            //MemoryStream stream = new MemoryStream();
            using (KmzFile kmz = KmzFile.Create(kmlFile))
            {
                kmz.Save(stream);
                kmz.Save(HttpContext.Current.Request.MapPath("~/App_Data/Test2.kmz"));
            }

            return stream;
        }
예제 #14
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));
        }
예제 #15
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);
        }
예제 #16
0
        /// <summary>
        /// Gerador de Kml
        /// </summary>
        /// <param name="pLinhaDados"></param>
        /// <param name="pTipoDados"></param>
        /// <param name="pNome"></param>
        /// <param name="pNumOcorrencia"></param>
        public void GerarKml(string pLinhaDados, eTipoDadoGeografico pTipoDados, string pNome, int pNumOcorrencia)
        {
            Placemark placemark = new Placemark();
            placemark.Name = pNome;
            string sCor = "";

            if (pNumOcorrencia >= 20)
                sCor = "ff0000ff";
            else if (pNumOcorrencia >= 10)
                sCor = "ff8080ff";
            else if (pNumOcorrencia >= 5)
                sCor = "ffc0c0ff";
            else if (pNumOcorrencia >= 0)
                sCor = "ffffffff";

            StringBuilder sbStilo = new StringBuilder();
            sbStilo.AppendLine("<color>");
            sbStilo.AppendLine(sCor);
            sbStilo.AppendLine("</color>");

                                     string sXml = "";
            // This is the root element of the file
            Kml kml = new Kml();
            kml.Feature = placemark;

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

            int iIndiceStilo = serializer.Xml.LastIndexOf("<Placemark>") + 11;

            sXml = serializer.Xml.Insert(iIndiceStilo, sbStilo.ToString());

            int iIndiceInicial = sXml.LastIndexOf("</name>") + 8;

            sXml = sXml.Insert(iIndiceInicial, pLinhaDados);

            string caminho = @"C:\Users\" + Environment.UserName + @"\Desktop\ArquivoKml" + DateTime.Now.ToString().Replace("/", "-").Replace(":", ".") + ".kml";
            StreamWriter arquivo = new StreamWriter(caminho);
            arquivo.WriteLine(sXml);
            arquivo.Close();
            //MessageBox.Show("Arquivo Gravado em " + caminho + " com sucesso");
        }
예제 #17
0
        private async void ConvertFileToKml()
        {
            KmlFile kmlF;
            foreach(YouMapPoint yp in loadmap.Points)
            {
                Point p = new Point();
                Placemark pl = new Placemark();
                p.Coordinate = yp.getLocationAsVector();
                pl.Geometry = p;
                doc.AddFeature(pl);
                

            }
            foreach(YouMapPolyline yp in loadmap.Polylines)
            {
                LineString ln = new LineString();
                ln.Coordinates = yp.LocationAsCords;
                Placemark pl = new Placemark();
                pl.Geometry = ln;
                doc.AddFeature(pl);

               
            }
            kml = new Kml();
            kml.Feature = doc;
            kmlF = KmlFile.Create(kml, false);
            StorageFolder root = await IOFile.getMyRootfolder();
            StorageFile newFile = await root.CreateFileAsync("Bobby.kml", CreationCollisionOption.ReplaceExisting);


            


            using (IRandomAccessStream fileStream = await newFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                 Stream myStream = fileStream.AsStreamForWrite();
                 kmlF.Save(myStream); 
               
            }

         }
예제 #18
0
        /// <summary>
        /// Reads the region types into a list of region data objects.
        /// </summary>
        /// <param name="file">The file.</param>
        /// <returns>List&lt;DBRegion&gt;.</returns>
        public static List <Region> ReadRegions(KmlFile file)
        {
            Dom.Kml kml = file.Root as Dom.Kml;
            if (kml == null)
            {
                DisplayError("Unable to find any recognized Kml root in the specified kml file.");
                return(null);
            }
            List <Dom.Placemark> placemarks = new List <Dom.Placemark>();

            ExtractPlacemarks(kml.Feature, placemarks);

            // Sort using their names
            placemarks.Sort((a, b) => string.CompareOrdinal(a.Name, b.Name));

            return((from placemark in placemarks
                    let polygon = placemark.Geometry as Dom.Polygon
                                  where polygon != null
                                  let coordinateCollection = polygon.OuterBoundary.LinearRing.Coordinates
                                                             select new Region(placemark.Name, coordinateCollection)).ToList());
        }
예제 #19
0
        protected void GenerateKml()
        {
            var id = Convert.ToInt32(Server.HtmlEncode(Request.QueryString["Code"]));
            var document = new Document();
            document.Id = "Document";
            document.Name = "Document";

            Description dsc = new Description();
            dsc.Text = @"<h1>Car's Tracking</h1> ";

            CoordinateCollection coordinates = new CoordinateCollection();

            DataTable dt = new DataTable();

            try
            {
                DataSet ds = FieldAreaViewMethof.getfieldAreaValue(id);
                dt = ds.Tables[0];

                string isreference = ds.Tables[0].Rows[0]["isReferencePoint"].ToString();
                if (isreference == "True")
                {
                    dt.Rows[0].Delete();
                }

                foreach (DataRow dr in dt.Rows)
                {
                    double lon = double.Parse(ParseDMS(dr["Longitude"].ToString()).ToString());
                    double lat = double.Parse(ParseDMS(dr["Latitude"].ToString()).ToString());
                    coordinates.Add(new Vector(lat, lon, 0));
                }

                OuterBoundary outerBoundary = new OuterBoundary();
                outerBoundary.LinearRing = new LinearRing();
                outerBoundary.LinearRing.Coordinates = coordinates;

                // Polygon Setting:
                Polygon polygon = new Polygon();
                polygon.Extrude = true;
                polygon.AltitudeMode = AltitudeMode.ClampToGround;
                polygon.OuterBoundary = outerBoundary;

                //Color Style Setting:
                byte byte_Color_R = 150, byte_Color_G = 150, byte_Color_B = 150, byte_Color_A = 100; //you may get your own color by other method
                var style = new SharpKml.Dom.Style();

                style.Polygon = new PolygonStyle();
                style.Polygon.ColorMode = SharpKml.Dom.ColorMode.Normal;
                style.Polygon.Color = new Color32(byte_Color_A, byte_Color_B, byte_Color_G, byte_Color_R);

                //Set the polygon and style to the Placemark:
                Placemark placemark = new Placemark();
                placemark.Name = "Kukrail";
                placemark.Geometry = polygon;
                placemark.AddStyle(style);

                //Finally to the document and save it
                document.AddFeature(placemark);

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

                KmlFile kmlFile = KmlFile.Create(kml, true);
                if (File.Exists(Server.MapPath("~") + "MAP.kml"))
                {
                    File.Delete(Server.MapPath("~") + "MAP.kml");
                }
                using (var stream = System.IO.File.OpenWrite(Server.MapPath("~") + "MAP.kml"))
                {
                    kmlFile.Save(stream);
                }

            }
            catch (Exception exc)
            {
                Response.Write(exc.Message);
            }
            finally
            {
            }
        }
예제 #20
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;
        }
예제 #21
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>());
        }
예제 #22
0
        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 deltakerPosisjoner = (from p in context.DeltakerPosisjoner
                                          join d in context.Deltakere on p.DeltakerId equals d.DeltakerId
                                          where match.StartTid < p.Tidspunkt && p.Tidspunkt < match.SluttTid
                                          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);
        }
예제 #23
0
 private void InitializeMapFeatures(Kml kml)
 {
     foreach (var mapFeature in GetPlacemarks(kml))
     {
         if (mapFeature.GeometryType != null)
         {
             _mapFeatures.Add(mapFeature);
             foreach (KeyValuePair<string, string> pair in mapFeature.Data)
             {
                 if (!_columnNames.Contains(pair.Key) && pair.Key.ToLower() != "id")
                 {
                     _columnNames.Add(pair.Key);
                 }
             }
         }
         else
         {
             _log.Append("The map feature '" + mapFeature.Name + "' was not a Polygon, Linestring, " +
                         "or Point type. It will be skipped.\r\n");
         }
     }
 }
예제 #24
0
        private KmlFile InternalExport()
        {
            OnStarted();

            _additionalFiles.Clear();

            var kml = new Kml();

            var document = CreateRootDocument();

            kml.Feature = document;

            var embeddedStyles = new Dictionary<string, StyleSelector>();

            foreach (FeatureDataRow featureRow in _featureDataTable.Rows)
            {
                var kmlStyle = GetStyle != null ? GetStyle(new ExportContext(this, _additionalFiles, featureRow)) : null;
                if (kmlStyle != null)
                {
                    var xml = GetStyleXml(kmlStyle);

                    if (!embeddedStyles.ContainsKey(xml))
                    {
                        document.AddStyle(kmlStyle);

                        embeddedStyles.Add(xml, kmlStyle);
                    }
                }
                var feature = CreateKmlFeature(featureRow, kmlStyle);
                document.AddFeature(feature);
            }

            var kmlFile = KmlFile.Create(kml, true);

            OnEnded();

            return kmlFile;
        }
예제 #25
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;
        }