private void AddLocationsFolder(Document document) { var locationFolder = new Folder { Name = "Locations" }; document.AddFeature(locationFolder); var listStyle = new ListStyle { ItemType = ListItemType.CheckHideChildren, }; listStyle.AddItemIcon(new ItemIcon { Href = new Uri("http://maps.google.com/mapfiles/kml/shapes/placemark_circle.png", UriKind.Absolute) }); locationFolder.AddStyle(new Style { List = listStyle }); locationFolder.AddFeature(this.From.ToKmlPlacemark(KmlCommonElements.PlacementCircleStyleMapReferenceUri)); locationFolder.AddFeature(this.To.ToKmlPlacemark(KmlCommonElements.PlacementCircleStyleMapReferenceUri)); }
/// <summary> /// passed a sector build a folder containing the sector and all sm's attached to the sector. /// </summary> /// <param name="ap"></param> private Folder generateSector(AccessPointRadioInfo ap, CnLocation location) { // Create this sectors folder to hold all subscribers var sectorFolder = new Folder() { Name = ap.Name }; // Tracker to know if we should show this sector by default (users are connected to it with bad signal) bool showSector = false; // Fetch all subscribers for this specific sector. var sectorSubscribers = _subscribers.Where(sm => sm.Latitude != 0 && sm.Longitude != 0 && sm.APName == ap.Name); sectorFolder.Description = CreateDescriptionFromObject(ap); // Loop through and create all the placemarks for these sector subscribers. if (settings.showSubscribers) { foreach (var sm in sectorSubscribers) { // Check if the sm coordinates are realistic (within our configured range of the sector) if (sm.DistanceGeoM <= settings.SmInvalidationRangeM) { var smPlacemark = generateSmPlacemark(sm); if (smPlacemark.Visibility == true) { showSector = true; } sectorFolder.AddFeature(smPlacemark); } } } if (ap.Azimuth != 999) { // Generate the plot to show the coverage based on the sectors azimuth and distance var sectorPlot = generateSectorPlot((double)location.coordinates[1], (double)location.coordinates[0], ap.Azimuth, 500, 90); var plotPlacemark = new Placemark() { Name = ap.Name + " Coverage", Geometry = sectorPlot, StyleUrl = new Uri($"#plot_{ap.Channel.ToString()}", UriKind.Relative) }; // We chose in settings to always show sector plots if (settings.alwaysShowSectorPlot == true) { showSector = true; } ; plotPlacemark.Visibility = showSector; sectorFolder.AddFeature(plotPlacemark); } else { Console.WriteLine($"AP Missing Azimuth: {ap.Name}"); } return(sectorFolder); }
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); }
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.Select(f => f.Id), Is.EqualTo(new[] { "Placemark1", "Placemark2", "SubFolder1", "SubFolder2" })); }
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); }
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); }
/// <summary> /// Creates a KML folder with the visualization settings of the link. /// </summary> /// <param name="directionVector">The direction vector to convert.</param> /// <returns>The KML elements for visualizing the link.</returns> public static Folder ToKmlLinkFolder(this IDirectionVector directionVector) { if (directionVector == null) { throw new ArgumentNullException(nameof(directionVector), "directionVector is null"); } var fromAsHamnetSite = directionVector.From as IHamnetDbSite; var toAsHamnetSite = directionVector.To as IHamnetDbSite; var linkFolder = new Folder { Name = (fromAsHamnetSite != null) && (toAsHamnetSite != null) ? $"Link between {fromAsHamnetSite.Callsign?.ToUpperInvariant()} and {toAsHamnetSite.Callsign?.ToUpperInvariant()}" : $"Link between {directionVector.From.Latitude}/{directionVector.From.Longitude} and {directionVector.To.Latitude}/{directionVector.To.Longitude}", Visibility = true }; var listStyle = new ListStyle { ItemType = ListItemType.CheckHideChildren, }; listStyle.AddItemIcon(new ItemIcon { Href = new Uri("empty_icon.png", UriKind.Relative) }); linkFolder.AddStyle(new Style { List = listStyle }); linkFolder.AddFeature(CreateLinePlacemark(directionVector.From, directionVector.To, "Line with screen to ground", new Uri("#line", UriKind.Relative), true, string.Empty)); // description will be added to the larger (outer) zone only - hence the 2.4 GHz zone string description = KmlCommonElements.BalloonCssString; description += (fromAsHamnetSite != null) && (toAsHamnetSite != null) ? $"<h2>Link between {fromAsHamnetSite.Callsign?.ToUpperInvariant()} and {toAsHamnetSite.Callsign?.ToUpperInvariant()}</h2>" : $"<h2>Link between {directionVector.From.Latitude}/{directionVector.From.Longitude} and {directionVector.To.Latitude}/{directionVector.To.Longitude}</h2>"; description += $@"<table> <tr><td class=""left"">distance: </td><td>{directionVector.Distance / 1000.0:F1} km</td></tr> <tr><td class=""left"">azimuth to: </td><td>{directionVector.Bearing:F1}°</td></tr> <tr><td class=""left"">elevation to: </td><td>{directionVector.Elevation:F1}°</td></tr> <tr><td class=""left"">azimuth from: </td><td>{(directionVector.Bearing + 180.0) % 360.0:F3}°</td></tr> <tr><td class=""left""><a href=""https://en.wikipedia.org/wiki/Free-space_path_loss"">FSPL</a>: </td><td>{directionVector.Distance.FreeSpacePathloss(2.4e9):F1} dB @ 2.4 GHz<br>{directionVector.Distance.FreeSpacePathloss(5.8e9):F1} dB @ 5.8 GHz</td></tr> </table>"; linkFolder.AddFeature(CreateFresnelPlacemark(directionVector, "2.4 GHz fresnel zone", 2.4e9, KmlCommonElements.PolygonStyleTransparentReferenceUri, description)); linkFolder.AddFeature(CreateFresnelPlacemark(directionVector, "5.8 GHz fresnel zone", 5.8e9, KmlCommonElements.PolygonStyleReferenceUri, string.Empty)); return(linkFolder); }
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>()); }
/// <summary> /// Adds a single line string placemark with given coordinates /// </summary> /// <param name="folder">folder to add to</param> /// <param name="elementName">name of element to create</param> /// <param name="coordinatesList">list of coordinates</param> private void AddLineStringPlacemark( Folder folder, string elementName, double[][] coordinatesList) { var lineString = new LineString { AltitudeMode = AltitudeMode.ClampToGround, Extrude = false, Coordinates = new CoordinateCollection(), }; foreach (var coordinates in coordinatesList) { Debug.Assert( coordinates.Length == 2, "there always must be 2 coordinate values"); lineString.Coordinates.Add( new Vector( latitude: coordinates[1], longitude: coordinates[0])); } var placemark = new Placemark { Name = elementName, Geometry = lineString, StyleUrl = new Uri($"#{this.elementStyle.Id}", UriKind.Relative), }; folder.AddFeature(placemark); }
/// <summary> /// Adds a single point placemark with given coordinates /// </summary> /// <param name="folder">folder to add to</param> /// <param name="elementName">name of element to create</param> /// <param name="coordinates">coordinates for the point</param> private void AddPointPlacemark( Folder folder, string elementName, double[] coordinates) { Debug.Assert( coordinates.Length == 2, "there always must be 2 coordinate values"); var point = new Point { AltitudeMode = AltitudeMode.ClampToGround, Extrude = false, Coordinate = new Vector( latitude: coordinates[1], longitude: coordinates[0]), }; var placemark = new Placemark { Name = elementName, Geometry = point, StyleUrl = new Uri($"#{this.elementStyle.Id}", UriKind.Relative), }; folder.AddFeature(placemark); }
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)); var file = KmlFile.Create(folder, false); var update = new Update(); for (int i = 0; i < NumberOfFolders; ++i) { var delete = new DeleteCollection { CreateFeature(i, false) // This time set the TargetId }; update.AddUpdate(delete); } update.Process(file); Assert.That(folder.Features.Count(), Is.EqualTo(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); }
public void ShouldBeAbleToAddAValidChild() { var child = new Placemark(); var parent = new Folder(); parent.AddFeature(child); Assert.That(parent.Children, Has.Member(child)); }
public void TestCalculateLookAtFolder() { var location = new Location { Latitude = 0, Longitude = 0 }; var model = new Model { Location = location }; var placemark = new Placemark { Geometry = model }; var folder = new Folder(); folder.AddFeature(placemark); LookAt 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)); var point = new Point { Coordinate = new Vector(10, 10) }; var overlay = new PhotoOverlay { 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)); }
public void ShouldNotAllowChildrenOfOtherNodesToBeAdded() { var child = new Placemark(); var parent1 = new Folder(); var parent2 = new Folder(); parent1.AddFeature(child); Assert.That(() => parent2.AddFeature(child), Throws.TypeOf <InvalidOperationException>()); }
/// <summary> /// Passed a Dictionary of Names and Locations create the folders for the Towers, and then call the next step. /// </summary> /// <param name="tower"></param> /// <returns></returns> private Folder generateTower(KeyValuePair <string, CnLocation> tower) { { // Generate folder for containing all this towers ap, sectors, sms. var towerFolder = new Folder() { Name = tower.Key }; // Generate our placemark for the towers themselves var towerPlacemark = new Placemark() { Name = tower.Key, Id = tower.Key, Geometry = new Point() { Coordinate = new Vector( latitude: (double)tower.Value.coordinates[1], longitude: (double)tower.Value.coordinates[0]) }, StyleUrl = new Uri($"#{nameof(towerIcon)}", UriKind.Relative) }; towerPlacemark.Visibility = settings.Icons["Tower"].Visibility; towerFolder.Description = new Description() { Text = $"<![CDATA[Total Subscribers:{_subscribers.Where(sm => sm.Tower == tower.Key).Count()}<br/>Correct Lat/Long Subs: {_subscribers.Where(sm => sm.Latitude != 0 && sm.Longitude != 0 && sm.Tower == tower.Key).Count()}]]>" }; // Loop through all the APs for this towers AP foreach (var ap in _accessPoints.Where(ap => ap.Tower == tower.Key)) { var sectorFolder = generateSector(ap, tower.Value); towerFolder.AddFeature(sectorFolder); } towerFolder.AddFeature(towerPlacemark); return(towerFolder); } }
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)); }
public FileContentResult DownloadKMLStatic(int id = 0) { var route = db.Flights.Where(r => r.FlightID == id).Select(r => r.RouteID).FirstOrDefault(); if (route == null) { route = id; //patch if route is for some reason empty } var flights = db.Flights.Where(r => r.RouteID == route).Select(r => new { r.FlightID }).ToList(); var doc = new Document(); doc.Id = "Route"; doc.Name = "Route"; var folder = new Folder(); folder.Id = "Flights"; folder.Name = "Flights"; foreach (var f in flights) { var i = flights.IndexOf(f); var flightLineStyles = new FlightLineStyles(i); var docStyle = flightLineStyles.style; folder.AddStyle(docStyle); var placemark = new FlightPlacemarkLineString(f.FlightID); placemark.styleUrlRef = docStyle.Id; folder.AddFeature(placemark.placemark); } doc.AddFeature(folder); var kml = new Kml(); kml.Feature = doc; KmlFile kmlFile = KmlFile.Create(kml, true); //using (var stream = System.IO.File.OpenWrite("C:/temp/kmlfile.kml")) //{ // kmlFile.Save(stream); //}; using (var stream = new System.IO.MemoryStream()) { kmlFile.Save(stream); var kmlFileName = "Flight_" + id + ".kml"; var fileBytes = new System.Text.UTF8Encoding().GetBytes(new System.Text.UTF8Encoding().GetString(stream.ToArray())); return(File(fileBytes, "application/vnd.google-earth.kml+xml", kmlFileName)); }; }
public static void Run() { // Create a Container and some Features. var placemark1 = new Placemark(); var placemark2 = new Placemark(); var folder = new Folder(); folder.AddFeature(placemark1); folder.AddFeature(placemark2); // Add a copy of the region to each Placemark var region = CreateRegion(); placemark1.Region = region.Clone(); placemark2.Region = region.Clone(); // Display the result var serializer = new Serializer(); serializer.Serialize(folder); Console.WriteLine(serializer.Xml); }
private void AddLinksFolder(Document document) { IDirectionVector vector = this.From.DirectionTo(this.To); var linkFolder = new Folder { Name = "Links", Open = true, Visibility = true }; document.AddFeature(linkFolder); linkFolder.AddFeature(vector.ToKmlLinkFolder()); }
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 }
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")); }
/// <summary> /// Converts a GeoJSON element to a KML element and adds it to the KML folder. /// </summary> /// <param name="folder">KML folder</param> /// <param name="parentElementName">the parent's element name</param> /// <param name="element">GeoJSON element</param> private void ConvertElementToKml( Folder folder, string parentElementName, Element element) { string elementName = this.NameFromElement(element, parentElementName); switch (element) { case FeatureCollection featureCollection: { var subFolder = new Folder { Name = elementName, }; folder.AddFeature(subFolder); foreach (Feature feature in featureCollection.FeatureList) { this.ConvertElementToKml(subFolder, elementName, feature); } break; } case Feature feature: this.ConvertElementToKml(folder, elementName, feature.Geometry); break; case Geometry geometry: this.ConvertGeometryToKml(folder, elementName, geometry); break; case GeometryCollection geometryCollection: { foreach (var singleGeometry in geometryCollection.GeometryList) { this.ConvertGeometryToKml(folder, elementName, singleGeometry); } break; } default: throw new FormatException("invalid element type"); } }
public static void KmlFilter(string originalPath, string emptyFilePath, string outputPath, bool multipleAssgnment = false) { var repo = new PhotoDbContext(); var beaches = repo.Beaches.ToList(); var stream = File.OpenRead(originalPath); var file = KmlFile.Load(stream); stream.Close(); var stream2 = File.OpenRead(emptyFilePath); var file2 = KmlFile.Load(stream2); stream2.Close(); var kml = file.Root as Kml; var kml2 = file2.Root as Kml; if (kml != null) { var list = kml.Feature.Flatten().OfType <Folder>().FirstOrDefault(); Folder folder = new Folder(); list.Flatten()?.OfType <Placemark>().ForEach(p => { var place = p.Clone(); ProceedPlacemark(ref place, beaches, multipleAssgnment); if (place.TargetId != "-1") { folder.AddFeature(place); } }); if (kml2 != null) { Document document = kml2.Feature.Flatten().OfType <Document>().FirstOrDefault(); var clone = document.Clone(); clone.AddFeature(folder); var file3 = KmlFile.Create(clone, true); var stream3 = File.OpenWrite(outputPath); file3.Save(stream3); stream3.Flush(); stream3.Close(); } } }
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>()); }
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)); }
/// <summary> /// Adds a single polygon placemark with given polygon point coordinates /// </summary> /// <param name="folder">folder to add to</param> /// <param name="elementName">name of element to create</param> /// <param name="polygonCollection">polygon point coordinates</param> private void AddPolygonPlacemark( Folder folder, string elementName, double[][] polygonCollection) { var polygon = new Polygon { AltitudeMode = AltitudeMode.ClampToGround, Extrude = false, OuterBoundary = new OuterBoundary { LinearRing = new LinearRing { Coordinates = new CoordinateCollection(), }, }, }; foreach (var coordinates in polygonCollection) { Debug.Assert( coordinates.Length == 2, "there always must be 2 coordinate values"); polygon.OuterBoundary.LinearRing.Coordinates.Add( new Vector( latitude: coordinates[1], longitude: coordinates[0])); } var placemark = new Placemark { Name = elementName, Geometry = polygon, StyleUrl = new Uri($"#{this.elementStyle.Id}", UriKind.Relative), }; folder.AddFeature(placemark); }
/** * @param args */ public static void createKml(GpxFileSetModel fileSetModel, KmlOptions kmlOptions) { // Generate the KML Kml kml = new Kml(); // Create the Document for this file Document document = new Document() { Name = "GPXViewer", Open = true }; kml.Feature = document; // Make the Styles for this Document // Trk Colors switch (kmlOptions.TrkColorMode) { case KmlColorMode.COLOR: createTrkColorColors(kmlOptions); break; case KmlColorMode.COLORSET: createTrkColorSetColors(kmlOptions); break; case KmlColorMode.RAINBOW: createTrkRainbowColors(kmlOptions, fileSetModel); break; } // Rte Colors switch (kmlOptions.RteColorMode) { case KmlColorMode.COLOR: createRteColorColors(kmlOptions); break; case KmlColorMode.COLORSET: createRteColorSetColors(kmlOptions); break; case KmlColorMode.RAINBOW: createRteRainbowColors(kmlOptions, fileSetModel); break; } // Wpt Colors switch (kmlOptions.WptColorMode) { case KmlColorMode.COLOR: createWptColorColors(kmlOptions); break; case KmlColorMode.COLORSET: createWptColorSetColors(kmlOptions); break; case KmlColorMode.RAINBOW: createWptRainbowColors(kmlOptions, fileSetModel); break; } // Create the color styles int nTrkColors = trkColors.Length; foreach (String color in trkColors) { document.AddStyle(new Style() { Id = "trk" + color, Line = new LineStyle() { Color = Color32.Parse(color), Width = kmlOptions.TrkLineWidth, }, Icon = new SharpKml.Dom.IconStyle() { Color = Color32.Parse(color), ColorMode = ColorMode.Normal, Scale = kmlOptions.IconScale, Icon = new IconStyle.IconLink(new Uri(kmlOptions.TrkIconUrl)) } }); } int nRteColors = rteColors.Length; foreach (String color in rteColors) { document.AddStyle(new Style() { Id = "rte" + color, Line = new LineStyle() { Color = Color32.Parse(color), Width = kmlOptions.TrkLineWidth, }, Icon = new SharpKml.Dom.IconStyle() { Color = Color32.Parse(color), ColorMode = ColorMode.Normal, Scale = kmlOptions.IconScale, Icon = new IconStyle.IconLink(new Uri(kmlOptions.RteIconUrl)) } }); } int nWptColors = wptColors.Length; foreach (String color in wptColors) { document.AddStyle(new Style() { Id = "wpt" + color, Line = new LineStyle() { Color = Color32.Parse(color), Width = kmlOptions.TrkLineWidth, }, Icon = new SharpKml.Dom.IconStyle() { Color = Color32.Parse(color), ColorMode = ColorMode.Normal, Scale = kmlOptions.IconScale, Icon = new IconStyle.IconLink(new Uri(kmlOptions.WptIconUrl)) } }); } // Loop over GPX files int nTrack = 0; int nRoute = 0; int nWaypoint = 0; List <GpxWaypointModel> waypointModels; wptType waypoint; Folder fileFolder; Folder waypointFolder; Folder trackFolder; Folder routeFolder; Folder folder; MultipleGeometry mg; Placemark placemark; Placemark trackPlacemark; MultipleTrack mt; Track track; LineString ls = null; double lat, lon, alt; String fileName; DateTime? when; List <GpxFileModel> fileModels = fileSetModel.Files; foreach (GpxFileModel fileModel in fileModels) { if (!fileModel.Checked) { continue; } fileName = fileModel.FileName; if (!File.Exists(fileName)) { Utils.errMsg("File does not exist: " + fileName); continue; } fileFolder = new Folder() { //Name = fileName, Name = Path.GetFileName(fileName), Open = false }; document.AddFeature(fileFolder); // Loop over waypoints waypointFolder = new Folder() { Name = "Waypoints", Open = false }; waypointModels = fileModel.Waypoints; if (waypointModels.Count > 0) { fileFolder.AddFeature(waypointFolder); } foreach (GpxWaypointModel waypointModel in waypointModels) { if (!waypointModel.Checked) { continue; } waypoint = waypointModel.Waypoint; lat = decimal.ToDouble(waypoint.lat); lon = decimal.ToDouble(waypoint.lon); if (waypoint.ele.HasValue) { alt = decimal.ToDouble((decimal)waypoint.ele); } else { alt = 0; } // Make a Placemark waypointFolder.AddFeature(new Placemark() { Name = waypointModel.Label, StyleUrl = new Uri("#wpt" + wptColors[nWaypoint % nWptColors], UriKind.Relative), Geometry = new SharpKml.Dom.Point() { Coordinate = new Vector(lat, lon, alt) } }); nWaypoint++; } // Loop over tracks trackFolder = new Folder() { Name = "Tracks", Open = false }; List <GpxTrackModel> trackModels; trackModels = fileModel.Tracks; bool useTrackIconFirst; bool useTrackTrackFirst; if (trackModels.Count > 0) { fileFolder.AddFeature(trackFolder); } trackPlacemark = null; mt = null; track = null; foreach (GpxTrackModel trackModel in trackModels) { if (!trackModel.Checked) { continue; } // Make a Placemark for the track if (kmlOptions.UseTrkTrack) { trackPlacemark = new Placemark() { Name = trackModel.Label, Open = false, StyleUrl = new Uri("#trk" + trkColors[nTrack % nTrkColors], UriKind.Relative), Snippet = new Snippet() }; trackFolder.AddFeature(trackPlacemark); mt = new MultipleTrack(); trackPlacemark.Geometry = mt; } // Make a Placemark with MultiGeometry placemark = new Placemark() { Name = trackModel.Label + " Lines", Visibility = kmlOptions.UseTrkTrack && !kmlOptions.UseTrkLines ? false:true, StyleUrl = new Uri("#trk" + trkColors[nTrack % nTrkColors], UriKind.Relative) }; trackFolder.AddFeature(placemark); // Need MultiGeometry to handle non-connected segments mg = new MultipleGeometry(); placemark.Geometry = mg; useTrackIconFirst = kmlOptions.UseTrkIcon ? true : false; useTrackTrackFirst = kmlOptions.UseTrkTrack ? true : false; foreach (trksegType trackSegment in trackModel.Track.trkseg) { // Add a LineString to the MultiGeometry ls = new LineString() { Extrude = false, Tessellate = true, Coordinates = new CoordinateCollection() }; mg.AddGeometry(ls); if (mt != null) { track = new Track(); mt.AddTrack(track); } foreach (wptType trackPoint in trackSegment.trkpt) { lat = decimal.ToDouble(trackPoint.lat); lon = decimal.ToDouble(trackPoint.lon); if (trackPoint.ele.HasValue) { alt = decimal.ToDouble((decimal)trackPoint.ele); } else { alt = 0; } if (trackPoint.time != null) { when = (DateTime)trackPoint.time; } else { when = null; } // Add coordinates to the LineString ls.Coordinates.Add(new Vector(lat, lon, alt)); if (track != null) { // Add coordinates (and when to the track ?) track.AddCoordinate(new Vector(lat, lon, alt)); if (when != null) { track.AddWhen((DateTime)when); } } // Make a Placemark with an icon at the first point // on the track if (useTrackIconFirst) { useTrackIconFirst = false; trackFolder.AddFeature(new Placemark() { Name = trackModel.Label, // The Track has its own icon Visibility = !kmlOptions.UseTrkTrack, StyleUrl = new Uri("#trk" + trkColors[nTrack % nTrkColors], UriKind.Relative), Geometry = new SharpKml.Dom.Point() { Coordinate = new Vector(lat, lon) } }); } if (trackPlacemark != null && useTrackTrackFirst) { useTrackTrackFirst = false; trackPlacemark.Description = new Description() { Text = trackPoint.time.ToString() }; } } } nTrack++; } // Loop over routes folder = new Folder() { Name = "Routes", Open = false }; List <GpxRouteModel> routeModels; routeModels = fileModel.Routes; bool useRteIconFirst; if (routeModels.Count > 0) { fileFolder.AddFeature(folder); } foreach (GpxRouteModel routeModel in routeModels) { if (!routeModel.Checked) { continue; } routeFolder = (new Folder() { Name = routeModel.Label, Open = false, }); folder.AddFeature(routeFolder); // Make a Placemark with MultiGeometry placemark = new Placemark() { Name = routeModel.Label + " Lines", StyleUrl = new Uri("#rte" + rteColors[nRoute % nRteColors], UriKind.Relative), }; routeFolder.AddFeature(placemark); // Need MultiGeometry to handle non-connected segments mg = new MultipleGeometry(); placemark.Geometry = mg; useRteIconFirst = kmlOptions.UseRteIcon ? true : false; // Add a LineString to the MultiGeometry ls = new LineString() { Extrude = false, Tessellate = true }; mg.AddGeometry(ls); foreach (wptType rtePoint in routeModel.Route.rtept) { lat = decimal.ToDouble(rtePoint.lat); lon = decimal.ToDouble(rtePoint.lon); if (rtePoint.ele.HasValue) { alt = decimal.ToDouble((decimal)rtePoint.ele); } else { alt = 0; } if (useRteIconFirst) { // Make a Placemark with an Icon at the first point // on the route useRteIconFirst = false; routeFolder.AddFeature(new Placemark() { Name = routeModel.Label, StyleUrl = new Uri("#rte" + rteColors[nRoute % nRteColors], UriKind.Relative), Geometry = new SharpKml.Dom.Point() { Coordinate = new Vector(lat, lon, alt) } }); } // Make a Placemark routeFolder.AddFeature(new Placemark() { Name = rtePoint.name, StyleUrl = new Uri("#rte" + rteColors[nRoute % nRteColors], UriKind.Relative), Geometry = new SharpKml.Dom.Point() { Coordinate = new Vector(lat, lon, alt) } }); } } nRoute++; } // Create the file String kmlFileName = kmlOptions.KmlFileName; string outFile = Environment.ExpandEnvironmentVariables(kmlFileName); if (kmlOptions.PromptToOverwrite && File.Exists(outFile)) { DialogResult dr = MessageBox.Show("File exists: " + outFile + "\nOK to overwrite?", "File Exists", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information); if (dr != DialogResult.Yes) { return; } } try { Serializer serializer = new Serializer(); serializer.Serialize(kml); File.WriteAllText(outFile, serializer.Xml); } catch (Exception ex) { Utils.excMsg("Error creating KML file: " + outFile, ex); } // Send it to Google Earth if (kmlOptions.SendToGoogleEarth) { Process result; try { result = Process.Start(outFile); if (result == null) { Utils.errMsg("Failed to send to Google Earth:" + NL + " " + outFile); } } catch (Exception ex) { Utils.excMsg("Failed to send to Google Earth:" + NL + " " + outFile, ex); } } }
private void writeKML(string filename) { SharpKml.Dom.AltitudeMode altmode = SharpKml.Dom.AltitudeMode.Absolute; if (MainV2.cs.firmware == MainV2.Firmwares.ArduPlane) { altmode = SharpKml.Dom.AltitudeMode.Absolute; } else if (MainV2.cs.firmware == MainV2.Firmwares.ArduCopter2) { altmode = SharpKml.Dom.AltitudeMode.RelativeToGround; } 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() { 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); Style stylet = new Style(); stylet.Id = "track"; SharpKml.Dom.IconStyle ico = new SharpKml.Dom.IconStyle(); LabelStyle lst = new LabelStyle(); lst.Scale = 0; stylet.Icon = ico; ico.Icon = new IconStyle.IconLink(new Uri("http://earth.google.com/images/kml-icons/track-directional/track-none.png")); stylet.Icon.Scale = 0.5; stylet.Label = lst; kml.AddStyle(stylet); // create sub folders Folder planes = new Folder(); planes.Name = "Planes"; kml.AddFeature(planes); Folder points = new Folder(); points.Name = "Points"; kml.AddFeature(points); // 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 = altmode; 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 = altmode; 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 = "Point " + 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; if (loc.Altitude < 0) { loc.Altitude = 0.01; } 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 = altmode; model.Scale = sca; try { Description desc = new Description(); desc.Text = @"<![CDATA[ <table> <tr><td>Roll: " + model.Orientation.Roll.Value.ToString("0.00") + @" </td></tr> <tr><td>Pitch: " + model.Orientation.Tilt.Value.ToString("0.00") + @" </td></tr> <tr><td>Yaw: " + model.Orientation.Heading.Value.ToString("0.00") + @" </td></tr> <tr><td>Time: " + cs.datetime.ToString("HH:mm:sszzzzzz") + @" </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); /// Placemark pmt = new Placemark(); SharpKml.Dom.Point pnt = new SharpKml.Dom.Point(); pnt.AltitudeMode = altmode; pnt.Coordinate = new Vector(cs.lat, cs.lng, cs.alt); pmt.Name = "" + a; pmt.Description = pmplane.Description; pmt.Time = tstamp; pmt.Geometry = pnt; pmt.StyleUrl = new Uri("#track", UriKind.Relative); points.AddFeature(pmt); 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(); flightdata.Clear(); }
private static void FPConverter(string file) { var lpFile = file; if (!File.Exists(lpFile)) { return; } XNamespace ns = "http://earth.google.com/kml/2.2"; var doc = XDocument.Load(lpFile); var placemarks = doc.Root .Element(ns + "Document") .Elements(ns + "Folder") .Elements(ns + "Placemark"); var kml = new Kml(); var document = new Document(); document.Name = Path.GetFileNameWithoutExtension(lpFile); foreach (var obj in placemarks) { var name = obj .Element(ns + "name"); Folder folder = new Folder() { Name = name.Value, }; Placemark newLine = new Placemark(); newLine.Name = name.Value; var coordinates = obj .Elements(ns + "LineString") .Elements(ns + "coordinates"); var runNumber = name.Value.Trim(); var runsubs = runNumber.Substring(3); const double Scale = 0.3048; if (!string.IsNullOrEmpty(runNumber)) { if (coordinates.Any()) { foreach (var coords in coordinates) { var value = coords.Value; var num = Regex.Match(value, @"[0-9]{0,4}\s+"); LineString line = new LineString(); var newCoords = coords.Value.Trim(); // splitting string values from original kml // into usable data for Vector class string[] splitCoords = newCoords.Split(' '); string[] splitCoords1 = splitCoords[0].Split(','); string[] splitCoords2 = splitCoords[1].Split(','); double long1 = double.Parse(splitCoords1[0]); double lat1 = double.Parse(splitCoords1[1]); double height1 = double.Parse(splitCoords1[2]); double long2 = double.Parse(splitCoords2[0]); double lat2 = double.Parse(splitCoords2[1]); double height2 = double.Parse(splitCoords2[2]); CoordinateCollection CoordsCollection = new CoordinateCollection(); CoordsCollection.Add(new Vector(lat1, long1, height1)); CoordsCollection.Add(new Vector(lat2, long2, height2)); // Start placemark code Placemark flightLabel = new Placemark(); Point point = new Point(); Vector pointVector = new Vector(); pointVector.Latitude = ReturnCentre(lat1, lat2); pointVector.Longitude = ReturnCentre(long1, long2); point.Coordinate = pointVector; flightLabel.Geometry = point; // end placemark code line.Coordinates = CoordsCollection; newLine.Geometry = line; //puts placemark into <folder> folder.AddFeature(newLine); //add the folder to the document. document.AddFeature(folder); if (num.Success) { var valueStr = num.Value.Trim(); if (int.TryParse(valueStr, out var height)) { checked { var feet = (height / Scale); flightLabel.Name = runNumber + "/" + Convert.ToInt32(feet) + "ft"; } } } folder.AddFeature(flightLabel); kml.Feature = document; KmlFile kmlFile = KmlFile.Create(kml, true); using (var fs = File.OpenWrite(document.Name + "-TEST-ONLY-DO-NOT-FLY.kml")) { kmlFile.Save(fs); } } } } } }