Пример #1
0
        private void WriteLineString(LineString lineString)
        {
            wkbWriter.Write(lineString.Points.Count);

            foreach (Point point in lineString.Points)
                WritePoint(point, lineString.Dimension);
        }
Пример #2
0
 public void Multils()
 {
     var rnd = new Random();
     var ls = new LineString[40];
     var lscheck = new GeoAPI.Geometries.ILineString[40];
     var gf = new NetTopologySuite.Geometries.GeometryFactory();
     for (var ii = 0; ii < 40; ii++)
     {
         var coord = new Coordinate[36];
         var coordcheck = new GeoAPI.Geometries.Coordinate[36];
         for (var i = 0; i < 36; i++)
         {
             coord[i] = new Coordinate((rnd.NextDouble() * 360) - 180, (rnd.NextDouble() * 180) - 90);
             var x = coord[i].X;
             var y = coord[i].Y;
             var c = new GeoAPI.Geometries.Coordinate(x, y);
             coordcheck[i] = c;
         }
         ls[ii] = new LineString(coord);
         lscheck[ii] = gf.CreateLineString(coordcheck);
     }
     var mls = new MultiLineString(ls);
     var mlscheck = gf.CreateMultiLineString(lscheck);
     for (var ii = 0; ii < mls.Coordinates.Count; ii++)
     {
         Assert.AreEqual(mls.Coordinates[ii].X, mlscheck.Coordinates[ii].X);
         Assert.AreEqual(mls.Coordinates[ii].Y, mlscheck.Coordinates[ii].Y);
     }
     Assert.AreEqual(mls.NumGeometries, mlscheck.NumGeometries);
 }
        public void LsToByteArray()
        {
            Coordinate[] coords = new Coordinate[36];
            Random rnd = new Random();
            for (int i = 0; i < 36; i++)
            {
                coords[i] = new Coordinate((rnd.NextDouble() * 360) - 180, (rnd.NextDouble() * 180) - 90);
            }
            LineString ls = new LineString(coords);
            byte[] vals = ls.ToBinary();
            WkbReader wkr = new WkbReader();
            IGeometry g = wkr.Read(vals);
            LineString lscheck = g as LineString;
            if (lscheck != null)
            {
                for (int i = 0; i < ls.Count; i++)
                {
                    Assert.AreEqual(ls.Coordinates[i].X, lscheck.Coordinates[i].X);
                    Assert.AreEqual(ls.Coordinates[i].Y, lscheck.Coordinates[i].Y);
                }
                Assert.AreEqual(ls.Length, lscheck.Length);
                Assert.AreEqual(ls.Envelope.Height, lscheck.Envelope.Height);
                Assert.AreEqual(ls.Envelope.Width, lscheck.Envelope.Width);
            }
            else
            {
                Assert.Fail("The test failed bc the check lscheck was null.");
            }

        }
Пример #4
0
 /// <summary>
 /// Adds an Edge, DirectedEdges, and Nodes for the given LineString representation
 /// of an edge.
 /// </summary>
 public virtual void AddEdge(LineString lineString)
 {
     if (lineString.IsEmpty)
         return;
     IList<Coordinate> coordinates = CoordinateArrays.RemoveRepeatedPoints(lineString.Coordinates);
     Coordinate startCoordinate = coordinates[0];
     Coordinate endCoordinate = coordinates[coordinates.Count - 1];
     Node startNode = GetNode(startCoordinate);
     Node endNode = GetNode(endCoordinate);
     DirectedEdge directedEdge0 = new LineMergeDirectedEdge(startNode, endNode,
                                         coordinates[1], true);
     DirectedEdge directedEdge1 = new LineMergeDirectedEdge(endNode, startNode,
                                         coordinates[coordinates.Count - 2], false);
     Edge edge = new LineMergeEdge(lineString);
     edge.SetDirectedEdges(directedEdge0, directedEdge1);
     Add(edge);
 }
Пример #5
0
        protected Geometry CreateGeometry(GeometryType geometryType, Dimension dimension)
        {
            Geometry geometry = null;

            switch (geometryType)
            {
                case GeometryType.Point: geometry = new Point(); break;
                case GeometryType.LineString: geometry = new LineString(); break;
                case GeometryType.Polygon: geometry = new Polygon(); break;
                case GeometryType.MultiPoint: geometry = new MultiPoint(); break;
                case GeometryType.MultiLineString: geometry = new MultiLineString(); break;
                case GeometryType.MultiPolygon: geometry = new MultiPolygon(); break;
                case GeometryType.GeometryCollection: geometry = new GeometryCollection(); break;
            }

            geometry.Dimension = dimension;

            return geometry;
        }
Пример #6
0
 public void LineLength()
 {
     var coords = new Coordinate[36];
     var rnd = new Random();
     var coordscheck = new GeoAPI.Geometries.Coordinate[36];
     for (var i = 0; i < 36; i++)
     {
         coords[i] = new Coordinate((rnd.NextDouble() * 360) - 180, (rnd.NextDouble() * 180) - 90);
         var x = coords[i].X;
         var y = coords[i].Y;
         var c = new GeoAPI.Geometries.Coordinate(x, y);
         coordscheck[i] = c;
     }
     var gf = new NetTopologySuite.Geometries.GeometryFactory();
     var lscheck = gf.CreateLineString(coordscheck);
     var ls = new LineString(coords);
     var length = ls.Length;
     var lengthcheck = lscheck.Length;
     Assert.AreEqual(length, lengthcheck);
 }
Пример #7
0
 public void LineLength()
 {
     Coordinate[] coords = new Coordinate[36];
     Random rnd = new Random();
     GeoAPI.Geometries.ICoordinate[] coordscheck = new GeoAPI.Geometries.ICoordinate[36];
     for (int i = 0; i < 36; i++)
     {
         coords[i] = new Coordinate((rnd.NextDouble() * 360) - 180, (rnd.NextDouble() * 180) - 90);
         double x = coords[i].X;
         double y = coords[i].Y;
         GisSharpBlog.NetTopologySuite.Geometries.Coordinate c = new GisSharpBlog.NetTopologySuite.Geometries.Coordinate(x, y);
         coordscheck[i] = c;
     }
     GisSharpBlog.NetTopologySuite.Geometries.GeometryFactory gf = new GisSharpBlog.NetTopologySuite.Geometries.GeometryFactory();
     GeoAPI.Geometries.ILineString lscheck = gf.CreateLineString(coordscheck);
     LineString ls = new LineString(coords);
     double length = ls.Length;
     double lengthcheck = lscheck.Length;
     Assert.AreEqual(length, lengthcheck);
 }
Пример #8
0
        public void Two_null_linestrings_should_equal()
        {
            LineString lineString = null, other = null;

            (lineString == other).Should().BeTrue();
        }
Пример #9
0
            /// <summary>
            /// Generates a bounding rect around a lat/lon rect, to constrain queries.
            /// Anyway this is a spherical rectangle, not a real rectangle, so it's not an exact rectangle but a rather strange rect.
            /// To prevent problems with this approach, we're changing the "radius" to a real radius of the bounding circle, which will be almost exact
            /// </summary>
            /// <param name="lat1"></param>
            /// <param name="lon1"></param>
            /// <param name="lat2"></param>
            /// <param name="lon2"></param>
            /// <param name="distanceInKilometers">Kinda' like radius</param>
            /// <returns></returns>
            static public LineString RectForDistanceAroundRect(double lat1, double lon1, double lat2, double lon2, double distanceInKilometers)
            {
                // Get the circle that bounds the rect. This will give us a much more accurate rect
                distanceInKilometers = (Math.Sqrt(2.0 * (distanceInKilometers * 2.0) * (distanceInKilometers * 2.0)) / 2.0);

                double d = Math.Min(lat1, lat2);
                lat2 = Math.Max(lat1, lat2);
                lat1 = d;

                d = Math.Min(lon1, lon2);
                lon2 = Math.Max(lon1, lon2);
                lon1 = d;

                LineString rect = new LineString();
                double distanceLat = distanceInKilometers / AVERAGE_KM_PER_LATITUDE_DEGREE;
                double distanceLon1 = distanceInKilometers / (AVERAGE_KM_PER_LATITUDE_DEGREE / Math.Cos(DEGREES_TO_RADIANS * lat1));
                double distanceLon2 = distanceInKilometers / (AVERAGE_KM_PER_LATITUDE_DEGREE / Math.Cos(DEGREES_TO_RADIANS * lat2));

                // This is enough as the wkbs are calculating the bounds and retrieves a rectangle.
                rect.Points.Add(new Point(lat2 + distanceLat, lon2 + distanceLon2));
                rect.Points.Add(new Point(lat1 - distanceLat, lon1 - distanceLon1));
                return rect;
            }
Пример #10
0
        public void Clone_an_invalid_linestring_should_still_invalid()
        {
            var lineString = new LineString();

            lineString.Clone().IsValid.Should().BeFalse();
        }
Пример #11
0
        public void One_valid_linestring_should_equal_to_itself()
        {
            var lineString = new LineString(new[] { new Point(120, 50) });

            lineString.Equals(lineString).Should().BeTrue();
        }
Пример #12
0
        public static void Write(LineString line, JsonTextWriter writer)
        {
            if (line == null)
                return;
            if (writer == null)
                throw new ArgumentNullException("writer", "A valid JSON writer object is required");

            writer.WriteStartObject();
            writer.WritePropertyName("type");
            writer.WriteValue("LineString");
            writer.WritePropertyName("coordinates");
            writer.WriteStartArray();
            foreach (Point entry in line.Vertices)
                WriteCoord(entry, writer);
            writer.WriteEndArray();
            writer.WriteEndObject();
        }
Пример #13
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="geom"></param>
 /// <returns></returns>
 public virtual bool IsSimple(LineString geom)
 {
     return IsSimpleLinearGeometry(geom);
 }
Пример #14
0
        /// <summary>
        /// Reads the JSON representation of the object.
        /// </summary>
        /// <param name="reader">The <see cref="T:Newtonsoft.Json.JsonReader" /> to read from.</param>
        /// <param name="objectType">Type of the object.</param>
        /// <param name="existingValue">The existing existingValue of object being read.</param>
        /// <param name="serializer">The calling serializer.</param>
        /// <returns>
        /// Deserialized object.
        /// </returns>
        public override object ReadJson(
            JsonReader reader,
            Type objectType,
            object existingValue,
            JsonSerializer serializer)
        {
            JToken token = JToken.Load(reader);

            if (token.Type == JTokenType.Null)
            {
                return(null);
            }

            if (token.Type != JTokenType.Object)
            {
                throw new JsonSerializationException(RMResources.SpatialInvalidGeometryType);
            }

            JToken typeToken = token["type"];

            if (typeToken.Type != JTokenType.String)
            {
                throw new JsonSerializationException(RMResources.SpatialInvalidGeometryType);
            }

            Geometry result;

            switch (typeToken.Value <string>())
            {
            case "Point":
                result = new Point();
                break;

            case "MultiPoint":
                result = new MultiPoint();
                break;

            case "LineString":
                result = new LineString();
                break;

            case "MultiLineString":
                result = new MultiLineString();
                break;

            case "Polygon":
                result = new Polygon();
                break;

            case "MultiPolygon":
                result = new MultiPolygon();
                break;

            case "GeometryCollection":
                result = new GeometryCollection();
                break;

            default:
                throw new JsonSerializationException(RMResources.SpatialInvalidGeometryType);
            }

            serializer.Populate(token.CreateReader(), result);
            return(result);
        }
Пример #15
0
        private static Folder BuildTripTrack(IEnumerable<Pushpin> positions)
        {
            Folder tripTrack = new Folder()
            {
                id = Guid.NewGuid().ToString(),
                name = "Trip Track",
                visibility = true,
                open = true,
                description = "Trip Track"
            };

            StringBuilder linestringBuilder = new StringBuilder(1024);
            var previousPosition = positions.FirstOrDefault();
            foreach (var position in positions.Skip(1))
            {
                linestringBuilder.AppendFormat(
                    "{0},{1},0,{2},{3},0\n",
                    previousPosition.Longitude,
                    previousPosition.Latitude,
                    position.Longitude,
                    position.Latitude);
                previousPosition = position;
            }

            Placemark track = new Placemark()
            {
                name = "TripTrack"
            };
            LineString lineString = new LineString(new coordinates(linestringBuilder.ToString()));
            lineString.tessellate = true;
            track.Geometry = lineString;
            tripTrack.Features.Add(track);

            return tripTrack;
        }
Пример #16
0
        public void If_linestring_with_one_point_then_it_should_be_close()
        {
            var lineString = new LineString(new[] { new Point(-120, 30) });

            lineString.IsClosed.Should().BeTrue();
        }
