static GeometryHelpers()
        {
            var point = "POINT (141299 185188)";
            var geometry = new WKTReader {
                DefaultSRID = SpatialReferenceSystemId.Lambert72
            }.Read(point);

            ExampleWkb         = geometry.AsBinary();
            geometry.SRID      = SpatialReferenceSystemId.Lambert72;
            ExampleExtendedWkb = WkbWriter.Write(geometry);
        }
Example #2
0
        public void linearring_should_be_written_as_wkb()
        {
            var factory  = GeometryFactory.Default;
            var expected = factory.CreateLinearRing(new[]
            {
                new Coordinate(0, 0),
                new Coordinate(10, 0),
                new Coordinate(10, 10),
                new Coordinate(0, 10),
                new Coordinate(0, 0)
            });

            var writer = new WKBWriter();

            byte[] bytes = writer.Write(expected);
            Assert.That(bytes, Is.Not.Null);
            Assert.That(bytes, Is.Not.Empty);

            var reader = new WKBReader();
            var actual = reader.Read(bytes);

            Assert.That(actual, Is.Not.Null);
            Assert.That(actual, Is.EqualTo(expected));
            Assert.That(actual.OgcGeometryType, Is.EqualTo(expected.OgcGeometryType));

            // WKBReader reads "LinearRing" geometries as LineString
            Assert.That(expected, Is.InstanceOf <LinearRing>());
            Assert.That(actual, Is.InstanceOf <LineString>());
            Assert.That(actual.GeometryType, Is.Not.EqualTo(expected.GeometryType));
        }
Example #3
0
        /// <summary>
        /// 将GeoAPI中的geometry对象转换为arcgis中的geometry对象
        /// </summary>
        /// <param name="geometry"></param>
        /// <returns></returns>
        public static IGeometry ConvertGeoApitoEsri(GeoAPI.Geometries.IGeometry geometry)
        {
            WKBWriter writer = new WKBWriter();

            byte[] bytes = writer.Write(geometry);
            return(ConvertWkbToGeometry(bytes));
        }
Example #4
0
        public static byte[] ConvertWkttoWkb(string wkt)
        {
            WKBWriter writer = new WKBWriter();
            WKTReader reader = new WKTReader();

            return(writer.Write(reader.Read(wkt)));
        }
Example #5
0
        public void NullSafeSet(IDbCommand cmd, object value, int index)
        {
            var geometry = (IGeometry)value;

            FixMixedCoordinateStyles(geometry);

            if (useWkt)
            {
                string wellKnownText = null;
                if (value != null)
                {
                    wellKnownText = wktWriter.Write(geometry);
                }
                NHibernateUtil.String.NullSafeSet(cmd, wellKnownText, index);
            }
            else
            {
                byte[] wellKnownBinary = null;
                if (value != null)
                {
                    wellKnownBinary = wkbWriter.Write(geometry);
                }

                NHibernateUtil.Binary.NullSafeSet(cmd, wellKnownBinary, index);
            }
        }
Example #6
0
        private static byte[] ConvertWKTToWKB(string wkt)
        {
            var writer = new WKBWriter();
            var reader = new WKTReader();

            return(writer.Write(reader.Read(wkt)));
        }
