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(); }
// Draw the unsimplified polygon private void DrawPolygon() { MapPoint center = mapView.Extent.GetCenter(); double lat = center.Y; double lon = center.X + 300; double latOffset = 300; double lonOffset = 300; var points = new CoordinateCollection() { new Coordinate(lon - lonOffset, lat), new Coordinate(lon, lat + latOffset), new Coordinate(lon + lonOffset, lat), new Coordinate(lon, lat - latOffset), new Coordinate(lon - lonOffset, lat), new Coordinate(lon - 2 * lonOffset, lat + latOffset), new Coordinate(lon - 3 * lonOffset, lat), new Coordinate(lon - 2 * lonOffset, lat - latOffset), new Coordinate(lon - 1.5 * lonOffset, lat + latOffset), new Coordinate(lon - lonOffset, lat) }; _unsimplifiedPolygon = new Polygon(points, mapView.SpatialReference); _polygonLayer.Graphics.Clear(); _polygonLayer.Graphics.Add(new Graphic(_unsimplifiedPolygon)); }
public void Initalise() { collection = new CoordinateCollection(); // Add four coordinates in the shape of a square collection.Add(new Coordinate(10, 10, 0)); collection.Add(new Coordinate(10, 20, 0)); collection.Add(new Coordinate(20, 10, 0)); collection.Add(new Coordinate(20, 20, 0)); }
CoordinateCollection CreateCoordinateCollection(List<OpenSMIL.Server.SimpleFeature.GeomtryTypes.Point> points) { CoordinateCollection coordinates = new CoordinateCollection(); foreach (var item in points) { coordinates.Add(new Vector(item.Lat, item.Lon)); } return coordinates; }
// Helper method private static CoordinateCollection FromArray(params double[] parameters) { CoordinateCollection coll = new CoordinateCollection(); for (int i = 0; i < parameters.Length - 1; i+=2) { coll.Add(new Coordinate(parameters[i], parameters[i + 1])); } return coll; }
public void SerializeShouldNotOutputAltitudeIfItIsNotSpecified() { var coords = new CoordinateCollection(new[] { new Vector(1, 2) }); var serializer = new Serializer(); serializer.SerializeRaw(coords); var expected = string.Format(CultureInfo.InvariantCulture, XmlFormat, "2,1"); Assert.That(serializer.Xml, Is.EqualTo(expected)); }
/// <summary> /// Converts a CoordinateCollection into a Bing Maps LocationCollection. /// </summary> /// <param name="coordinates">CoordinateCollection to convert.</param> /// <returns>LocationCollection of the converted CoordinateCollection.</returns> public static LocationCollection ToBMGeometry(this CoordinateCollection coordinates) { var locs = new LocationCollection(); foreach (var c in coordinates) { locs.Add(new Location(c.Latitude, c.Longitude)); } return(locs); }
private async void CommandBinding_AddPolygonBarrierExecuted(object sender, ExecutedRoutedEventArgs e) { try { //Polygon polygon; //polygon = await map1.Editor.RequestShape(Esri.ArcGISRuntime.Controls.DrawShape.Polygon) as Polygon; //_polygonBarriersGraphicsLayer.Graphics.Add(new Graphic(polygon)); // Polygon Barrier: Polygon polygon = new Polygon(); // Assign Spatial Reference (no SR conveyed from Coordinates to PolyLine) polygon.SpatialReference = mapView1.SpatialReference; CoordinateCollection coords = new CoordinateCollection(); // 1st Point: MapPoint mapPoint; mapPoint = await mapView1.Editor.RequestPointAsync(); coords.Add(mapPoint.Coordinate); Graphic g1 = new Graphic(mapPoint); _pointBarriersGraphicsLayer.Graphics.Add(g1); // 2nd Point: mapPoint = await mapView1.Editor.RequestPointAsync(); coords.Add(mapPoint.Coordinate); Graphic g2 = new Graphic(mapPoint); _pointBarriersGraphicsLayer.Graphics.Add(g2); // Return to UI thread to allow 2nd graphic to appear. await Task.Delay(100); // 3rd Point: mapPoint = await mapView1.Editor.RequestPointAsync(); coords.Add(mapPoint.Coordinate); Graphic g3 = new Graphic(mapPoint); _pointBarriersGraphicsLayer.Graphics.Add(g3); // Return to UI thread to allow 2nd graphic to appear. await Task.Delay(100); polygon.Rings.Add(coords); _polygonBarriersGraphicsLayer.Graphics.Add(new Graphic(polygon)); _pointBarriersGraphicsLayer.Graphics.Remove(g1); _pointBarriersGraphicsLayer.Graphics.Remove(g2); _pointBarriersGraphicsLayer.Graphics.Remove(g3); await SolveRoute(); } catch (TaskCanceledException) { return; } catch (Exception exception) { MessageBox.Show(exception.Message); } }
private static JArray CreateCoordinates(CoordinateCollection coordinates) { var coords = new JArray(); foreach (var c in coordinates) { coords.Add(CreateCoordinate(c)); } return(coords); }
/// <summary> /// Converts a LocationCollection into a CoordinateCollection object. /// </summary> /// <param name="locations">A Bing Maps LocationCollection object</param> /// <returns>A CoordinateCollection representation of the LocationCollection object</returns> public static CoordinateCollection ToGeometry(this LocationCollection locations) { CoordinateCollection coords = new CoordinateCollection(); for (int i = 0; i < locations.Count; i++) { coords.Add(new Coordinate(locations[i].Latitude, locations[i].Longitude)); } return(coords); }
/// <summary> /// This adds a point to the current line. /// </summary> /// <param name="pt">the Coordinate to add /// </param> public void Add(Coordinate pt, bool allowRepeatedPoints) { if (coordList == null) { coordList = new CoordinateCollection(); } coordList.Add(pt, allowRepeatedPoints); lastPt = pt; }
/// <summary> /// Converts a Geopath into a CoordinateCollection object. /// </summary> /// <param name="locations">A Geopath object</param> /// <returns>A CoordinateCollection representation of the Geopath object</returns> public static CoordinateCollection ToGeometry(this Geopath locations) { CoordinateCollection coords = new CoordinateCollection(); for (int i = 0; i < locations.Positions.Count; i++) { coords.Add(locations.Positions[i].ToGeometry()); } return(coords); }
private ICoordinateList ReadCoordinates(XmlReader reader) { string strCoordinates = reader.ReadString(); if (strCoordinates != null && strCoordinates.Length > 0) { string[] arrOrds = strCoordinates.Split(TupleSeparator); if (arrOrds != null && arrOrds.Length > 0) { int nCount = arrOrds.Length; CoordinateCollection coordinates = new CoordinateCollection(nCount); for (int i = 0; i < nCount; i++) { string strCoordinate = arrOrds[i]; if (strCoordinate == null || strCoordinate.Length == 0) { continue; } Coordinate coord = null; string[] arrOrd = strCoordinate.Split(Separator); if (arrOrd != null && arrOrd.Length >= 2) { int nLength = arrOrd.Length; if (nLength == 2) { coord = new Coordinate(Convert.ToDouble(arrOrd[0]), Convert.ToDouble(arrOrd[1])); } else if (nLength == 3) { coord = new Coordinate3D(Convert.ToDouble(arrOrd[0]), Convert.ToDouble(arrOrd[1]), Convert.ToDouble(arrOrd[2])); } } if (coord != null) { coordinates.Add(coord); } } return(coordinates); } } return(null); }
protected EdgeRing(DirectedEdge start, GeometryFactory geometryFactory) { edges = new ArrayList(); pts = new CoordinateCollection(); label = new Label(LocationType.None); holes = new ArrayList(); this.geometryFactory = geometryFactory; ComputePoints(start); ComputeRing(); }
//returns the Azimuth of line from first vertex to last vertex private static Azimuth GetAzimuthFromVertices(CoordinateCollection points) { if (points == null) throw new ArgumentNullException("points"); if (points.LastIndex != 1 || points.IsARing) throw new ArgumentException("vertices must contain two, and only two, non equal coordinates"); Coordinate firstPoint = points.First(); Coordinate lastPoint = points.Last(); double angle = Math.Atan2(lastPoint.Y - firstPoint.Y, lastPoint.X - firstPoint.X); return Azimuth.FromTrigAngleAsRadians(angle); }
private static async Task <CoordinateCollection> ParsePosList(XElement node, bool optimize, double tolerance) { if (node.Name.Namespace == gmlNS && (string.Compare(node.Name.LocalName, "poslist", StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(node.Name.LocalName, "coordinates", StringComparison.OrdinalIgnoreCase) == 0)) { var dimension = XmlUtilities.GetDoubleAttribute(node, "dimension"); int dim = 2; if (!double.IsNaN(dimension) && dimension > 2) { dim = (int)dimension; } var sCoord = XmlUtilities.GetString(node, false); var vals = CoordArtifactRx.Replace(sCoord, " ").Split(SpaceSplitter, StringSplitOptions.RemoveEmptyEntries); var c = new CoordinateCollection(); double lat, lon, alt; if (dim == 3 && vals.Length >= 3) { for (var i = 0; i < vals.Length; i = i + 3) { if (double.TryParse(vals[i], NumberStyles.Float, CultureInfo.InvariantCulture, out lat) && double.TryParse(vals[i + 1], NumberStyles.Float, CultureInfo.InvariantCulture, out lon) && double.TryParse(vals[i + 1], NumberStyles.Float, CultureInfo.InvariantCulture, out alt)) { c.Add(new Coordinate(lat, lon, alt)); } } } else if (dim == 2 && vals.Length >= 2) { for (var i = 0; i < vals.Length; i = i + 2) { if (double.TryParse(vals[i], NumberStyles.Float, CultureInfo.InvariantCulture, out lat) && double.TryParse(vals[i + 1], NumberStyles.Float, CultureInfo.InvariantCulture, out lon)) { c.Add(new Coordinate(lat, lon)); } } } if (optimize) { c = await SpatialTools.VertexReductionAsync(c, tolerance); } return(c); } return(null); }
public PointF[] RingToPointFList(CoordinateCollection coords) { int numPoints = coords.Count; var points = new PointF[numPoints]; System.Threading.Tasks.Parallel.For(0, numPoints, (i) => { points[i] = LatLongToPointF(coords[i]); }); return(points); }
/// <param name="coordinates"> /// Contains the single coordinate on which to base this Point /// , or null to create the empty geometry. /// </param> public Text(CoordinateCollection coordinates, string text, GeometryFactory factory) : base(factory) { m_objCoordinates = coordinates; if (coordinates != null) { m_objPosition = coordinates.Count != 0 ? coordinates[0] : null; } m_strLabel = text; }
public void AddRangeTest() { // Ensure there are four elements before starting Assert.AreEqual(4, collection.Count); // Make a clone of the collection CoordinateCollection collection2 = (CoordinateCollection)collection.Clone(); // Add the cloned data back into the original collection collection.AddRange(collection2); // Test to ensure the count has gone up. Assert.AreEqual(8, collection.Count); }
private ICoordinateList ReadCoordinates(bool hasZ) { int nCount = m_objReader.ReadInt32(); ICoordinateList coords = new CoordinateCollection(nCount); for (int i = 0; i < nCount; i++) { coords.Add(ReadCoordinate(hasZ)); } return(coords); }
private LineString GetKml(TLineString line) { var(xys, _) = ReprojectGeometry(line); var kml = new LineString(); var cc = new CoordinateCollection(); for (var i = 0; i < line.Coords.Count; i++) { cc.Add(new Vector(xys[i * 2 + 1], xys[i * 2])); } kml.Coordinates = cc; return(kml); }
/// <summary> /// An alternative to Stack.ToArray, which is not present in earlier versions /// of Java. /// </summary> private ICoordinateList ToCoordinateArray(Stack stack) { CoordinateCollection list = new CoordinateCollection(); foreach (object obj in stack) { list.Add((Coordinate)obj); } list.Reverse(); return(list); }
/// <summary> /// Returns a list containing a Coordinate from each Polygon, LineString, and Point /// found inside the specified geometry. Thus, if the specified geometry is /// not a GeometryCollection, an empty list will be returned. /// </summary> public static ICoordinateList GetCoordinates(Geometry geometry) { if (geometry == null) { throw new ArgumentNullException("geometry"); } ICoordinateList pts = new CoordinateCollection(); geometry.Apply(new ConnectedElementPointFilter(pts)); return(pts); }
/// <summary> /// /// </summary> /// <param name="envelope"></param> /// <returns></returns> public string Write(Envelope envelope) { if (envelope == null) { throw new ArgumentNullException("envelope"); } try { m_bIsMeasured = false; StringBuilder builder = new StringBuilder(); StringWriter writer = new StringWriter(builder); XmlTextWriter xmlWriter = new XmlTextWriter(writer); xmlWriter.Formatting = Formatting.Indented; if (m_nIndent > 0) { xmlWriter.Indentation = m_nIndent; } WriteStartElement(xmlWriter, GeometryGml2.GmlBox, null, m_bIncludeSRID); if (!envelope.IsEmpty) { CoordinateCollection coordindates = new CoordinateCollection(2); coordindates.Add(envelope.Min); coordindates.Add(envelope.Max); Write(coordindates, xmlWriter); } WriteEndElement(xmlWriter); return(builder.ToString()); } catch (IOException ex) { ExceptionManager.Publish(ex); throw ex; } catch (Exception ex) { ExceptionManager.Publish(ex); throw ex; } }
public void Test3dParse() { CoordinateCollection coords = new CoordinateCollection(); coords.AddInnerText("1.123,-2.789,3000.5919"); Assert.That(coords.Count, Is.EqualTo(1)); AssertVector(coords.ElementAt(0), -2.789, 1.123, 3000.5919); // This should NOT destroy the first value coords.AddInnerText("\n-122.123,38.789,1050.0987 -122.123,39.789,1050.098"); Assert.That(coords.Count, Is.EqualTo(3)); AssertVector(coords.ElementAt(1), 38.789, -122.123, 1050.0987); AssertVector(coords.ElementAt(2), 39.789, -122.123, 1050.098); }
// Creates a polyline with two paths in the shape of an 'X' centered at the given point private Polyline CreatePolylineX(MapPoint center, double length) { var halfLen = length / 2.0; CoordinateCollection coords1 = new CoordinateCollection(); coords1.Add(new Coordinate(center.X - halfLen, center.Y + halfLen)); coords1.Add(new Coordinate(center.X + halfLen, center.Y - halfLen)); CoordinateCollection coords2 = new CoordinateCollection(); coords2.Add(new Coordinate(center.X + halfLen, center.Y + halfLen)); coords2.Add(new Coordinate(center.X - halfLen, center.Y - halfLen)); return new Polyline(new List<CoordinateCollection> { coords1, coords2 }, mapView.SpatialReference); }
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 var point = new Point { Coordinate = new Vector(37.42052549, -122.0816695) }; var coordinates = new CoordinateCollection(); var lineString = new LineString() { Extrude = true, Tessellate = true, AltitudeMode = AltitudeMode.Absolute, Coordinates = coordinates }; var placemark = new Placemark { Name = "Cool Statue", Geometry = lineString }; // This is the root element of the file var kml = new Kml { Feature = placemark }; var serializer = new Serializer(); serializer.Serialize(kml); Console.WriteLine(serializer.Xml); Console.WriteLine("\nReading Xml..."); var 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); }
/// <param name="coordinates"> Contains the single coordinate on which to base this Point /// , or null to create the empty geometry. /// </param> public Circle(CoordinateCollection coordinates, double radius, GeometryFactory factory) : base(factory) { if (coordinates == null) { coordinates = new CoordinateCollection(); } Debug.Assert(coordinates.Count <= 1); m_objCoordinates = coordinates; m_objCenter = coordinates.Count != 0 ? coordinates[0] : null; m_dRadius = radius; }
private ICoordinateList ComputeOctRing(ICoordinateList inputPts) { Coordinate[] octPts = ComputeOctPts(inputPts); CoordinateCollection coordList = new CoordinateCollection(octPts); // points must all lie in a line if (coordList.Count < 3) { return(null); } coordList.CloseRing(); return(coordList); }
/// <summary> If the coordinate array argument has repeated points, /// constructs a new array containing no repeated points. /// Otherwise, returns the argument. /// </summary> /// <seealso cref="HasRepeatedCoordinates(Coordinate[])"> /// </seealso> private static ICoordinateList RemoveRepeatedPoints(ICoordinateList coord) { if (!HasRepeatedCoordinates(coord)) { return(coord); } CoordinateCollection coordList = new CoordinateCollection(); for (int i = 0; i < coord.Count; i++) { coordList.Add(coord[i], false); } return(coordList); }
public void TestWalkCustomElements() { const int Count = 10; CoordinateCollection coordinates = new CoordinateCollection(); for (int i = 0; i < Count; ++i) { coordinates.Add(new Vector()); } Assert.That(ElementWalker.Walk(coordinates).Count(), Is.EqualTo(1)); // This class uses a private class deriving from ICustomElement as a child // Make sure it's not included. ItemIcon icon = new ItemIcon(); icon.State = ItemIconStates.Open | ItemIconStates.Error; Assert.That(ElementWalker.Walk(icon).Count(), Is.EqualTo(1)); }
/// <summary> /// Writes a Location collection to the writer /// </summary> /// <param name="Locations"></param> private static void WriteLocations(CoordinateCollection Locations, TextWriter writer, bool includeAltitude) { writer.Write("("); for (int i = 0; i < Locations.Count; i++) { if (i > 0) { writer.Write(","); } WriteLocation(Locations[i], writer, includeAltitude); } writer.Write(")"); }
/// <param name="coordinates"> Contains the single coordinate on which to base this Point /// , or null to create the empty geometry. /// </param> public Ellipse(CoordinateCollection coordinates, double majorAxis, double minorAxis, GeometryFactory factory) : base(factory) { if (coordinates == null) { coordinates = new CoordinateCollection(); } Debug.Assert(coordinates.Count <= 1); m_objCoordinates = coordinates; m_objCenter = coordinates.Count != 0 ? coordinates[0] : null; m_dMajorAxis = majorAxis; m_dMinorAxis = minorAxis; }
/// <param name="coordinates"> Contains the single coordinate on which to base this Point /// , or null to create the empty geometry. /// </param> protected CircularArc(ICoordinateList coordinates, double radius, GeometryFactory factory) : base(factory) { if (coordinates == null) { coordinates = new CoordinateCollection(new Coordinate[] {}); } else { Debug.Assert(coordinates.Count <= 1); m_objCoordinates = coordinates; m_objCenter = coordinates.Count != 0 ? coordinates[0] : null; m_dRadius = radius; } }
public void TestSerialize() { var serializer = new Serializer(); var coords = new CoordinateCollection(); // First test empty. serializer.SerializeRaw(coords); Assert.That(serializer.Xml, Is.EqualTo("<coordinates xmlns=\"http://www.opengis.net/kml/2.2\" />")); // Now with a value. coords.Add(new Vector(1, 2, 3)); serializer.SerializeRaw(coords); string expected = string.Format(CultureInfo.InvariantCulture, XmlFormat, "2,1,3"); Assert.That(serializer.Xml, Is.EqualTo(expected)); }
public void SerializeShouldUseTheDelimiterToSeparatePoints() { var coords = new CoordinateCollection(new [] { new Vector(1, 2, 3), new Vector(2, 1, 3) }); var serializer = new Serializer(); CoordinateCollection.Delimiter = " "; serializer.SerializeRaw(coords); CoordinateCollection.Delimiter = "\n"; // Reset to prove it worked during the call to serialize var expected = string.Format(CultureInfo.InvariantCulture, XmlFormat, "2,1,3 1,2,3"); Assert.That(serializer.Xml, Is.EqualTo(expected)); }
/// <param name="points"> the points of the linestring, or null /// to create the empty geometry. Consecutive points may not be equal. /// </param> public LineString(ICoordinateList coords, GeometryFactory factory) : base(factory) { if (coords == null) { coords = new CoordinateCollection(); } else { if (coords.Count == 1) { throw new ArgumentException("point array must contain 0 or >1 elements"); } } this.points = coords; }
/// <param name="points"> the points of the linestring, or null /// to create the empty geometry. Consecutive points may not be equal. /// </param> public BezierCurve(ICoordinateList coordinates, GeometryFactory factory) : base(factory) { if (coordinates == null) { coordinates = new CoordinateCollection(); } else { if (coordinates.Count <= 1) { throw new ArgumentException("point array must contain 0 or >1 elements"); } } this.points = coordinates; }
// Creates a square polygon with a hole centered at the given point private Polygon CreatePolygonBox(MapPoint center, double length) { var halfLen = length / 2.0; CoordinateCollection coords = new CoordinateCollection(); coords.Add(new Coordinate(center.X - halfLen, center.Y + halfLen)); coords.Add(new Coordinate(center.X + halfLen, center.Y + halfLen)); coords.Add(new Coordinate(center.X + halfLen, center.Y - halfLen)); coords.Add(new Coordinate(center.X - halfLen, center.Y - halfLen)); coords.Add(new Coordinate(center.X - halfLen, center.Y + halfLen)); halfLen /= 3; CoordinateCollection coordsHole = new CoordinateCollection(); coordsHole.Add(new Coordinate(center.X - halfLen, center.Y + halfLen)); coordsHole.Add(new Coordinate(center.X - halfLen, center.Y - halfLen)); coordsHole.Add(new Coordinate(center.X + halfLen, center.Y - halfLen)); coordsHole.Add(new Coordinate(center.X + halfLen, center.Y + halfLen)); coordsHole.Add(new Coordinate(center.X - halfLen, center.Y + halfLen)); return new Polygon(new List<CoordinateCollection> { coords, coordsHole }, mapView.SpatialReference); }
private void CreateReportFiles(Dictionary<string, PictureInformation> listPhotosWithInfo, string dirWithImages, float offset) { // Write report files Document kml = new Document(); // 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 longitude/X latitude/Y 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) { 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(); }*/ kml.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(kml); 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"); } }
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 { } }
private static Vector[] ParseVector(string input) { CoordinateCollection coords = new CoordinateCollection(); coords.AddInnerText(input); return coords.ToArray(); }
public void UpdateCentroidTest() { // Setup a new Collection CoordinateCollection col = new CoordinateCollection(); // Check the centroid has been initalised Assert.AreEqual(0, col.Centroid.Latitude); Assert.AreEqual(0, col.Centroid.Latitude); Assert.AreEqual(0, col.Centroid.Altitude); // Add four coordinates in the shape of a square col.Add(new Coordinate(10, 10, 0)); col.Add(new Coordinate(10, 20, 0)); col.Add(new Coordinate(20, 10, 0)); col.Add(new Coordinate(20, 20, 0)); // Check the centroid has been updated Assert.AreEqual(15, col.Centroid.Longitude); Assert.AreEqual(15, col.Centroid.Latitude); Assert.AreEqual(0, col.Centroid.Altitude); }
public void TestCollection() { CoordinateCollection coords = new CoordinateCollection(); coords.Add(new Vector(1, 2, 3)); coords.Add(new Vector(2, 3, 4)); Assert.That(() => coords.Add(null), Throws.TypeOf<ArgumentNullException>()); Assert.That(coords.Count, Is.EqualTo(2)); Vector vector = null; int counter = 0; foreach (var point in coords) { ++counter; vector = point; } Assert.That(counter, Is.EqualTo(2)); Assert.That(vector.Altitude, Is.EqualTo(4)); Assert.True(coords.Contains(vector)); Assert.False(coords.Contains(new Vector())); Assert.False(coords.Contains(null)); Assert.True(coords.Remove(vector)); Assert.False(coords.Remove(new Vector())); Assert.False(coords.Remove(null)); Assert.That(coords.Count, Is.EqualTo(1)); coords.Add(vector); Vector[] vectors = new Vector[3]; coords.CopyTo(vectors, 1); Assert.That(vectors[0], Is.Null); Assert.That(vectors[1], Is.Not.Null); Assert.That(vectors[2], Is.Not.Null); coords.Clear(); Assert.That(coords.Count, Is.EqualTo(0)); }