Пример #17
0
        public void If_linestring_with_last_overlap_point_then_it_should_be_close()
        {
            var lineString = new LineString(new[] { new Point(-120, 30), new Point(20, 70), new Point(0, 0), new Point(-120, 30) });

            lineString.IsClosed.Should().BeTrue();
        }
Пример #18
0
        public void If_linestring_with_valid_point_then_it_should_be_valid()
        {
            var lineString = new LineString(new [] { new Point(-120, 30) });

            lineString.IsValid.Should().BeTrue();
        }
Пример #19
0
        public void If_linestring_with_invalid_point_then_it_should_be_invalid()
        {
            var lineString = new LineString(new [] { new Point(-180.1, 90) });

            lineString.IsValid.Should().BeFalse();
        }
Пример #20
0
        public void Clone_a_valid_linestring_should_equal()
        {
            var lineString = new LineString(new[] { new Point(120, 50) });

            lineString.Clone().Equals(lineString).Should().BeTrue();
        }
Пример #21
0
        private static LineString CreateWKBLineString(BinaryReader reader, WkbByteOrder byteOrder)
        {
            var l = new LineString();
            //l.Vertices.AddRange(ReadCoordinates(reader, byteOrder));
            var arrPoint = ReadCoordinates(reader, byteOrder);
            foreach (var t in arrPoint)
            {
                l.Vertices.Add(t);
            }

            return l;
        }
Пример #22
0
 public static Terradue.ServiceModel.Ogc.GeoRss.GeoRss.GeoRssLine ToGeoRssLine(this LineString lineString)
 {
     return(new Terradue.ServiceModel.Ogc.GeoRss.GeoRss.GeoRssLine()
     {
         Item = lineString.Coordinates.ToArray().ToGmlPosList(2).Text
     });
 }
Пример #23
0
 public PolygonizeEdge(LineString line)
 {
     this.line = line;
 }
Пример #24
0
 /// <summary>
 /// Constructs a LineMergeEdge with vertices given by the
 /// specified LineString.
 /// </summary>
 public LineMergeEdge(LineString line)
 {
     this.line = line;
 }
Пример #25
0
        /// <summary>
        /// Converts a LineString to &lt;LineString Text&gt; format, then
        /// Appends it to the writer.
        /// </summary>
        /// <param name="lineString">The LineString to process.</param>
        /// <param name="level"></param>
        /// <param name="doIndent"></param>
        /// <param name="writer">The output stream to Append to.</param>
        protected void AppendLineStringText(LineString lineString, int level, bool doIndent, StringWriter writer)
        {
            if ( lineString.isEmpty() )
            {
                writer.Write("EMPTY");
            }
            else
            {
                if (doIndent)
                {
                    Indent(level, writer);
                }

                writer.Write("(");

                for (int i = 0; i < lineString.getNumPoints(); i++)
                {
                    if (i > 0)
                    {
                        writer.Write(", ");
                        if (i % 10 == 0) Indent(level + 2, writer);
                    }

                    AppendCoordinate( lineString.getCoordinates()[i], writer, lineString.getPrecisionModel() );
                }

                writer.Write(")");
            }
        }
Пример #26
0
        /// <summary>
        /// Interprets an OSM-object and returns the corresponding geometry.
        /// </summary>
        /// <param name="osmObject"></param>
        /// <returns></returns>
        public override GeometryCollection Interpret(CompleteOsmGeo osmObject)
        {
            // DISCLAIMER: this is a very very very simple geometry interpreter and
            // contains hardcoded all relevant tags.

            GeometryCollection collection = new GeometryCollection();
            TagsCollection     tags;

            if (osmObject != null)
            {
                switch (osmObject.Type)
                {
                case CompleteOsmType.Node:
                    SimpleTagsCollection newCollection = new SimpleTagsCollection(
                        osmObject.Tags);
                    newCollection.RemoveKey("FIXME");
                    newCollection.RemoveKey("node");
                    newCollection.RemoveKey("source");

                    if (newCollection.Count > 0)
                    {     // there is still some relevant information left.
                        collection.Add(new Point((osmObject as CompleteNode).Coordinate));
                    }
                    break;

                case CompleteOsmType.Way:
                    tags = osmObject.Tags;

                    bool isArea = false;
                    if ((tags.ContainsKey("building") && !tags.IsFalse("building")) ||
                        (tags.ContainsKey("landuse") && !tags.IsFalse("landuse")) ||
                        (tags.ContainsKey("amenity") && !tags.IsFalse("amenity")) ||
                        (tags.ContainsKey("harbour") && !tags.IsFalse("harbour")) ||
                        (tags.ContainsKey("historic") && !tags.IsFalse("historic")) ||
                        (tags.ContainsKey("leisure") && !tags.IsFalse("leisure")) ||
                        (tags.ContainsKey("man_made") && !tags.IsFalse("man_made")) ||
                        (tags.ContainsKey("military") && !tags.IsFalse("military")) ||
                        (tags.ContainsKey("natural") && !tags.IsFalse("natural")) ||
                        (tags.ContainsKey("office") && !tags.IsFalse("office")) ||
                        (tags.ContainsKey("place") && !tags.IsFalse("place")) ||
                        (tags.ContainsKey("power") && !tags.IsFalse("power")) ||
                        (tags.ContainsKey("public_transport") && !tags.IsFalse("public_transport")) ||
                        (tags.ContainsKey("shop") && !tags.IsFalse("shop")) ||
                        (tags.ContainsKey("sport") && !tags.IsFalse("sport")) ||
                        (tags.ContainsKey("tourism") && !tags.IsFalse("tourism")) ||
                        (tags.ContainsKey("waterway") && !tags.IsFalse("waterway")) ||
                        (tags.ContainsKey("wetland") && !tags.IsFalse("wetland")) ||
                        (tags.ContainsKey("water") && !tags.IsFalse("water")) ||
                        (tags.ContainsKey("aeroway") && !tags.IsFalse("aeroway")))
                    {     // these tags usually indicate an area.
                        isArea = true;
                    }

                    if (tags.IsTrue("area"))
                    {     // explicitly indicated that this is an area.
                        isArea = true;
                    }
                    else if (tags.IsFalse("area"))
                    {     // explicitly indicated that this is not an area.
                        isArea = false;
                    }

                    if (isArea)
                    {     // area tags leads to simple polygon
                        LineairRing lineairRing = new LineairRing((osmObject as CompleteWay).GetCoordinates().ToArray <GeoCoordinate>());
                        lineairRing.Attributes = new SimpleGeometryAttributeCollection(tags);
                        collection.Add(lineairRing);
                    }
                    else
                    {     // no area tag leads to just a line.
                        LineString lineString = new LineString((osmObject as CompleteWay).GetCoordinates().ToArray <GeoCoordinate>());
                        lineString.Attributes = new SimpleGeometryAttributeCollection(tags);
                        collection.Add(lineString);
                    }
                    break;

                case CompleteOsmType.Relation:
                    CompleteRelation relation = (osmObject as CompleteRelation);
                    tags = relation.Tags;

                    string typeValue;
                    if (tags.TryGetValue("type", out typeValue))
                    {     // there is a type in this relation.
                        if (typeValue == "multipolygon")
                        { // this relation is a multipolygon.
                            Geometry geometry = this.InterpretMultipolygonRelation(relation);
                            if (geometry != null)
                            {     // add the geometry.
                                collection.Add(geometry);
                            }
                        }
                        else if (typeValue == "boundary")
                        {     // this relation is a boundary.
                        }
                    }
                    break;
                }
            }
            return(collection);
        }
Пример #27
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="parentLine"></param>
 public TaggedLineString(LineString parentLine) : this(parentLine, 2) { }
Пример #28
0
        /// <summary>
        /// The Search Along Route endpoint allows you to perform a fuzzy search for POIs along a specified route. This search is constrained by specifying the maxDetourTime limiting measure.
        /// To send the route-points you will use a POST request where the request body will contain the route object represented as a GeoJSON LineString type and the Content-Type header will be set to application/json. Each route-point in route is represented as a GeoJSON Position type i.e. an array where the longitude value is followed by the latitude value and the altitude value is ignored. The route should contain at least 2 route-points.
        /// It is possible that original route will be altered, some of it's points may be skipped. If the route that passes through the found point is faster than the original one, the detourTime value in the response is negative.
        /// </summary>
        /// <param name="req"></param>
        /// <param name="lineString"></param>
        /// <returns></returns>
        public virtual async Task <Response <SearchAlongRouteResponse> > GetSearchAlongRoute(SearchAlongRouteRequest req, LineString lineString)
        {
            try
            {
                var bodyContent = new { route = lineString };

                var queryContent = Newtonsoft.Json.JsonConvert.SerializeObject(bodyContent);

                var args = GetQuery <SearchAlongRouteRequest>(req, true);

                var url = $"https://atlas.microsoft.com/search/alongRoute/json?subscription-key={Key}&api-version=1.0{args}";

                using (var responseMsg = await GetHttpResponseMessage(url, queryContent))
                {
                    using (var data = responseMsg.Content)
                    {
                        var content = await data.ReadAsStringAsync();

                        var response = Newtonsoft.Json.JsonConvert.DeserializeObject <SearchAlongRouteResponse>(content);
                        return(Response <SearchAlongRouteResponse> .CreateResponse(response));
                    }
                }
            }
            catch (AzureMapsException ex)
            {
                return(Response <SearchAlongRouteResponse> .CreateErrorResponse(ex));
            }
        }
Пример #29
0
 /// <summary>
 ///     Converts a LineString to &lt;LineString Text&gt; format, then
 ///     Appends it to the writer.
 /// </summary>
 /// <param name="lineString">The LineString to process.</param>
 /// <param name="writer">The output stream to Append to.</param>
 private static void AppendLineStringText(LineString lineString, StringWriter writer)
 {
     if ((lineString == null) || lineString.IsEmpty())
         writer.Write("EMPTY");
     else
     {
         writer.Write("(");
         for (var i = 0; i < lineString.NumPoints; i++)
         {
             if (i > 0)
                 writer.Write(", ");
             AppendCoordinate(lineString.Vertices[i], writer);
         }
         writer.Write(")");
     }
 }
Пример #30
0
        public void One_none_null_linestring_should_not_equal_a_null_linestring()
        {
            LineString lineString = null, other = new LineString();

            (lineString == other).Should().BeFalse();
        }
Пример #31
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="lineString"></param>
 /// <param name="writer"></param>
 protected virtual void Write(LineString lineString, XmlTextWriter writer)
 {
     writer.WriteStartElement("LineString");
     Write(lineString.Coordinates, writer);
     writer.WriteEndElement();
 }
Пример #32
0
        public void LineStringEnvelopeHeightWidth()
        {
            var coords = new Coordinate[36];
            var rnd = new Random();
            var coordscheck = new GeoAPI.Geometries.Coordinate[36];
            for (var i = 0; i < 36; i++)
            {
                coords[i] = new Coordinate((rnd.NextDouble() * 360) - 180, (rnd.NextDouble() * 180) - 90);
                var x = coords[i].X;
                var y = coords[i].Y;
                var c = new GeoAPI.Geometries.Coordinate(x, y);
                coordscheck[i] = c;
            }
            var gf = new NetTopologySuite.Geometries.GeometryFactory();
            GeoAPI.Geometries.ILineString lscheck = gf.CreateLineString(coordscheck);
            var ls = new LineString(coords);
            AssertExt.AreEqual15(ls.Envelope.Width, lscheck.EnvelopeInternal.Width);
            AssertExt.AreEqual15(ls.Envelope.Height, lscheck.EnvelopeInternal.Height);

        }
 public LineString Test(LineString arg) => arg;