Example #7
0
        private IEnumerable <trout_stream_section> CreateSection(trout_streams_minnesota asdf, StreamRoute route)
        {
            var routeMultilineString      = route.OriginalGeometry as IMultiLineString;
            var troutStreamSection        = (asdf.OriginalGeometry as IMultiLineString);
            var desiredTroutStreamSection = (asdf.Geometry_4326 as IMultiLineString);
            var TroutStreamSection4236    = (asdf.Geometry_4326 as IMultiLineString);
            var numberOfGeometries        = troutStreamSection.Geometries.Count();

            for (var i = 0; i < numberOfGeometries; i++)
            {
                var s = troutStreamSection.Geometries[i] as ILineString;
                var desiredGeometry = desiredTroutStreamSection.Geometries[i] as ILineString;
                desiredGeometry.SRID = 44326;
                var asdf4236 = TroutStreamSection4236.Geometries[i];

                var trout_section = new trout_stream_section();

                var centroid = asdf4236.Centroid;
                trout_section.centroid_latitude  = Convert.ToDecimal(centroid.X);
                trout_section.centroid_longitude = Convert.ToDecimal(centroid.Y);
                trout_section.length_mi          = Convert.ToDecimal(s.Length) / METERS_IN_MILE;
                trout_section.public_length      = 0;
                trout_section.section_name       = asdf.kittle_nam ?? "Unnamed Stream";
                trout_section.source_id          = asdf.kittle_nbr;

                var multilineString = new MultiLineString(new[] { s });

                var t         = new LinearReference();
                var wktWriter = new WKTWriter();
                wktWriter.EmitSRID   = true;
                wktWriter.HandleSRID = true;
                var desiredMultilineString = new MultiLineString(new[] { desiredGeometry });
                desiredMultilineString.SRID = 4326;
                var text = wktWriter.Write(desiredMultilineString);
//                var superResultLol =
                var writer = new WKBWriter();
//                writer.HandleSRID = true;
//                writer.EmitSRID = true;

                var binResult = writer.Write(desiredMultilineString);
                var bin2      = desiredMultilineString.ToBinary();

                var stringResult = System.Text.Encoding.UTF7.GetString(binResult);
                trout_section.Geom = asdf.Geom_4326;
                var result = t.GetIntersectionOfLine(routeMultilineString.Geometries.First() as ILineString, s).ToList();

                trout_section.start = (decimal)result[0] / METERS_IN_MILE;
                trout_section.stop  = (decimal)result[1] / METERS_IN_MILE;

                yield return(trout_section);
            }
        }
        // Writes shapes in an internal format readable by {@link #readShapeFromBytes(byte[], int, int)}.
        public byte[] WriteShapeToBytes(Shape shape)
        {
            var p = shape as Shapes.Point;

            if (p != null)
            {
                using (var stream = new MemoryStream(1 + (2 * 8)))
                    using (var bytes = new BinaryWriter(stream))
                    {
                        bytes.Write(TYPE_POINT);
                        bytes.Write(p.GetX());
                        bytes.Write(p.GetY());
                        return(stream.ToArray());
                    }
            }

            var rect = shape as Rectangle;

            if (rect != null)
            {
                using (var stream = new MemoryStream(1 + (4 * 8)))
                    using (var bytes = new BinaryWriter(stream))
                    {
                        bytes.Write(TYPE_BBOX);
                        bytes.Write(rect.GetMinX());
                        bytes.Write(rect.GetMaxX());
                        bytes.Write(rect.GetMinY());
                        bytes.Write(rect.GetMaxY());
                        return(stream.ToArray());
                    }
            }

            var ntsShape = shape as NtsGeometry;

            if (ntsShape != null)
            {
                var    writer = new WKBWriter();
                byte[] bb     = writer.Write(ntsShape.GetGeom());
                using (var stream = new MemoryStream(1 + bb.Length))
                    using (var bytes = new BinaryWriter(stream))
                    {
                        bytes.Write(TYPE_GEOM);
                        bytes.Write(bb);
                        return(stream.ToArray());
                    }
            }

            throw new ArgumentException("unsuported shape:" + shape);
        }
        public RouteNode Create(Point point)
        {
            var wkbWriter = new WKBWriter();

            var node = new RouteNode
                       (
                Guid.NewGuid(),
                wkbWriter.Write(point),
                Guid.Empty,
                _applicationSettings.ApplicationName,
                _applicationSettings.ApplicationName
                       );

            return(node);
        }
        public void TestSRID()
        {
            var gf = new GeometryFactory();
            var p1 = gf.CreatePoint(new Coordinate(1, 2));

            p1.SRID = 1234;

            //first write out without srid set
            var w = new WKBWriter(ByteOrder.BigEndian);

            byte[] wkb = w.Write(p1);

            //check the 3rd bit of the second byte, should be unset
            byte b = (byte)(wkb[1] & 0x20);

            Assert.AreEqual(0, b);

            //read geometry back in
            var r  = new WKBReader();
            var p2 = (Point)r.Read(wkb);

            Assert.IsTrue(p1.EqualsExact(p2));
            //NOTE: this differs from JTS-WKBReader, where SRID = 0 when handleSRID = false;
            Assert.AreEqual(-1, p2.SRID);

            //not write out with srid set
            w   = new WKBWriter(ByteOrder.BigEndian, true);
            wkb = w.Write(p1);

            //check the 3rd bit of the second byte, should be set
            b = (byte)(wkb[1] & 0x20);
            Assert.AreEqual(0x20, b);

            int srid = ((int)(wkb[5] & 0xff) << 24) | ((int)(wkb[6] & 0xff) << 16) |
                       ((int)(wkb[7] & 0xff) << 8) | ((int)(wkb[8] & 0xff));

            Assert.AreEqual(1234, srid);

            r  = new WKBReader();
            p2 = (Point)r.Read(wkb);

            //read the geometry back in
            Assert.IsTrue(p1.EqualsExact(p2));
            Assert.AreEqual(1234, p2.SRID);
        }