Пример #34
0
        /// <inheritdoc/>
        protected override void AppendGeometry(ShapefileHeader header, Geometry feature, int numFeatures)
        {
            FileInfo fi     = new FileInfo(Filename);
            int      offset = Convert.ToInt32(fi.Length / 2);

            FileStream shpStream = new FileStream(Filename, FileMode.Append, FileAccess.Write, FileShare.None, 10000);
            FileStream shxStream = new FileStream(header.ShxFilename, FileMode.Append, FileAccess.Write, FileShare.None, 100);

            List <int> parts = new List <int>();

            List <Coordinate> points = new List <Coordinate>();
            int contentLength        = 22;

            for (int iPart = 0; iPart < feature.NumGeometries; iPart++)
            {
                parts.Add(points.Count);
                LineString pg = feature.GetGeometryN(iPart) as LineString;
                if (pg == null)
                {
                    continue;
                }
                points.AddRange(pg.Coordinates);
            }

            contentLength += 2 * parts.Count;
            if (header.ShapeType == ShapeType.PolyLine)
            {
                contentLength += points.Count * 8;
            }

            if (header.ShapeType == ShapeType.PolyLineM)
            {
                contentLength += 8;                 // mmin mmax
                contentLength += points.Count * 12; // x, y, m
            }

            if (header.ShapeType == ShapeType.PolyLineZ)
            {
                contentLength += 16;                // mmin, mmax, zmin, zmax
                contentLength += points.Count * 16; // x, y, m, z
            }

            ////                                              Index File
            //                                                -------------------------------------------------------------------
            //                                                Position     Value               Type        Number      Byte Order
            //                                                -------------------------------------------------------------------
            shxStream.WriteBe(offset);                        // Byte 0    Offset              Integer     1           Big
            shxStream.WriteBe(contentLength);                 // Byte 4    Content Length      Integer     1           Big
            shxStream.Flush();
            shxStream.Close();
            ////                                              X Y Poly Lines
            //                                                -------------------------------------------------------------------
            //                                                Position     Value               Type        Number      Byte Order
            //                                                -------------------------------------------------------------------
            shpStream.WriteBe(numFeatures);                   // Byte 0    Record Number       Integer     1           Big
            shpStream.WriteBe(contentLength);                 // Byte 4    Content Length      Integer     1           Big
            shpStream.WriteLe((int)header.ShapeType);         // Byte 8    Shape Type 3        Integer     1           Little
            if (header.ShapeType == ShapeType.NullShape)
            {
                return;
            }

            shpStream.WriteLe(feature.EnvelopeInternal.MinX); // Byte 12   Xmin                Double      1           Little
            shpStream.WriteLe(feature.EnvelopeInternal.MinY); // Byte 20   Ymin                Double      1           Little
            shpStream.WriteLe(feature.EnvelopeInternal.MaxX); // Byte 28   Xmax                Double      1           Little
            shpStream.WriteLe(feature.EnvelopeInternal.MaxY); // Byte 36   Ymax                Double      1           Little
            shpStream.WriteLe(parts.Count);                   // Byte 44   NumParts            Integer     1           Little
            shpStream.WriteLe(points.Count);                  // Byte 48   NumPoints           Integer     1           Little

            foreach (int iPart in parts)
            {
                shpStream.WriteLe(iPart);                     // Byte 52   Parts               Integer     NumParts    Little
            }

            double[] xyVals = new double[points.Count * 2];

            for (var i = 0; i < points.Count; i++)
            {
                xyVals[i * 2]     = points[i].X;
                xyVals[i * 2 + 1] = points[i].Y;
            }

            shpStream.WriteLe(xyVals, 0, 2 * points.Count);

            if (header.ShapeType == ShapeType.PolyLineZ)
            {
                // Pandell, 2020-06-23: "NetTopologySuite" version 1.7.5 doesn't have "NetTopologySuite.Geometries.Envelope.Minimum" property
                // shpStream.WriteLe(feature.EnvelopeInternal.Minimum.Z);
                // shpStream.WriteLe(feature.EnvelopeInternal.Maximum.Z);
                shpStream.WriteLe(double.NaN);
                shpStream.WriteLe(double.NaN);
                double[] zVals = new double[points.Count];
                for (int ipoint = 0; ipoint < points.Count; ipoint++)
                {
                    zVals[ipoint] = points[ipoint].Z;
                }

                shpStream.WriteLe(zVals, 0, points.Count);
            }

            if (header.ShapeType == ShapeType.PolyLineM || header.ShapeType == ShapeType.PolyLineZ)
            {
                if (feature.Envelope == null)
                {
                    shpStream.WriteLe(0.0);
                    shpStream.WriteLe(0.0);
                }
                else
                {
                    // Pandell, 2020-06-23: "NetTopologySuite" version 1.7.5 doesn't have "NetTopologySuite.Geometries.Envelope.Minimum" property
                    // shpStream.WriteLe(feature.EnvelopeInternal.Minimum.M);
                    // shpStream.WriteLe(feature.EnvelopeInternal.Maximum.M);
                    shpStream.WriteLe(double.NaN);
                    shpStream.WriteLe(double.NaN);
                }

                double[] mVals = new double[points.Count];
                for (int ipoint = 0; ipoint < points.Count; ipoint++)
                {
                    mVals[ipoint] = points[ipoint].M;
                }

                shpStream.WriteLe(mVals, 0, points.Count);
            }

            shpStream.Flush();
            shpStream.Close();
            offset += contentLength;
            Shapefile.WriteFileLength(Filename, offset + 4); // Add 4 for the record header
            Shapefile.WriteFileLength(header.ShxFilename, 50 + numFeatures * 4);
        }
Пример #35
0
 /// <summary>
 /// Convert a polyline to a graphic.
 /// NOTE Although we could have used a Polyline to create the graphic, it would mean that we cannot specify the fill color,
 /// which is why I've chosen to convert it to a Polygon.
 /// </summary>
 /// <param name="ls"></param>
 /// <param name="g"></param>
 private void ConvertPolylineToGraphic(LineString ls, PoiGraphic g)
 {
     var polygon = new Polygon();
     var pc = new PointCollection();
     foreach (var point in ls.Line)
     {
         pc.Add(mercator.FromGeographic(new MapPoint(point.X, point.Y)) as MapPoint);
     }
     //if (pc.First().X != pc.Last().X || pc.First().Y != pc.Last().Y)
     //    pc.Add(pc.First());
     polygon.Rings.Add(pc);
     g.SetGeometry(polygon);
 }
Пример #36
0
        public void OverlapWith2XyEqualCoordinatesInARow()
        {
            var cList1 = new List <Coordinate>
            {
                new CoordinateZ(404907.751, 6471787.332, 107.90599999702),
                new CoordinateZ(404907.751, 6471787.332, 107.906000000003),
                new CoordinateZ(404907.748, 6471786.75, 107.913),
                new CoordinateZ(404909.313, 6471780.353, 107.992000000013),
                new CoordinateZ(404910.342, 6471775.076, 108.057000000001),
                new CoordinateZ(404910.739, 6471768.872, 108.131999999998)
            };

            var cList2 = new List <Coordinate>
            {
                new CoordinateZ(403643.38, 6471428.533, 105.391000000003),
                new CoordinateZ(403655.126, 6471432.67, 105.509999999995),
                new CoordinateZ(403681.732, 6471442.614, 105.774999999994),
                new CoordinateZ(403709.495, 6471452.217, 106.097999999998),
                new CoordinateZ(403768.351, 6471471.859, 106.842000000004),
                new CoordinateZ(403808.526, 6471486.045, 107.251000000018),
                new CoordinateZ(403842.265, 6471497.695, 107.502999999997),
                new CoordinateZ(403872.106, 6471507.932, 107.569000000003),
                new CoordinateZ(403885.109, 6471512.253, 107.570000000022),
                new CoordinateZ(403897.809, 6471516.798, 107.570000000022),
                new CoordinateZ(403908.806, 6471520.209, 107.561000000002),
                new CoordinateZ(403920.496, 6471523.102, 107.538),
                new CoordinateZ(403936, 6471527.101, 107.50900000002),
                new CoordinateZ(403951.27, 6471530.917, 107.479000000007),
                new CoordinateZ(403967.298, 6471533.838, 107.379000000001),
                new CoordinateZ(403983.781, 6471536.211, 107.342000000004),
                new CoordinateZ(404001.67, 6471538.223, 107.372000000003),
                new CoordinateZ(404008.845, 6471539.031, 107.376000000004),
                new CoordinateZ(404038.665, 6471541.303, 107.657000000007),
                new CoordinateZ(404068.718, 6471544.306, 107.566000000021),
                new CoordinateZ(404102.126, 6471547.656, 107.320000000022),
                new CoordinateZ(404115.592, 6471549.174, 107.200000000012),
                new CoordinateZ(404120.202, 6471549.815, 107.165000000008),
                new CoordinateZ(404170.485, 6471555.509, 107.023000000016),
                new CoordinateZ(404218.371, 6471564.16, 107.841),
                new CoordinateZ(404266.142, 6471579.021, 107.308000000019),
                new CoordinateZ(404275.645, 6471581.107, 107.547999999995),
                new CoordinateZ(404295.22, 6471586.933, 107.798999999999),
                new CoordinateZ(404312.662, 6471594.065, 108.028999999995),
                new CoordinateZ(404345.322, 6471606.214, 107.884000000005),
                new CoordinateZ(404362.72, 6471612.33, 106.939000000013),
                new CoordinateZ(404370.226, 6471614.968, 106.691000000006),
                new CoordinateZ(404394.423, 6471623.278, 106.396999999997),
                new CoordinateZ(404411.605, 6471629.948, 106.494000000035),
                new CoordinateZ(404438.912, 6471639.042, 106.926000000007),
                new CoordinateZ(404470.538, 6471649.984, 107.447000000015),
                new CoordinateZ(404510.51, 6471663.29, 107.570000000022),
                new CoordinateZ(404546.025, 6471674.752, 107.732000000018),
                new CoordinateZ(404575.88, 6471685.013, 107.75900000002),
                new CoordinateZ(404613.138, 6471697.079, 107.875),
                new CoordinateZ(404657.753, 6471711.892, 108.015000000014),
                new CoordinateZ(404694.853, 6471724.396, 108.180000000008),
                new CoordinateZ(404725.929, 6471734.583, 108.377000000008),
                new CoordinateZ(404747.434, 6471741.897, 107.820000000022),
                new CoordinateZ(404756.761, 6471745.069, 108.397000000026),
                new CoordinateZ(404784.852, 6471754.261, 108.407000000007),
                new CoordinateZ(404808.738, 6471762.267, 108.550000000017),
                new CoordinateZ(404817.941, 6471764.939, 108.603000000003),
                new CoordinateZ(404827.475, 6471767.412, 108.656000000003),
                new CoordinateZ(404833.218, 6471768.981, 108.688000000009),
                new CoordinateZ(404840.24, 6471770.585, 108.747000000018),
                new CoordinateZ(404845.942, 6471771.198, 108.801000000021),
                new CoordinateZ(404852.977, 6471772.115, 108.843999999997),
                new CoordinateZ(404869.14, 6471772.1, 108.830000000002),
                new CoordinateZ(404901.213, 6471769.834, 108.304000000018),
                new CoordinateZ(404910.739, 6471768.872, 108.131999999998),
                new CoordinateZ(404946.338, 6471765.28, 107.558000000019),
                new CoordinateZ(404975.086, 6471762.622, 107.116999999998),
                new CoordinateZ(404988.827, 6471761.632, 106.909),
                new CoordinateZ(405006.055, 6471760.454, 106.739000000016),
                new CoordinateZ(405014.995, 6471759.967, 106.701000000015),
                new CoordinateZ(405023.925, 6471759.909, 106.707000000009),
                new CoordinateZ(405036.662, 6471760.04, 106.755000000019),
                new CoordinateZ(405044.804, 6471760.663, 106.801000000021),
                new CoordinateZ(405054.064, 6471762.011, 106.864000000001),
                new CoordinateZ(405065.696, 6471765.191, 106.889999999999),
                new CoordinateZ(405074.274, 6471767.871, 106.885000000009),
                new CoordinateZ(405083.813, 6471771.568, 106.864000000001),
                new CoordinateZ(405096.038, 6471776.334, 106.837),
                new CoordinateZ(405106.617, 6471781.635, 106.884000000005),
                new CoordinateZ(405118.888, 6471787.111, 107.055999999997),
                new CoordinateZ(405129.981, 6471791.946, 107.317999999999),
                new CoordinateZ(405138.014, 6471795.089, 107.555999999997),
                new CoordinateZ(405146.024, 6471797.846, 108.165000000008),
                new CoordinateZ(405156.669, 6471801.315, 108.717000000033),
                new CoordinateZ(405162.439, 6471802.921, 108.905000000028),
                new CoordinateZ(405173.434, 6471805.332, 109.151000000027),
                new CoordinateZ(405182.863, 6471807.124, 109.29300000002),
                new CoordinateZ(405193.114, 6471807.968, 109.389999999999),
                new CoordinateZ(405199.57, 6471808.162, 109.418000000005),
                new CoordinateZ(405208.054, 6471808.07, 109.455000000016),
                new CoordinateZ(405218.548, 6471807.231, 109.498999999996),
                new CoordinateZ(405230.21, 6471804.613, 109.516000000018),
                new CoordinateZ(405247.744, 6471800.078, 109.555999999997),
                new CoordinateZ(405270.247, 6471794.156, 109.677000000011),
                new CoordinateZ(405290.459, 6471788.619, 109.775999999998),
                new CoordinateZ(405312.549, 6471782.554, 109.862000000008),
                new CoordinateZ(405333.078, 6471777.104, 110.082999999999),
                new CoordinateZ(405352.259, 6471772.052, 110.505000000019),
                new CoordinateZ(405376.555, 6471765.785, 110.932000000015),
                new CoordinateZ(405394.879, 6471760.736, 111.134000000005),
                new CoordinateZ(405408.007, 6471757.722, 111.225999999995),
                new CoordinateZ(405419.143, 6471754.867, 111.043999999994),
                new CoordinateZ(405426.504, 6471752.98, 110.864000000001),
                new CoordinateZ(405433.29, 6471751.502, 110.760999999999),
                new CoordinateZ(405440.937, 6471750.169, 110.66700000003),
                new CoordinateZ(405450.667, 6471748.827, 110.593000000023),
                new CoordinateZ(405457.744, 6471747.706, 109.881999999998),
                new CoordinateZ(405466.238, 6471747.146, 109.263000000021),
                new CoordinateZ(405479.163, 6471746.813, 109.058999999994),
                new CoordinateZ(405484.798, 6471747.37, 109.072),
                new CoordinateZ(405492.145, 6471748.097, 109.193000000014),
                new CoordinateZ(405506.915, 6471750.644, 109.894),
                new CoordinateZ(405517.918, 6471752.623, 110.432000000015),
                new CoordinateZ(405524.734, 6471754.088, 110.551000000021),
                new CoordinateZ(405537.049, 6471758.859, 111.246000000014),
                new CoordinateZ(405550.662, 6471764.231, 111.52800000002),
                new CoordinateZ(405557.071, 6471767.121, 111.591),
                new CoordinateZ(405564.819, 6471770.614, 111.693000000014),
                new CoordinateZ(405581.163, 6471778.507, 111.893000000011),
                new CoordinateZ(405587.978, 6471781.798, 111.906000000003),
                new CoordinateZ(405616.121, 6471794.269, 111.628000000012),
                new CoordinateZ(405653.686, 6471811.788, 111.955000000016),
                new CoordinateZ(405682.556, 6471825.184, 111.534),
                new CoordinateZ(405710.314, 6471837.575, 110.535000000018),
                new CoordinateZ(405751.313, 6471857.474, 111.078999999998),
                new CoordinateZ(405784.196, 6471872.651, 110.188000000009),
                new CoordinateZ(405833.614, 6471895.717, 110.558000000019),
                new CoordinateZ(405862.643, 6471909.973, 110.286999999997),
                new CoordinateZ(405889.271, 6471922.241, 109.948000000033),
                new CoordinateZ(405900.484723792, 6471927.2667716, 109.918001569153),
            };

            var feature1 = new LineString(cList1.ToArray());
            var feature2 = new LineString(cList2.ToArray());

            Assert.DoesNotThrow(() => feature1.Overlaps(feature2));
        }