Example #11
0
        public void TestWritingEmptyLineString()
        {
            var wkbWriter    = new WKBWriter();
            var memoryStream = new MemoryStream();
            var linestring   = new LineString(new ICoordinate[0]);

            Assert.IsNull(linestring.Coordinate);

            try
            {
                wkbWriter.Write(linestring, memoryStream);
            }
            finally
            {
                memoryStream.Close();
                memoryStream.Dispose();
            }
        }
Example #12
0
        private static ExtendedWkbGeometry CreateEWkb(byte[] wkb)
        {
            if (wkb == null)
            {
                return(null);
            }

            var geometry = WKBReaderFactory.Create()
                           .Read(wkb);

            geometry.SRID = SpatialReferenceSystemId.Lambert72;

            var wkbWriter = new WKBWriter {
                Strict = false, HandleSRID = true
            };

            return(new ExtendedWkbGeometry(wkbWriter.Write(geometry)));
        }
        /// <summary>
        /// Geometries to string.
        /// </summary>
        /// <param name="geo">The geo.</param>
        /// <returns></returns>
        public static string ToString(this Geometry geo)
        {
            // Kann ja passieren, ist ja auch nicht weiter schlimm, liefern wir halt eben auch null zurück.
            if (geo == null)
            {
                return(null);
            }

            byte[] baData = wkbwriter.Write(geo);

            StringBuilder sb = new StringBuilder(baData.Length << 1);

            foreach (byte b in baData)
            {
                sb.AppendFormat("{0:X2}", b);
            }

            return(sb.ToString());
        }
        public void OracleWKBBigEndianWriteTest()
        {
            var shell = Factory.CreateLinearRing(new Coordinate[] { new Coordinate(100, 100),
                                                                    new Coordinate(200, 100),
                                                                    new Coordinate(200, 200),
                                                                    new Coordinate(100, 200),
                                                                    new Coordinate(100, 100), });
            var hole = Factory.CreateLinearRing(new Coordinate[] { new Coordinate(120, 120),
                                                                   new Coordinate(180, 120),
                                                                   new Coordinate(180, 180),
                                                                   new Coordinate(120, 180),
                                                                   new Coordinate(120, 120), });
            var polygon = Factory.CreatePolygon(shell, new LinearRing[] { hole, });
            var writer  = new WKBWriter(ByteOrder.BigEndian);

            byte[] bytes = writer.Write(polygon);
            Assert.IsNotNull(bytes);
            Assert.IsNotEmpty(bytes);
            Debug.WriteLine(bytes.Length);
        }
        private static ExtendedWkbGeometry CreateEWkb(byte[] wkb)
        {
            if (wkb == null)
            {
                return(null);
            }

            var geometry = new WKBReader(
                new NtsGeometryServices(
                    new DotSpatialAffineCoordinateSequenceFactory(Ordinates.XY),
                    new PrecisionModel(PrecisionModels.Floating),
                    SpatialReferenceSystemId.Lambert72)).Read(wkb);

            geometry.SRID = SpatialReferenceSystemId.Lambert72;

            var wkbWriter = new WKBWriter {
                Strict = false, HandleSRID = true
            };

            return(new ExtendedWkbGeometry(wkbWriter.Write(geometry)));
        }