Пример #37
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="lineString"></param>
 /// <returns></returns>
 protected virtual int SetByteStreamLength(LineString lineString)
 {
     int count = INIT_VALUE;
     count += lineString.NumPoints * COORD_SIZE;
     return count;
 }
Пример #38
0
        /// <summary>
        /// Method to create a NonSimple Closed Linestring for testing purposes
        /// </summary>
        /// <returns>A lineString</returns>
        private LineString NonSimpleClosed()
        {
            Coordinates coords = new Coordinates();
            Coordinate  coord  = new Coordinate(0, 0);

            coord = new Coordinate(2, 2);
            coords.Add(coord);
            coord = new Coordinate(3, 1);
            coords.Add(coord);
            coord = new Coordinate(4, 2);
            coords.Add(coord);
            coord = new Coordinate(5, 3);
            coords.Add(coord);
            coord = new Coordinate(6, 4);
            coords.Add(coord);
            coord = new Coordinate(7, 5);
            coords.Add(coord);
            coord = new Coordinate(7, 6);
            coords.Add(coord);
            coord = new Coordinate(7, 7);
            coords.Add(coord);
            coord = new Coordinate(7, 8);
            coords.Add(coord);
            coord = new Coordinate(7, 9);
            coords.Add(coord);
            coord = new Coordinate(6, 10);
            coords.Add(coord);
            coord = new Coordinate(5, 11);
            coords.Add(coord);
            coord = new Coordinate(6, 12);
            coords.Add(coord);
            coord = new Coordinate(7, 13);
            coords.Add(coord);
            coord = new Coordinate(8, 14);
            coords.Add(coord);
            coord = new Coordinate(9, 13);
            coords.Add(coord);
            coord = new Coordinate(10, 12);
            coords.Add(coord);
            coord = new Coordinate(10, 11);
            coords.Add(coord);
            coord = new Coordinate(10, 10);
            coords.Add(coord);
            coord = new Coordinate(10, 9);
            coords.Add(coord);
            coord = new Coordinate(9, 8);
            coords.Add(coord);
            coord = new Coordinate(8, 7);
            coords.Add(coord);
            coord = new Coordinate(7, 7);
            coords.Add(coord);
            coord = new Coordinate(6, 7);
            coords.Add(coord);
            coord = new Coordinate(5, 8);
            coords.Add(coord);
            coord = new Coordinate(4, 8);
            coords.Add(coord);
            coord = new Coordinate(3, 7);
            coords.Add(coord);
            coord = new Coordinate(2, 6);
            coords.Add(coord);
            coord = new Coordinate(1, 5);
            coords.Add(coord);
            coord = new Coordinate(2, 4);
            coords.Add(coord);
            coord = new Coordinate(1, 3);
            coords.Add(coord);
            coord = new Coordinate(2, 2);
            coords.Add(coord);

            GeometryFactory gf = new GeometryFactory(_precMod, _sRID);
            LineString      ls = gf.CreateLineString(coords);

            return(ls);
        }
Пример #39
0
        protected LineString ReadLineString(Dimension dimension)
        {
            ExpectGroupStart();
            LineString lineString = new LineString(MatchCoordinates(dimension));
            lineString.Dimension = dimension;
            ExpectGroupEnd();

            return lineString;
        }
Пример #40
0
        public void test_GeometryType()
        {
            LineString ls = SimpleOpen();

            Assertion.AssertEquals("GetType: ", "LineString", ls.GetGeometryType());
        }
Пример #41
0
            /// <summary>
            /// Generates a bounding rect around a lat/lon coordinate, to constrain queries.
            /// Anyway this is a spherical rectangle, not a real rectangle, so it's not an exact rectangle but a rather strange rect.
            /// To prevent problems with this approach, we're changing the "radius" to a real radius of the bounding circle, which will be almost exact
            /// </summary>
            /// <param name="latitude"></param>
            /// <param name="longitude"></param>
            /// <param name="distanceInKilometers">Kinda' like radius</param>
            /// <returns></returns>
            static public LineString RectForDistanceAroundLatLon(double latitude, double longitude, double distanceInKilometers)
            {
                // Get the circle that bounds the rect. This will give us a much more accurate rect
                distanceInKilometers = (Math.Sqrt(2.0 * (distanceInKilometers * 2.0) * (distanceInKilometers * 2.0)) / 2.0);

                LineString rect = new LineString();
                double distanceLat = distanceInKilometers / AVERAGE_KM_PER_LATITUDE_DEGREE;
                double distanceLon = distanceInKilometers / (AVERAGE_KM_PER_LATITUDE_DEGREE / Math.Cos(DEGREES_TO_RADIANS * latitude));

                // This is a real rect
                //rect.Points.Add(new Point(latitude + distanceLat, longitude + distanceLon));
                //rect.Points.Add(new Point(latitude - distanceLat, longitude + distanceLon));
                //rect.Points.Add(new Point(latitude - distanceLat, longitude - distanceLon));
                //rect.Points.Add(new Point(latitude + distanceLat, longitude - distanceLon));
                //rect.Points.Add(rect.Points[0]);

                // This is enough as the wkbs are calculating the bounds and retrieves a rectangle.
                rect.Points.Add(new Point(latitude + distanceLat, longitude + distanceLon));
                rect.Points.Add(new Point(latitude - distanceLat, longitude - distanceLon));
                return rect;
            }
Пример #42
0
        public void test_GetBoundary()
        {
            //try on a simple-open linestring
            LineString ls   = SimpleOpen();
            Geometry   geom = ls.GetBoundary();

            Assertion.AssertEquals("GetBoundary-1: ", false, geom.IsEmpty());

            Assertion.AssertEquals("GetBoundary-2: ", 2, geom.GetNumPoints());

            GeometryFactory gf = new GeometryFactory(_precMod, _sRID);
            MultiPoint      mp = gf.CreateMultiPoint(geom.GetCoordinates());

            for (int i = 0; i < mp.GetNumPoints(); i++)
            {
                switch (i)
                {
                case 0:
                    Assertion.AssertEquals("GetBoundary-3: ", 1.0, mp.GetCoordinate(i).X);
                    Assertion.AssertEquals("GetBoundary-4: ", 1.0, mp.GetCoordinate(i).Y);
                    break;

                case 1:
                    Assertion.AssertEquals("GetBoundary-5: ", 9.0, mp.GetCoordinate(i).X);
                    Assertion.AssertEquals("GetBoundary-6: ", 22.0, mp.GetCoordinate(i).Y);
                    break;

                default:
                    Assertion.Fail("This should never be reached");
                    break;
                }
            }

            //try on a simple-closed linestring
            ls   = SimpleClosed();
            geom = ls.GetBoundary();

            Assertion.AssertEquals("GetBoundary-7: ", true, geom.IsEmpty());

            Assertion.AssertEquals("GetBoundary-8: ", 0, geom.GetNumPoints());

            //try on a nonsimple-open linestring
            ls   = NonSimpleOpen();
            geom = ls.GetBoundary();

            Assertion.AssertEquals("GetBoundary-9: ", false, geom.IsEmpty());

            Assertion.AssertEquals("GetBoundary-10: ", 2, geom.GetNumPoints());

            mp = gf.CreateMultiPoint(geom.GetCoordinates());

            for (int i = 0; i < mp.GetNumPoints(); i++)
            {
                switch (i)
                {
                case 0:
                    Assertion.AssertEquals("GetBoundary-11: ", 2.0, mp.GetCoordinate(i).X);
                    Assertion.AssertEquals("GetBoundary-12: ", 2.0, mp.GetCoordinate(i).Y);
                    break;

                case 1:
                    Assertion.AssertEquals("GetBoundary-13: ", 3.0, mp.GetCoordinate(i).X);
                    Assertion.AssertEquals("GetBoundary-14: ", 9.0, mp.GetCoordinate(i).Y);
                    break;

                default:
                    Assertion.Fail("This should never be reached");
                    break;
                }
            }

            //try on a simple-closed linestring
            ls   = NonSimpleClosed();
            geom = ls.GetBoundary();

            Assertion.AssertEquals("GetBoundary-15: ", true, geom.IsEmpty());

            Assertion.AssertEquals("GetBoundary-16: ", 0, geom.GetNumPoints());
        }
Пример #43
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="reader"></param>
 /// <returns></returns>
 protected virtual IGeometry ReadMultiLineString(BinaryReader reader)
 {
     int numGeometries = reader.ReadInt32();
     LineString[] strings = new LineString[numGeometries];
     for (int i = 0; i < numGeometries; i++)
     {
         ReadByteOrder(reader);
         WkbGeometryType geometryType = (WkbGeometryType)reader.ReadInt32();
         if (geometryType != WkbGeometryType.LineString)
             throw new ArgumentException("LineString feature expected");
         strings[i] = ReadLineString(reader) as LineString;
     }
     return Factory.CreateMultiLineString(strings);
 }
Пример #44
0
 /// <summary>
 /// Converts a LineString to LineString tagged text format,
 /// </summary>
 /// <param name="lineString">The LineString to process.</param>
 /// <param name="writer">The output stream writer to Append to.</param>
 private static void AppendLineStringTaggedText(LineString lineString, StringWriter writer)
 {
     writer.Write("LINESTRING ");
     AppendLineStringText(lineString, writer);
 }
Пример #45
0
        private void WriteLineString(LineString ls, WKBByteOrder byteOrder, bool writeHeader)
        {
            if (writeHeader)
            {
                // Write byte order
                _writer.Write((byte)byteOrder);

                // Write type
                this.WriteType(ls, byteOrder);
            }

            // Write the number of points in this linestring.
            this.Write((uint)ls.getNumPoints(), byteOrder);

            // Loop on each set of coordinates.
            foreach (Coordinate coord in ls.getCoordinates())
            {
                // Create a new point from the coordinates & write it.
                WritePoint(_factory.createPoint(coord), byteOrder, false);
            }
        }