Example #16
0
        /// <summary>
        /// Writes a geometry to a byte array using the specified encoding.
        /// </summary>
        /// <param name="g">The geometry to write</param>
        /// <param name="wkbByteOrder">Byte order</param>
        /// <returns>WKB representation of the geometry</returns>
        public static byte[] Write(IGeometry g, WkbByteOrder wkbByteOrder)
        {
            ByteOrder order;

            switch (wkbByteOrder)
            {
            case WkbByteOrder.Xdr:
                order = ByteOrder.BigEndian;
                break;

            case WkbByteOrder.Ndr:
                order = ByteOrder.LittleEndian;
                break;

            default:
                throw new ArgumentOutOfRangeException("wkbByteOrder");
            }

            WKBWriter wkb = new WKBWriter(order);

            return(wkb.Write(g));

            /*
             * MemoryStream ms = new MemoryStream();
             * BinaryWriter bw = new BinaryWriter(ms);
             *
             * //Write the byteorder format.
             * bw.Write((byte) wkbByteOrder);
             *
             * //Write the type of this geometry
             * WriteType(g, bw, wkbByteOrder);
             *
             * //Write the geometry
             * WriteGeometry(g, bw, wkbByteOrder);
             *
             * return ms.ToArray();
             */
        }
        void CheckWKB(string wkt, ByteOrder byteOrder, bool emitZ, int srid, string expectedWKBHex)
        {
            var geom = Read(wkt);

            // set SRID if not -1
            bool includeSRID = false;

            if (srid > 0)
            {
                includeSRID = true;
                geom.SRID   = srid;
            }

            var wkbWriter = new WKBWriter(byteOrder, includeSRID, emitZ)
            {
                Strict = false
            };

            byte[] wkb    = wkbWriter.Write(geom);
            string wkbHex = WKBWriter.ToHex(wkb);

            Assert.AreEqual(expectedWKBHex, wkbHex);
        }
Example #18
0
        public void BuildGraphBinary()
        {
            string path = "strade" + shp;

            Assert.IsTrue(File.Exists(path));

            ShapefileReader     reader = new ShapefileReader(path, factory);
            IGeometryCollection coll   = reader.ReadAll();

            Assert.IsNotNull(coll);
            Assert.IsNotEmpty(coll.Geometries);

            IGeometry result = coll.Geometries[0];

            for (int i = 1; i < coll.NumGeometries; i++)
            {
                Debug.WriteLine(String.Format("Union of {0}'th geometry", i));
                result = result.Union(coll.Geometries[i]);
            }
            Assert.IsNotNull(result);
            Assert.IsInstanceOfType(typeof(MultiLineString), result);

            WKBWriter wkbwriter = new WKBWriter();

            byte[] rawdata = wkbwriter.Write(result);
            Assert.IsNotEmpty(rawdata);

            path = "graph";
            if (File.Exists(path))
            {
                File.Delete(path);
            }
            Assert.IsFalse(File.Exists(path));
            using (FileStream stream = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None))
                stream.Write(rawdata, 0, rawdata.Length);
            Assert.IsTrue(File.Exists(path));
        }