Пример #46
0
        /// <summary>
        /// 注释单行
        /// </summary>
        /// <param name="ls"></param>
        private bool SelectLine(LineString ls)
        {
            if (string.IsNullOrWhiteSpace(ls.Text))
            {
                return(false);
            }

            if (ls.IsFurl())
            {
                var width = this.PParser.GetLsWidth(ls);
                this.DeleteSeelctPuckerLineStringAndY = new List <PuckerLineStringAndID>();
                int indexY          = this.PParser.PCursor.CousorPointForWord.Y;
                var startIndexY     = indexY;
                int puckerLength    = 0;
                var arrayPuckerHide = this.GetHidePuckerID(ref indexY, ref puckerLength, ls, this.DeleteSeelctPuckerLineStringAndY);

                this.PuckerShowAndComment();
                this.CommentAllLine(startIndexY, indexY - startIndexY);
                if (this.PCommentStartWidth == -1)
                {
                    return(false);
                }

                #region 设置选择坐标
                var cpoint = new CPoint();
                cpoint.X               = this.PParser.GetLeftSpace;
                cpoint.Y               = startIndexY * FontContainer.FontHeight;
                cpoint.LineWidth       = width + this.PCommentStartWidth;
                cpoint.LineStringIndex = -1;
                this.PParser.SetBgStartPoint(cpoint);
                cpoint = new CPoint();
                var lastLs = arrayPuckerHide.Last();
                width                  = GetLsWidth(lastLs);
                cpoint.X               = this.PParser.GetLeftSpace + width;
                cpoint.Y               = indexY * FontContainer.FontHeight;
                cpoint.LineWidth       = width;
                cpoint.LineStringIndex = lastLs.Length - 1;
                this.PParser.SetBgEndPoint(cpoint);
                this.SetSelectBg();
                #endregion


                #region 赋值
                this.SetPuckerArrayID();
                #endregion
            }
            else
            {
                int leftIndex = 0;
                int lsWidth   = ls.Width;
                int wordIndex = InsertText(ls, ref leftIndex);
                if (wordIndex == -1)
                {
                    return(false);
                }
                if (wordIndex < this.minInsertWordIndex)
                {
                    this.minInsertWordIndex = wordIndex;
                    this.minInsertLineIndex = leftIndex;
                }
                this.CommentAllLine(this.PParser.PCursor.CousorPointForWord.Y, 1);

                var width = this.PCommentStartWidth;
                //var w = ls.PWord[wordIndex];
                //var width = CharCommand.GetCharWidth(this.PParser.PIEdit.GetGraphics, this.PCommentStartStr, w.PIncluedFont == null ? null : w.PIncluedFont.PFont);
                if (width > 0 && leftIndex < this.PParser.PCursor.CousorPointForWord.X)
                {
                    this.PParser.PCursor.CousorPointForWord.X += this.PCommentStartStr.Length;
                    this.PParser.PCursor.CousorPointForEdit.X += width;
                    //this.PCommentStartWidth = width;
                    //this.PParser.ClearSelect();
                    (this.PActionOperation as CommentAction).PCommentStartWidth = this.PCommentStartWidth;
                    lsWidth += width;
                    this.PParser.SetBgStartPoint(new CPoint(this.PParser.GetLeftSpace, this.PParser.PCursor.CousorPointForEdit.Y, lsWidth, -1));
                    this.PParser.SetBgEndPoint(new CPoint(this.PParser.GetLeftSpace + lsWidth, this.PParser.PCursor.CousorPointForEdit.Y, lsWidth, ls.Length - 1));
                }
            }

            return(true);
        }
Пример #47
0
        /// <summary>
        /// Generates the KML string.
        /// </summary>
        /// <param name="toolStripProgressBar">A windows Forms ToolStripProgressBar</param>
        /// <returns>The KML string.</returns>
        public string generateKML(ref System.Windows.Forms.ToolStripProgressBar toolStripProgressBar)
        {
            XNamespace gx = "http://www.google.com/kml/ext/2.2";
            XElement document = (XElement)(new Document().ToXNode());

            XDocument kml = new XDocument(
                new XComment("Created with excel2earth"),
                new XElement("kml",
                    new XAttribute(XNamespace.Xmlns + "kml", "http://www.opengis.net/kml/2.2"),
                    new XAttribute(XNamespace.Xmlns + "gx", "http://www.google.com/kml/ext/2.2"),
                    document
                )
            );

            int lastRow;

            if (this.range.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing).Row < this.range.Rows.Count)
            {
                lastRow = this.range.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing).Row;
            }
            else
            {
                lastRow = this.range.Rows.Count;
            }

            toolStripProgressBar.Minimum = this.range.Cells.Row + Convert.ToInt32(this.hasHeaders);
            toolStripProgressBar.Maximum = lastRow;
            toolStripProgressBar.Value = toolStripProgressBar.Minimum;
            toolStripProgressBar.Step = 1;

            foreach (StyleMap styleMap in this.styleSelection.Values.Where(StyleMap => StyleMap != null).Distinct())
            {
                if (!document.Descendants("StyleMap").Where(StyleMap => StyleMap.Attribute("id").Value == styleMap.id).Any())
                {
                    document.Add((XElement)styleMap.ToXNode());
                }
            }

            for (int row = 1 + Convert.ToInt32(this.hasHeaders); row <= lastRow; row++)
            {
                XElement parentNode = document;
                Placemark placemark = new Placemark(((Excel.Range)this.range.Cells[row, this.nameColumn]).Value2.ToString());
                string id = "";
                DecimalDegrees decimalDegrees;
                double altitude = 0.0;
                XElement[] childElements;
                XName childType = "Placemark";
                DateTime dateTime1;
                DateTime dateTime2;
                Geometry geometry = null;
                bool addElements = true;

                // XY Coordinates
                try
                {
                    switch (this.coordinatesFormat)
                    {
                        case 0: // Decimal Degrees
                            decimalDegrees = new DecimalDegrees(((Excel.Range)this.range.Cells[row, this.coordinatesField2Column]).Value2.ToString(), ((Excel.Range)this.range.Cells[row, this.coordinatesField1Column]).Value2.ToString());
                            break;
                        case 1: // Degrees, Decimal Minutes
                            decimalDegrees = new DegreesDecimalMinutes(((Excel.Range)this.range.Cells[row, this.coordinatesField2Column]).Value2.ToString(), ((Excel.Range)this.range.Cells[row, this.coordinatesField1Column]).Value2.ToString()).ToDecimalDegrees();
                            break;
                        case 2: // Degrees, Minutes, Seconds
                            decimalDegrees = new DegreesMinutesSeconds(((Excel.Range)this.range.Cells[row, this.coordinatesField2Column]).Value2.ToString(), ((Excel.Range)this.range.Cells[row, this.coordinatesField1Column]).Value2.ToString()).ToDecimalDegrees();
                            break;
                        case 3: // Military Grid Reference System
                            decimalDegrees = new MilitaryGridReferenceSystem(((Excel.Range)this.range.Cells[row, this.coordinatesField1Column]).Value2.ToString()).ToDecimalDegrees();
                            break;
                        //case 4: // Universal Transverse Mercator
                        //    throw new NotImplementedException();
                        //    break;
                        default:
                            decimalDegrees = new DecimalDegrees(0d, 0d);
                            break;
                    }
                }
                catch
                {
                    toolStripProgressBar.PerformStep();
                    continue;
                }

                // Z Coodinate
                if (this.hasAltitude)
                {
                    if (!double.TryParse(((Excel.Range)this.range.Cells[row, this.altitudeColumn]).Value2.ToString(), out altitude))
                    {
                        continue;
                    }

                    altitude *= altitudeUnitMultipliers[this.altitudeUnit];
                }

                Geometry.CoordinateSet coordinateSet = new Geometry.CoordinateSet(decimalDegrees.Latitude, decimalDegrees.Longitude, altitude);

                // Folders
                for (int i = 0; i < this.folderColumns.Length; i++)
                {
                    XElement[] folders = (from folder in parentNode.Descendants("Folder")
                                          where folder.Element("name").Value == ((Excel.Range)this.range.Cells[row, this.folderColumns[i]]).Value2.ToString()
                                          select folder).ToArray<XElement>();

                    if (folders.Length < 1) // If the folder doesn't exist, create it
                    {
                        parentNode.Add(new Folder(((Excel.Range)this.range.Cells[row, this.folderColumns[i]]).Value2.ToString()).ToXNode());
                        i--;
                    }
                    else // If the folder exists, use it
                    {
                        parentNode = folders[0];
                    }
                }

                // Snippet
                if (this.hasSnippet)
                {
                    placemark.snippet = ((Excel.Range)this.range.Cells[row, this.snippetColumn]).Value2.ToString();
                    placemark.snippetMaxLines = this.snippetMaxLines;
                }

                // Description
                if (this.descriptionColumns.Length > 0)
                {
                    XElement descriptionTable = new XElement("table");

                    for (int i = 0; i < this.descriptionColumns.Length; i++)
                    {
                        descriptionTable.Add
                        (
                            new XElement("tr",
                                new XAttribute("style", "background-color: #" + (i % 2 == 0 ? "FFFFFF" : "DDDDDD") + ";"),
                                new XElement("td",
                                    new XAttribute("style", "font-weight: bold;"),
                                    new XText(((Excel.Range)this.range.Cells[1, this.descriptionColumns[i]]).Value2.ToString())
                                ),
                                new XElement("td",
                                    new XText(((Excel.Range)this.range.Cells[row, this.descriptionColumns[i]]).Value2.ToString())
                                )
                            )
                        );
                    }

                    placemark.description = descriptionTable.ToString();
                }

                // Style
                if (this.iconColumn > 0)
                {
                    string styleKey = ((Excel.Range)this.range.Cells[row, this.iconColumn]).Value2.ToString();

                    if (this.styleSelection.ContainsKey(styleKey) && this.styleSelection[styleKey].id != null)
                    {
                        placemark.styleUrl = "#" + this.styleSelection[styleKey].id;
                    }
                }

                // Date/Time
                if (this.hasTimeStamp || this.hasTimeSpan)
                {
                    if (this.dateTimeFormat1 == 1)
                    {
                        DateTime.TryParse(((Excel.Range)this.range.Cells[row, this.dateTimeField1Column]).Value2.ToString() + " " + ((Excel.Range)this.range.Cells[row, this.dateTimeField2Column]).Value2.ToString(), out dateTime1);
                    }
                    else
                    {
                        DateTime.TryParse(((Excel.Range)this.range.Cells[row, this.dateTimeField1Column]).Value2.ToString(), new System.Globalization.CultureInfo("en-us", false).DateTimeFormat, System.Globalization.DateTimeStyles.AssumeUniversal, out dateTime1);
                    }

                    if (this.hasTimeStamp)
                    {
                        placemark.timePrimitive = new TimeStamp(dateTime1, dateTimeFormats[this.dateTimeFormat1]);
                    }

                    if (this.hasTimeSpan)
                    {
                        if (this.dateTimeFormat2 == 1)
                        {
                            DateTime.TryParse(((Excel.Range)this.range.Cells[row, this.dateTimeField3Column]).Value2.ToString() + " " + ((Excel.Range)this.range.Cells[row, this.dateTimeField4Column]).Value2.ToString(), out dateTime2);
                        }
                        else
                        {
                            DateTime.TryParse(((Excel.Range)this.range.Cells[row, this.dateTimeField3Column]).Value2.ToString(), out dateTime2);
                        }

                        placemark.timePrimitive = new excel2earth.kml.TimeSpan(dateTime1, dateTimeFormats[dateTimeFormat1], dateTime2, dateTimeFormats[dateTimeFormat2]);
                    }
                }

                // Model
                Orientation modelOrientation = null;
                Scale modelScale = null;
                Link modelLink = null;

                if (this.hasModel)
                {
                    // Orientation
                    if (this.modelHeadingColumn > 0 || this.modelTiltColumn > 0 || this.modelRollColumn > 0)
                    {
                        double modelHeading = 0.0;
                        double modelTilt = 0.0;
                        double modelRoll = 0.0;

                        if (this.modelHeadingColumn > 0)
                        {
                            double.TryParse(((Excel.Range)this.range.Cells[row, this.modelHeadingColumn]).Value2.ToString(), out modelHeading);
                        }

                        if (this.modelTiltColumn > 0)
                        {
                            double.TryParse(((Excel.Range)this.range.Cells[row, this.modelTiltColumn]).Value2.ToString(), out modelTilt);
                        }

                        if (this.modelRollColumn > 0)
                        {
                            double.TryParse(((Excel.Range)this.range.Cells[row, this.modelRollColumn]).Value2.ToString(), out modelRoll);
                        }

                        modelOrientation = new Orientation(modelHeading, modelTilt, modelRoll);
                    }

                    // Scale
                    if (this.modelXScaleColumn > 0 || this.modelYScaleColumn > 0 || this.modelZScaleColumn > 0)
                    {
                        double modelXScale = 1.0;
                        double modelYScale = 1.0;
                        double modelZScale = 1.0;

                        if (this.modelXScaleColumn > 0)
                        {
                            double.TryParse(((Excel.Range)this.range.Cells[row, this.modelXScaleColumn]).Value2.ToString(), out modelXScale);
                        }

                        if (this.modelYScaleColumn > 0)
                        {
                            double.TryParse(((Excel.Range)this.range.Cells[row, this.modelYScaleColumn]).Value2.ToString(), out modelYScale);
                        }

                        if (this.modelZScaleColumn > 0)
                        {
                            double.TryParse(((Excel.Range)this.range.Cells[row, this.modelZScaleColumn]).Value2.ToString(), out modelZScale);
                        }

                        modelScale = new Scale(modelXScale, modelYScale, modelZScale);
                    }

                    if (this.modelColumn > 0)
                    {
                        modelLink = new Link(((Excel.Range)this.range.Cells[row, this.modelColumn]).Value2.ToString());
                    }
                }

                // Geometry
                if (this.hasMultiGeometry)
                {
                    id = ((Excel.Range)this.range.Cells[row, this.multiGeometryColumn]).Value2.ToString();
                    childElements = (from children in parentNode.Descendants(childType)
                                     where children.Element("MultiGeometry").Attribute("id").Value == id
                                     select children).ToArray<XElement>();
                    childType = "MultiGeometry";

                    if (childElements.Length < 1) // If the Placemark doesn't exist, create it
                    {
                        placemark.geometry = new MultiGeometry(id);
                        parentNode.Add(placemark.ToXNode());
                        parentNode = (from elements in parentNode.Descendants("Placemark").Descendants(childType)
                                      where elements.Attribute("id").Value == id
                                      select elements).First();
                    }
                    else // If the Placemark exists, use it
                    {
                        parentNode = childElements.First();
                    }
                }

                #region MultiType
                switch (this.multiType)
                {
                    case 0: // None
                        break;
                    case 1: // Polygon
                        id = ((Excel.Range)this.range.Cells[row, this.multiTypeGroupColumn]).Value2.ToString();
                        childElements = (from children in parentNode.Descendants(childType).Descendants("Polygon")
                                         where children.Attribute("id").Value == id
                                         select children).ToArray<XElement>();
                        if (childElements.Length < 1) // If the Placemark doesn't exist, create it
                        {
                            Polygon polygon = new Polygon(id);

                            if (this.hasAltitude)
                            {
                                polygon.hasAltitude = true;
                                polygon.altitudeMode = this.altitudeModeIntToEnum[this.altitudeMode];
                                polygon.extrude = this.extrude;
                                polygon.tessellate = this.tesselllate;
                            }

                            if (childType == "Placemark")
                            {
                                XElement xPlacemark = (XElement)placemark.ToXNode();
                                parentNode.Add(xPlacemark);
                                parentNode = xPlacemark;
                            }

                            XElement xPolygon = (XElement)polygon.ToXNode();
                            parentNode.Add(xPolygon);
                            parentNode = xPolygon;
                        }
                        else // If the Placemark exists, use it
                        {
                            parentNode = childElements[0];
                            System.Windows.Forms.MessageBox.Show(parentNode.ToString());
                        }

                        childType = "Polygon";
                        break;
                    case 2: // MultiTrack
                        id = ((Excel.Range)this.range.Cells[row, this.multiTypeGroupColumn]).Value2.ToString();
                        childElements = (from children in parentNode.Descendants(childType).Descendants(gx + "MultiTrack")
                                         where children.Attribute("id").Value == id
                                         select children).ToArray<XElement>();

                        if (childElements.Length < 1) // If the Placemark doesn't exist, create it
                        {
                            MultiTrack multiTrack = new MultiTrack(id, this.trackInterpolate);

                            if (this.hasAltitude)
                            {
                                multiTrack.hasAltitude = true;
                                multiTrack.altitudeMode = this.altitudeModeIntToEnum[this.altitudeMode];
                            }

                            if (childType == "Placemark")
                            {
                                if (this.hasModel)
                                {
                                    placemark.styleUrl = null;
                                }

                                XElement xPlacemark = (XElement)placemark.ToXNode();
                                xPlacemark.Descendants("TimeStamp").Remove();
                                parentNode.Add(xPlacemark);
                                parentNode = xPlacemark;
                            }

                            XElement xMultiTrack = (XElement)multiTrack.ToXNode();
                            parentNode.Add(xMultiTrack);
                            parentNode = xMultiTrack;
                        }
                        else // If the placemark exists, use it
                        {
                            parentNode = childElements.First();
                        }

                        childType = gx + "MultiTrack";
                        break;
                }
                #endregion

                switch (this.dataType)
                {
                    case 0: // Point
                        geometry = new Point(new Geometry.Coordinates(coordinateSet));

                        if (this.hasAltitude)
                        {
                            ((Point)geometry).extrude = this.extrude;
                        }

                        break;
                    case 1: // Line String
                        id = ((Excel.Range)this.range.Cells[row, this.dataTypeGroupColumn]).Value2.ToString();
                        childElements = (from children in parentNode.Descendants(childType).Descendants("LineString")
                                         where children.Attribute("id").Value.ToString() == id
                                         select children).ToArray<XElement>();

                        if (childElements.Length < 1) // LineString does not exist
                        {
                            geometry = new LineString(id, new Geometry.Coordinates(coordinateSet));

                            if (this.hasAltitude)
                            {
                                ((LineString)geometry).extrude = this.extrude;
                                ((LineString)geometry).tessellate = this.tesselllate;
                            }
                        }
                        else // LineString exists, add coordinates
                        {
                            XElement coordinates = childElements[0].Element("coordinates");
                            coordinates.SetValue(coordinates.Value + " " + coordinateSet.getString());
                            updateDescriptionTable(ref this.range, ref row, ref document, (XElement)childElements[0].Parent);
                            addElements = false;
                        }

                        break;
                    case 2: // Linear Ring
                        id = ((Excel.Range)this.range.Cells[row, this.dataTypeGroupColumn]).Value2.ToString();

                        if (childType != "Polygon")
                        {
                            childElements = (from children in parentNode.Descendants(childType).Descendants("LinearRing")
                                             where children.Attribute("id").Value == id
                                             select children).ToArray<XElement>();
                        }
                        else
                        {
                            childElements = (from children in parentNode.Descendants().Descendants("LinearRing")
                                             where children.Attribute("id").Value == id
                                             select children).ToArray<XElement>();
                        }

                        if (childElements.Length < 1) // LinearRing does not exist
                        {
                            geometry = new LinearRing(id, new Geometry.Coordinates(coordinateSet));

                            if (this.hasAltitude && childType != "Polygon")
                            {
                                ((LinearRing)geometry).extrude = this.extrude;
                                ((LinearRing)geometry).tessellate = this.tesselllate;
                            }

                            if (childType == "Polygon")
                            {
                                if (!parentNode.Descendants("outerBoundaryIs").Any())
                                {
                                    parentNode.Add(new XElement("outerBoundaryIs", geometry.ToXNode()));
                                }
                                else
                                {
                                    parentNode.Add(new XElement("innerBoundaryIs", geometry.ToXNode()));
                                    updateDescriptionTable(ref this.range, ref row, ref document, parentNode.Parent);
                                }

                                addElements = false;
                            }
                        }
                        else // LinearRing exists, add coordinates
                        {
                            XElement coordinates = childElements[0].Element("coordinates");
                            coordinates.SetValue(coordinates.Value + " " + coordinateSet.getString());
                            updateDescriptionTable(ref this.range, ref row, ref document, childElements[0].Parent);
                            addElements = false;
                        }
                        break;
                    case 3: // Model
                        geometry = new Model(new Location(coordinateSet), modelOrientation, modelScale, modelLink);
                        break;
                    case 4: // Track
                        Orientation trackOrientation = null;
                        if (this.trackHeadingColumn > 0 || this.trackTiltColumn > 0 || this.trackRollColumn > 0)
                        {
                            double trackHeading = 0.0;
                            double trackTilt = 0.0;
                            double trackRoll = 0.0;

                            if (this.trackHeadingColumn > 0)
                            {
                                double.TryParse(((Excel.Range)this.range.Cells[row, this.trackHeadingColumn]).Value2.ToString(), out trackHeading);
                            }

                            if (this.trackTiltColumn > 0)
                            {
                                double.TryParse(((Excel.Range)this.range.Cells[row, this.trackTiltColumn]).Value2.ToString(), out trackTilt);
                            }

                            if (this.trackRollColumn > 0)
                            {
                                double.TryParse(((Excel.Range)this.range.Cells[row, this.trackRollColumn]).Value2.ToString(), out trackRoll);
                            }

                            trackOrientation = new Orientation(trackHeading, trackTilt, trackRoll);
                        }

                        id = ((Excel.Range)this.range.Cells[row, this.dataTypeGroupColumn]).Value2.ToString();

                        if (childType != gx + "MultiTrack")
                        {
                            childElements = (from children in parentNode.Descendants(childType).Descendants(gx + "Track")
                                             where children.Attribute("id").Value == id
                                             select children).ToArray<XElement>();
                        }
                        else
                        {
                            childElements = (from children in parentNode.Descendants(gx + "Track")
                                             where children.Attribute("id").Value == id
                                             select children).ToArray<XElement>();
                        }
                        if (childElements.Length < 1) // If the placemark doesn't exist, create it
                        {
                            geometry = new Track(id, new Geometry.Coordinates(coordinateSet));

                            if (this.hasTimeStamp)
                            {
                                ((Track)geometry).whens = new TimeStamp[] { (TimeStamp)placemark.timePrimitive };
                            }

                            if (trackOrientation != null)
                            {
                                ((Track)geometry).angles = new Orientation[] { trackOrientation };
                            }

                            if (this.hasModel)
                            {
                                ((Track)geometry).model = new Model(modelOrientation, modelScale, modelLink);
                            }

                            if (childType == gx + "MultiTrack" && parentNode.Descendants(gx + "Track").Any())
                            {
                                updateDescriptionTable(ref this.range, ref row, ref document, parentNode.Parent);
                            }
                        }
                        else
                        {
                            XElement track = childElements[0];

                            if (this.hasTimeStamp)
                            {
                                (from whens in track.Descendants("when") select whens).Last().AddAfterSelf(((XElement)placemark.timePrimitive.ToXNode()).Descendants("when"));
                            }

                            (from coords in track.Descendants(gx + "coord") select coords).Last().AddAfterSelf(new XElement(gx + "coord", coordinateSet.getString().Replace(',', ' ')));

                            if (trackOrientation != null)
                            {
                                (from angles in track.Descendants(gx + "angles") select angles).Last().AddAfterSelf(new XElement(gx + "angles", trackOrientation.getString()));
                            }

                            updateDescriptionTable(ref this.range, ref row, ref document, childElements[0].Parent);
                            addElements = false;
                        }
                        break;
                }

                if (addElements)
                {
                    if (this.hasAltitude && this.multiType != 1)
                    {
                        geometry.hasAltitude = true;
                        geometry.altitudeMode = this.altitudeModeIntToEnum[this.altitudeMode];
                    }

                    if (childType == "Placemark")
                    {
                        if (this.dataType == 4)
                        {
                            placemark.timePrimitive = null;
                        }

                        placemark.geometry = geometry;
                        parentNode.Add(placemark.ToXNode());
                    }
                    else
                    {
                        parentNode.Add(geometry.ToXNode());
                    }
                }
                toolStripProgressBar.PerformStep();
            }

            return kml.ToString();
        }