Example #19
0
        void RunGeometry(Geometry g, int dimension, ByteOrder byteOrder, bool toHex, int srid)
        {
            bool includeSRID = false;

            if (srid >= 0)
            {
                includeSRID = true;
                g.SRID      = srid;
            }

            var wkbWriter = new WKBWriter(byteOrder, includeSRID, dimension == 2 ? false : true);

            byte[] wkb    = wkbWriter.Write(g);
            string wkbHex = null;

            if (toHex)
            {
                wkbHex = WKBWriter.ToHex(wkb);
            }

            if (toHex)
            {
                wkb = WKBReader.HexToBytes(wkbHex);
            }
            var g2 = (Geometry)_wkbReader.Read(wkb);

            var  comp    = (dimension == 2) ? Comp2 : Comp3;
            bool isEqual = (g.CompareTo(g2, comp) == 0);

            Assert.IsTrue(isEqual);

            if (includeSRID)
            {
                bool isSRIDEqual = g.SRID == g2.SRID;
                Assert.IsTrue(isSRIDEqual);
            }
        }
        public static string GetValueEscaped(object val, PropertyInfo prop = null)
        {
            if (val == null)
            {
                return("null");
            }
            Type t;

            if (prop == null)
            {
                t = val.GetType();
            }
            else
            {
                t = prop.PropertyType;
            }
            if (t == typeof(double) || t == typeof(double?))
            {
                return(CheapEscape(((double)val).ToString(CultureInfo.InvariantCulture)));
            }
            else if (t == typeof(int) || t == typeof(int?))
            {
                return(val.ToString());
            }
            else if (t == typeof(bool) || t == typeof(bool?))
            {
                if ((bool)val)
                {
                    return("1");
                }
                else
                {
                    return("0");
                }
            }
            else if (t == typeof(byte[]))
            {
                //No se puede insertar byte array porque rompe el max_allowed_packet, además
                //duplica el tamaño porque hay que mandarlo como hexa.
                throw new Exception("Invalid type.");
            }
            else if (t == typeof(Geometry))
            {
                WKBWriter writer = new WKBWriter();
                var       bytes  = writer.Write((Geometry)val);
                return("0x00000000" + BitConverter.ToString(bytes).Replace("-", ""));
            }
            else if (t == typeof(Point))
            {
                WKBWriter writer = new WKBWriter();
                var       bytes  = writer.Write((Point)val);
                return("0x00000000" + BitConverter.ToString(bytes).Replace("-", ""));
            }
            else if (t == typeof(MultiPolygon))
            {
                WKBWriter writer = new WKBWriter();
                var       bytes  = writer.Write((MultiPolygon)val);
                return("0x00000000" + BitConverter.ToString(bytes).Replace("-", ""));
            }
            else if (t == typeof(LineString))
            {
                WKBWriter writer = new WKBWriter();
                var       bytes  = writer.Write((LineString)val);
                return("0x00000000" + BitConverter.ToString(bytes).Replace("-", ""));
            }
            else if (t == typeof(MultiLineString))
            {
                WKBWriter writer = new WKBWriter();
                var       bytes  = writer.Write((MultiLineString)val);
                return("0x00000000" + BitConverter.ToString(bytes).Replace("-", ""));
            }
            else if (t == typeof(Polygon))
            {
                WKBWriter writer = new WKBWriter();
                var       bytes  = writer.Write((Polygon)val);
                return("0x00000000" + BitConverter.ToString(bytes).Replace("-", ""));
            }
            else if (typeof(IIdentifiable).IsAssignableFrom(t))
            {
                return(((IIdentifiable)val).Id.ToString());
            }
            else
            {
                return(CheapEscape(val.ToString()));
            }
        }
Example #21
0
 public byte[] Write(IGeometry geometry) => _wkbWriter.Write(geometry);
Example #22
0
 public byte[] Write(IGeometry geometry)
 {
     return(_wkbWriter.Write(geometry));
 }