Пример #48
0
        /// <summary>
        /// Reads and parses the geometry with ID 'oid' from the ShapeFile
        /// </summary>
        /// <remarks><see cref="FilterDelegate">Filtering</see> is not applied to this method</remarks>
        /// <param name="oid">Object ID</param>
        /// <returns>geometry</returns>
        // ReSharper disable once CyclomaticComplexity // Fix when changes need to be made here
        private Geometry ReadGeometry(uint oid)
        {
            _brShapeFile.BaseStream.Seek(GetShapeIndex(oid) + 8, 0); //Skip record number and content length
            var type = (ShapeType)_brShapeFile.ReadInt32();          //Shape type

            if (type == ShapeType.Null)
            {
                return(null);
            }
            if (_shapeType == ShapeType.Point || _shapeType == ShapeType.PointM || _shapeType == ShapeType.PointZ)
            {
                return(new Point(_brShapeFile.ReadDouble(), _brShapeFile.ReadDouble()));
            }
            if (_shapeType == ShapeType.Multipoint || _shapeType == ShapeType.MultiPointM ||
                _shapeType == ShapeType.MultiPointZ)
            {
                _brShapeFile.BaseStream.Seek(32 + _brShapeFile.BaseStream.Position, 0); //skip min/max box
                var feature = new MultiPoint();
                int nPoints = _brShapeFile.ReadInt32();                                 // get the number of points
                if (nPoints == 0)
                {
                    return(null);
                }
                for (int i = 0; i < nPoints; i++)
                {
                    feature.Points.Add(new Point(_brShapeFile.ReadDouble(), _brShapeFile.ReadDouble()));
                }

                return(feature);
            }
            if (_shapeType == ShapeType.PolyLine || _shapeType == ShapeType.Polygon ||
                _shapeType == ShapeType.PolyLineM || _shapeType == ShapeType.PolygonM ||
                _shapeType == ShapeType.PolyLineZ || _shapeType == ShapeType.PolygonZ)
            {
                _brShapeFile.BaseStream.Seek(32 + _brShapeFile.BaseStream.Position, 0); //skip min/max box

                int nParts = _brShapeFile.ReadInt32();                                  // get number of parts (segments)
                if (nParts == 0)
                {
                    return(null);
                }
                int nPoints = _brShapeFile.ReadInt32(); // get number of points

                var segments = new int[nParts + 1];
                //Read in the segment indexes
                for (int b = 0; b < nParts; b++)
                {
                    segments[b] = _brShapeFile.ReadInt32();
                }
                //add end point
                segments[nParts] = nPoints;

                if ((int)_shapeType % 10 == 3)
                {
                    var mline = new MultiLineString();
                    for (int lineId = 0; lineId < nParts; lineId++)
                    {
                        var line = new LineString();
                        for (int i = segments[lineId]; i < segments[lineId + 1]; i++)
                        {
                            line.Vertices.Add(new Point(_brShapeFile.ReadDouble(), _brShapeFile.ReadDouble()));
                        }
                        mline.LineStrings.Add(line);
                    }
                    if (mline.LineStrings.Count == 1)
                    {
                        return(mline[0]);
                    }
                    return(mline);
                }
                else //(_ShapeType == ShapeType.Polygon etc...)
                {
                    //First read all the rings
                    var rings = new List <LinearRing>();
                    for (int ringId = 0; ringId < nParts; ringId++)
                    {
                        var ring = new LinearRing();
                        for (int i = segments[ringId]; i < segments[ringId + 1]; i++)
                        {
                            ring.Vertices.Add(new Point(_brShapeFile.ReadDouble(), _brShapeFile.ReadDouble()));
                        }
                        rings.Add(ring);
                    }
                    var isCounterClockWise = new bool[rings.Count];
                    int polygonCount       = 0;
                    for (int i = 0; i < rings.Count; i++)
                    {
                        isCounterClockWise[i] = rings[i].IsCCW();
                        if (!isCounterClockWise[i])
                        {
                            polygonCount++;
                        }
                    }
                    if (polygonCount == 1) //We only have one polygon
                    {
                        var poly = new Polygon {
                            ExteriorRing = rings[0]
                        };
                        if (rings.Count > 1)
                        {
                            for (int i = 1; i < rings.Count; i++)
                            {
                                poly.InteriorRings.Add(rings[i]);
                            }
                        }
                        return(poly);
                    }
                    else
                    {
                        var mpoly = new MultiPolygon();
                        var poly  = new Polygon {
                            ExteriorRing = rings[0]
                        };
                        for (var i = 1; i < rings.Count; i++)
                        {
                            if (!isCounterClockWise[i])
                            {
                                mpoly.Polygons.Add(poly);
                                poly = new Polygon(rings[i]);
                            }
                            else
                            {
                                poly.InteriorRings.Add(rings[i]);
                            }
                        }
                        mpoly.Polygons.Add(poly);
                        return(mpoly);
                    }
                }
            }

            throw (new ApplicationException("Shapefile type " + _shapeType.ToString() + " not supported"));
        }
Пример #49
0
 /// <summary>
 /// Converts a LineString to LineString tagged text format, 
 /// </summary>
 /// <param name="lineString">The LineString to process.</param>
 /// <param name="level"></param>
 /// <param name="writer">The output stream writer to Append to.</param>
 protected void AppendLineStringTaggedText(LineString lineString, int level, StringWriter writer)
 {
     writer.Write("LINESTRING ");
     AppendLineStringText(lineString, level, false, writer);
 }
Пример #50
0
 private static void WriteLineString(LineString lineString, TextWriter writer, bool includeAltitude)
 {
     writer.Write("LINESTRING");
     WriteLocations(lineString.Vertices, writer, includeAltitude);
 }
Пример #51
0
        /// <summary>
        ///     Writes a linestring.
        /// </summary>
        /// <param name="ls">The linestring to be written.</param>
        /// <param name="bWriter">Stream to write to.</param>
        /// <param name="byteorder">Byte order</param>
        private static void WriteLineString(LineString ls, BinaryWriter bWriter, WkbByteOrder byteorder)
        {
            //Write the number of points in this linestring.
            WriteUInt32((uint) ls.Vertices.Count, bWriter, byteorder);

            //Loop on each vertices.
            foreach (var p in ls.Vertices)
            {
                WritePoint(p, bWriter, byteorder);
            }
        }
Пример #52
0
        private bool WritePostGIS(LineString lineString)
        {
            WritePostGIS(lineString.Coordinates);

            return(true);
        }
Пример #53
0
        public static void Write(LineString line, TextWriter writer)
        {
            if (line == null)
                return;
            if (writer == null)
                throw new ArgumentNullException("writer", "A valid text writer object is required");

            Write(line, CreateWriter(writer));
        }
Пример #54
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="lineString"></param>
        /// <returns></returns>
        public MultiLineString ClipLineString(LineString lineString)
        {
            //List of line strings that make up the multi line string result
            var lineStrings = new List <LineString>();

            //list of clipped vertices for current pass
            var clippedVertices = new List <Point>();

            //vertices of current line string
            var vertices = lineString.Vertices;
            var count    = vertices.Count;

            //Compute starting clipcode
            double           x0, y0;
            OutsideClipCodes oc0Initial;
            var oc0 = oc0Initial = ComputeClipCode(vertices[0], out x0, out y0);

            //Point is inside => add it to the list
            if (oc0 == OutsideClipCodes.Inside)
            {
                clippedVertices.Add(vertices[0]);
            }

            double x1old = double.NaN, y1old = double.NaN;

            for (var i = 1; i < count; i++)
            {
                double           x1, y1;
                OutsideClipCodes oc1Initial;
                var oc1    = oc1Initial = ComputeClipCode(vertices[i], out x1, out y1);
                var x1Orig = x1;
                var y1Orig = y1;

                var accept = false;

                while (true)
                {
                    if ((oc0 | oc1) == OutsideClipCodes.Inside)
                    {
                        // Bitwise OR is 0. Trivially accept and get out of loop
                        accept = true;
                        break;
                    }

                    if ((oc0 & oc1) != OutsideClipCodes.Inside)
                    {
                        // Bitwise AND is not 0. Trivially reject and get out of loop
                        break;
                    }

                    // failed both tests, so calculate the line segment to clip
                    // from an outside point to an intersection with clip edge
                    double x = double.NaN, y = double.NaN;

                    // At least one endpoint is outside the clip rectangle; pick it.
                    var ocOut = oc0 != OutsideClipCodes.Inside ? oc0 : oc1;

                    // Now find the intersection point;
                    // use formulas y = y0 + slope * (x - x0), x = x0 + (1 / slope) * (y - y0)
                    if ((ocOut & OutsideClipCodes.Top) == OutsideClipCodes.Top)
                    {
                        // point is above the clip rectangle
                        x = x0 + (x1 - x0) * (_ymax - y0) / (y1 - y0);
                        y = _ymax;
                    }
                    else if ((ocOut & OutsideClipCodes.Bottom) == OutsideClipCodes.Bottom)
                    {
                        // point is below the clip rectangle
                        x = x0 + (x1 - x0) * (_ymin - y0) / (y1 - y0);
                        y = _ymin;
                    }
                    else if ((ocOut & OutsideClipCodes.Right) == OutsideClipCodes.Right)
                    {
                        // point is to the right of clip rectangle
                        y = y0 + (y1 - y0) * (_xmax - x0) / (x1 - x0);
                        x = _xmax;
                    }
                    else if ((ocOut & OutsideClipCodes.Left) == OutsideClipCodes.Left)
                    {
                        // point is to the left of clip rectangle
                        y = y0 + (y1 - y0) * (_xmin - x0) / (x1 - x0);
                        x = _xmin;
                    }
                    // Now we move outside point to intersection point to clip
                    // and get ready for next pass.
                    if (oc0 == ocOut)
                    {
                        x0  = x;
                        y0  = y;
                        oc0 = ComputeClipCode(x, y);
                    }
                    else
                    {
                        x1  = x;
                        y1  = y;
                        oc1 = ComputeClipCode(x, y);
                    }
                }

                if (accept)
                {
                    if (oc0Initial != oc0)
                    {
                        clippedVertices.Add(new Point(x0, y0));
                    }

                    if (x1old != x1 || y1old != y1)
                    {
                        clippedVertices.Add(new Point(x1, y1));
                    }

                    if (oc1Initial != OutsideClipCodes.Inside)
                    {
                        if (clippedVertices.Count > 0)
                        {
                            lineStrings.Add(new LineString(clippedVertices));
                            clippedVertices = new List <Point>();
                        }
                    }
                }
                x0  = x1old = x1Orig;
                y0  = y1old = y1Orig;
                oc0 = oc0Initial = oc1Initial;
            }

            if (clippedVertices.Count > 0)
            {
                lineStrings.Add(new LineString(clippedVertices));
            }

            return(new MultiLineString {
                LineStrings = lineStrings
            });
        }
Пример #55
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="parentLine"></param>
 /// <param name="minimumSize"></param>
 public TaggedLineString(LineString parentLine, int minimumSize)
 {
     _parentLine = parentLine;
     _minimumSize = minimumSize;
     Init();
 }
Пример #56
0
        private void writeKML(string filename)
        {
            try
            {
                writeGPX(filename);
            }
            catch { }

            Color[] colours = { Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Blue, Color.Indigo, Color.Violet, Color.Pink };

            AltitudeMode altmode = AltitudeMode.absolute;

            if (MainV2.comPort.MAV.cs.firmware == MainV2.Firmwares.ArduCopter2)
            {
                altmode = AltitudeMode.relativeToGround; // because of sonar, this is both right and wrong. right for sonar, wrong in terms of gps as the land slopes off.
            }

            KMLRoot kml  = new KMLRoot();
            Folder  fldr = new Folder("Log");

            Style style = new Style();

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

            PolyStyle pstyle = new PolyStyle();

            pstyle.Color = HexStringToColor("7f00ff00");
            style.Add(pstyle);

            kml.Document.AddStyle(style);

            int stylecode = 0xff;
            int g         = -1;

            foreach (List <Point3D> poslist in position)
            {
                g++;
                if (poslist == null)
                {
                    continue;
                }

                LineString ls = new LineString();
                ls.AltitudeMode = altmode;
                ls.Extrude      = true;
                //ls.Tessellate = true;

                Coordinates coords = new Coordinates();
                coords.AddRange(poslist);

                ls.coordinates = coords;

                Placemark pm = new Placemark();

                string mode = "";
                if (g < modelist.Count)
                {
                    mode = modelist[g];
                }

                pm.name       = g + " Flight Path " + mode;
                pm.styleUrl   = "#yellowLineGreenPoly";
                pm.LineString = ls;

                stylecode = colours[g % (colours.Length - 1)].ToArgb();

                Style style2 = new Style();
                Color color  = Color.FromArgb(0xff, (stylecode >> 16) & 0xff, (stylecode >> 8) & 0xff, (stylecode >> 0) & 0xff);
                log.Info("colour " + color.ToArgb().ToString("X") + " " + color.ToKnownColor().ToString());
                style2.Add(new LineStyle(color, 4));



                pm.AddStyle(style2);

                fldr.Add(pm);
            }

            Folder planes = new Folder();

            planes.name = "Planes";
            fldr.Add(planes);

            Folder waypoints = new Folder();

            waypoints.name = "Waypoints";
            fldr.Add(waypoints);


            LineString lswp = new LineString();

            lswp.AltitudeMode = AltitudeMode.relativeToGround;
            lswp.Extrude      = true;

            Coordinates coordswp = new Coordinates();

            foreach (PointLatLngAlt p1 in cmd)
            {
                coordswp.Add(new Point3D(p1.Lng, p1.Lat, p1.Alt));
            }

            lswp.coordinates = coordswp;

            Placemark pmwp = new Placemark();

            pmwp.name = "Waypoints";
            //pm.styleUrl = "#yellowLineGreenPoly";
            pmwp.LineString = lswp;

            waypoints.Add(pmwp);

            int a = 0;
            int l = -1;

            Model lastmodel = null;

            foreach (Data mod in flightdata)
            {
                l++;
                if (mod.model.Location.latitude == 0)
                {
                    continue;
                }

                if (lastmodel != null)
                {
                    if (lastmodel.Location.Equals(mod.model.Location))
                    {
                        continue;
                    }
                }
                Placemark pmplane = new Placemark();
                pmplane.name = "Plane " + a;

                pmplane.visibility = false;

                Model model = mod.model;
                model.AltitudeMode = altmode;
                model.Scale.x      = 2;
                model.Scale.y      = 2;
                model.Scale.z      = 2;

                try
                {
                    pmplane.description = @"<![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>
                <tr><td>WP dist " + mod.ntun[2] + @" </td></tr>
				<tr><td>tar bear "                 + mod.ntun[3] + @" </td></tr>
				<tr><td>nav bear "                 + mod.ntun[4] + @" </td></tr>
				<tr><td>alt error "                 + mod.ntun[5] + @" </td></tr>
              </table>
            ]]>";
                }
                catch { }

                try
                {
                    pmplane.Point = new KmlPoint((float)model.Location.longitude, (float)model.Location.latitude, (float)model.Location.altitude);
                    pmplane.Point.AltitudeMode = altmode;

                    Link link = new Link();
                    link.href = "block_plane_0.dae";

                    model.Link = link;

                    pmplane.Model = model;

                    planes.Add(pmplane);
                }
                catch { } // bad lat long value

                lastmodel = mod.model;

                a++;
            }

            kml.Document.Add(fldr);

            kml.Save(filename);

            // create kmz - aka zip file

            FileStream      fs        = File.Open(filename.Replace(".log.kml", ".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.OpenRead(filename))
            {
                StreamUtils.Copy(streamReader, zipStream, buffer);
            }
            zipStream.CloseEntry();

            File.Delete(filename);

            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();

            positionindex = 0;
            modelist.Clear();
            flightdata.Clear();
            position = new List <Core.Geometry.Point3D> [200];
            cmd.Clear();
        }
Пример #57
0
 private void WriteLineString(LineString lineString)
 {
     wktBuilder.Append("(");
     WriteWktCoordinates(lineString.Points);
     wktBuilder.Append(")");
 }
Пример #58
0
        public void writeKML(string filename)
        {
            try
            {
                writeGPX(filename);

                writeRinex(filename);
            }
            catch { }

            Color[] colours = { Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Blue, Color.Indigo, Color.Violet, Color.Pink };

            AltitudeMode altmode = AltitudeMode.absolute;

            KMLRoot kml  = new KMLRoot();
            Folder  fldr = new Folder("Log");

            Style style = new Style();

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

            Style style1 = new Style();

            style1.Id = "spray";
            style1.Add(new LineStyle(HexStringToColor("4c0000ff"), 0));
            style1.Add(new PolyStyle()
            {
                Color = HexStringToColor("4c0000ff")
            });

            PolyStyle pstyle = new PolyStyle();

            pstyle.Color = HexStringToColor("7f00ff00");
            style.Add(pstyle);

            kml.Document.AddStyle(style);
            kml.Document.AddStyle(style1);

            int stylecode = 0xff;
            int g         = -1;

            foreach (List <Point3D> poslist in position)
            {
                g++;
                if (poslist == null)
                {
                    continue;
                }

                /*
                 * List<PointLatLngAlt> pllalist = new List<PointLatLngAlt>();
                 *
                 * foreach (var point in poslist)
                 * {
                 *  pllalist.Add(new PointLatLngAlt(point.Y, point.X, point.Z, ""));
                 * }
                 *
                 * var ans = Utilities.LineOffset.GetPolygon(pllalist, 2);
                 *
                 *
                 *
                 * while (ans.Count > 0)
                 * {
                 *  var first = ans[0];
                 *  var second = ans[1];
                 *  var secondlast = ans[ans.Count - 2];
                 *  var last = ans[ans.Count-1];
                 *
                 *  ans.Remove(first);
                 *  ans.Remove(last);
                 *
                 *  var polycoords = new BoundaryIs();
                 *
                 *  polycoords.LinearRing = new LinearRing();
                 *
                 *  polycoords.LinearRing.Coordinates.Add(new Point3D(first.Lng, first.Lat, 1));
                 *  polycoords.LinearRing.Coordinates.Add(new Point3D(second.Lng, second.Lat, 1));
                 *  polycoords.LinearRing.Coordinates.Add(new Point3D(secondlast.Lng, secondlast.Lat, 1));
                 *  polycoords.LinearRing.Coordinates.Add(new Point3D(last.Lng, last.Lat, 1));
                 *  polycoords.LinearRing.Coordinates.Add(new Point3D(first.Lng, first.Lat, 1));
                 *
                 *  //if (!IsClockwise(polycoords.LinearRing.Coordinates))
                 *    //  polycoords.LinearRing.Coordinates.Reverse();
                 *
                 *  Polygon kmlpoly = new Polygon() { AltitudeMode = AltitudeMode.relativeToGround, Extrude = false, OuterBoundaryIs = polycoords };
                 *
                 *  Placemark pmpoly = new Placemark();
                 *  pmpoly.Polygon = kmlpoly;
                 *  pmpoly.name = g + " test";
                 *  pmpoly.styleUrl = "#spray";
                 *
                 *  fldr.Add(pmpoly);
                 * }
                 */
                LineString ls = new LineString();
                ls.AltitudeMode = altmode;
                ls.Extrude      = true;
                //ls.Tessellate = true;

                Coordinates coords = new Coordinates();
                coords.AddRange(poslist);

                ls.coordinates = coords;

                Placemark pm = new Placemark();

                string mode = "";
                if (g < modelist.Count)
                {
                    mode = modelist[g];
                }

                pm.name       = g + " Flight Path " + mode;
                pm.styleUrl   = "#yellowLineGreenPoly";
                pm.LineString = ls;

                stylecode = colours[g % (colours.Length - 1)].ToArgb();

                Style style2 = new Style();
                Color color  = Color.FromArgb(0xff, (stylecode >> 16) & 0xff, (stylecode >> 8) & 0xff, (stylecode >> 0) & 0xff);
                log.Info("colour " + color.ToArgb().ToString("X") + " " + color.ToKnownColor().ToString());
                style2.Add(new LineStyle(color, 4));



                pm.AddStyle(style2);

                fldr.Add(pm);
            }

            Placemark pmPOS = new Placemark();

            pmPOS.name                   = "POS Message";
            pmPOS.LineString             = new LineString();
            pmPOS.LineString.coordinates = new Coordinates();
            Point3D        lastPoint3D = new Point3D();
            PointLatLngAlt lastplla    = PointLatLngAlt.Zero;

            foreach (var item in PosLatLngAlts)
            {
                var newpoint = new Point3D(item.Lng, item.Lat, item.Alt);

                if (item.GetDistance(lastplla) < 0.1 &&
                    lastPoint3D.Z >= (newpoint.Z - 0.3) &&
                    lastPoint3D.Z <= (newpoint.Z + 0.3))
                {
                    continue;
                }

                pmPOS.LineString.coordinates.Add(newpoint);
                lastPoint3D = newpoint;
                lastplla    = item;
            }
            pmPOS.AddStyle(style);
            fldr.Add(pmPOS);

            Folder planes = new Folder();

            planes.name = "Planes";
            fldr.Add(planes);

            Folder waypoints = new Folder();

            waypoints.name = "Waypoints";
            fldr.Add(waypoints);


            LineString lswp = new LineString();

            lswp.AltitudeMode = AltitudeMode.relativeToGround;
            lswp.Extrude      = true;

            Coordinates coordswp = new Coordinates();

            foreach (PointLatLngAlt p1 in cmd)
            {
                coordswp.Add(new Point3D(p1.Lng, p1.Lat, p1.Alt));
            }

            lswp.coordinates = coordswp;

            Placemark pmwp = new Placemark();

            pmwp.name = "Waypoints";
            //pm.styleUrl = "#yellowLineGreenPoly";
            pmwp.LineString = lswp;

            waypoints.Add(pmwp);

            int a = 0;
            int l = -1;

            Model lastmodel = null;

            foreach (Data mod in flightdata)
            {
                l++;
                if (mod.model.Location.latitude == 0)
                {
                    continue;
                }

                if (lastmodel != null)
                {
                    if (lastmodel.Location.Equals(mod.model.Location))
                    {
                        continue;
                    }
                }
                Placemark pmplane = new Placemark();
                pmplane.name = "Plane " + a;

                pmplane.visibility = false;

                Model model = mod.model;
                model.AltitudeMode = altmode;
                model.Scale.x      = 2;
                model.Scale.y      = 2;
                model.Scale.z      = 2;

                try
                {
                    pmplane.description = @"<![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>
                <tr><td>WP dist " + mod.ntun[2] + @" </td></tr>
				<tr><td>tar bear "                 + mod.ntun[3] + @" </td></tr>
				<tr><td>nav bear "                 + mod.ntun[4] + @" </td></tr>
				<tr><td>alt error "                 + mod.ntun[5] + @" </td></tr>
              </table>
            ]]>";
                }
                catch { }

                try
                {
                    pmplane.Point = new KmlPoint((float)model.Location.longitude, (float)model.Location.latitude, (float)model.Location.altitude);
                    pmplane.Point.AltitudeMode = altmode;

                    Link link = new Link();
                    link.href = "block_plane_0.dae";

                    model.Link = link;

                    pmplane.Model = model;

                    planes.Add(pmplane);
                }
                catch { } // bad lat long value

                lastmodel = mod.model;

                a++;
            }

            kml.Document.Add(fldr);

            kml.Save(filename);

            // create kmz - aka zip file

            FileStream      fs        = File.Open(filename.ToLower().Replace(".log.kml", ".kmz").Replace(".bin.kml", ".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.OpenRead(filename))
            {
                StreamUtils.Copy(streamReader, zipStream, buffer);
            }
            zipStream.CloseEntry();

            File.Delete(filename);

            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();

            positionindex = 0;
            modelist.Clear();
            flightdata.Clear();
            position = new List <Core.Geometry.Point3D> [200];
            cmd.Clear();
        }
Пример #59
0
 public void LineEndPoint()
 {
     var coords = new Coordinate[36];
     var rnd = new Random();
     var coordscheck = new GeoAPI.Geometries.Coordinate[36];
     for (var i = 0; i < 36; i++)
     {
         coords[i] = new Coordinate((rnd.NextDouble() * 360) - 180, (rnd.NextDouble() * 180) - 90);
         var x = coords[i].X;
         var y = coords[i].Y;
         var c = new GeoAPI.Geometries.Coordinate(x, y);
         coordscheck[i] = c;
     }
     var gf = new NetTopologySuite.Geometries.GeometryFactory();
     var lscheck = gf.CreateLineString(coordscheck);
     var ls = new LineString(coords);
     AssertExt.AreEqual15(ls.EndPoint.X, lscheck.EndPoint.X);
     AssertExt.AreEqual15(ls.EndPoint.Y, lscheck.EndPoint.Y);
 }
Пример #60
0
        public static void Main(string[] args)
        {
            {
                #region Snippet_0a
                IStringFormat stringFormat = CSharpFormat.Default;
                IString       str          = stringFormat.Parse("Hello, {0}.");
                #endregion Snippet_0a
            }
            {
                #region Snippet_0b
                ILine line = LineRoot.Global.Key("").Format("Hello, {0}.");
                #endregion Snippet_0b
            }
            {
                #region Snippet_1a
                IStringFormat stringFormat = TextFormat.Default;
                IString       str          = stringFormat.Parse("{in braces}");
                #endregion Snippet_1a
            }
            {
                #region Snippet_1b
                ILine line = LineRoot.Global.Key("").Text("{in braces}");
                #endregion Snippet_1b
            }

            {
                #region Snippet_2a
                IStringFormat stringFormat = CSharpFormat.Default;
                IString       str          = stringFormat.Parse("Hello, {0}.");
                #endregion Snippet_2a
                #region Snippet_2b
                ILine line = LineRoot.Global.Key("Hello").String(str);
                #endregion Snippet_2b
                #region Snippet_2c
                LineString lineString = line.Value("Corellia Melody").ResolveString();
                #endregion Snippet_2c
                #region Snippet_2d
                if (!lineString.Failed)
                {
                    Console.WriteLine(lineString.Value);
                }
                #endregion Snippet_2d
            }
            {
                #region Snippet_3
                // Convert unescaped string "{not placeholder}" to IString
                IString ss = TextFormat.Default.Parse("{not placeholder}");
                // Escape with CSharpFormat to "\{not placeholder\}"
                string str = CSharpFormat.Default.Print(ss);
                // Convert escaped string back to IString
                IString cs = CSharpFormat.Default.Parse(str);
                // Unescape IString back to "{not placeholder}"
                string tt = TextFormat.Default.Print(cs);
                #endregion Snippet_3
                Console.WriteLine(tt);
            }
            {
                #region Snippet_4
                #endregion Snippet_4
            }
            {
                #region Snippet_5
                #endregion Snippet_5
            }
            {
                #region Snippet_6
                #endregion Snippet_6
            }
            {
                #region Snippet_7
                #endregion Snippet_7
            }
            {
                #region Snippet_8
                #endregion Snippet_8
            }
        }