public void Test()
        {
            var features = new List<Features.IFeature>();
            var seq = DotSpatialAffineCoordinateSequenceFactory.Instance.Create(1, Ordinates.XY);
            seq.SetOrdinate(0, Ordinate.X, -91.0454);
            seq.SetOrdinate(0, Ordinate.Y, 32.5907);
            var pt = new GeometryFactory(DotSpatialAffineCoordinateSequenceFactory.Instance).CreatePoint(seq);
            var attr = new Features.AttributesTable();
            attr.AddAttribute("FirstName", "John");
            attr.AddAttribute("LastName", "Doe");
            features.Add(new Features.Feature(pt, attr));

            var fileName = Path.GetTempFileName();
            fileName = fileName.Substring(0, fileName.Length - 4);
            var shpWriter = new IO.ShapefileDataWriter(fileName, features[0].Geometry.Factory)
            {
                Header = IO.ShapefileDataWriter.GetHeader(features[0], features.Count)
            };
            shpWriter.Write(features);

            bool isTrue;
            using (var reader = new IO.ShapefileDataReader(fileName, pt.Factory))
                @isTrue = reader.ShapeHeader.ShapeType.ToString() == "Point";
           
            foreach (var file in Directory.GetFiles(Path.GetTempPath(), Path.GetFileName(fileName) + ".*" ))
            {
                File.Delete(file);
            }

            Assert.IsTrue(@isTrue);
        }
        public void TestAreaPrecisionPerformance()
        {

            const double originX = 1000000;
            const double originY = 5000000;
            var sw = new Stopwatch();
            var sw1 = new Stopwatch();
            var sw2 = new Stopwatch();
            var sw3 = new Stopwatch();
                                   
            //-2,23057128323489E-11

            sw.Start();
            for (var nrVertices = 4; nrVertices <= 5000000; nrVertices *= 2)
            {
                var coordinates = new Coordinate[nrVertices + 1];

                for (var i = 0; i <= nrVertices; i++)
                {
                    var vertex = new Coordinate(originX + (1d + Math.Sin( i/(double) nrVertices*2*Math.PI)),
                                                originY + (1d + Math.Cos( i/(double) nrVertices*2*Math.PI)));
                    coordinates[i] = vertex;
                }
                // close ring
                coordinates[nrVertices] = coordinates[0];

                var g1 = new GeometryFactory().CreateLinearRing(coordinates);
                var holes = new ILinearRing[] {};
                var polygon = (Polygon) new GeometryFactory().CreatePolygon(g1, holes);
                //Console.WriteLine(polygon);

                sw1.Start();
                var area = polygon.Area;
                sw1.Stop();
                sw2.Start();
                var area2 = AccurateSignedArea(coordinates);
                sw2.Stop();
                sw3.Start();
                var areaOld = OriginalSignedArea(coordinates);
                sw3.Stop();

                var exactArea = 0.5 * nrVertices * Math.Sin(2 * Math.PI / nrVertices);
                var eps1 = exactArea - area;
                var eps2 = exactArea - area2;
                var eps3 = exactArea - areaOld;
                
                //Assert.IsTrue(Math.Abs(eps2) <= Math.Abs(eps3));

                Console.WriteLine(string.Format("{0,10},\tnow err: {1,23},\tacc err: {2,23},\told err: {3,23}", nrVertices ,eps1, eps2 ,eps3));
            }
            
            sw.Stop();

            Console.WriteLine("\n\nTime: " + sw.Elapsed);
            Console.WriteLine("Time Now: " + sw1.ElapsedTicks);
            Console.WriteLine("Time Acc: " + sw2.ElapsedTicks);
            Console.WriteLine("Time Old: " + sw3.ElapsedTicks);
            
            Assert.IsTrue(true);
        }
Example #3
0
        public static Point WgsToGoogle(Point p)
        {
            GeometryFactory factory = new NetTopologySuite.Geometries.GeometryFactory();
            Point           result  = GeometryTransform.TransformGeometry(p, LayerTools.wgs84toGoogle.MathTransform, factory) as Point;

            return(result);
        }
Example #4
0
        private void Form2_Load(object sender, EventArgs e)
        {
            //TileAsyncLayer osmLayer= new TileAsyncLayer(new OsmTileSource(), "TileLayer - OSM");
            TileAsyncLayer bingLayer = new TileAsyncLayer(new BingTileSource(BingRequest.UrlBing, "", BingMapType.Roads), "TileLayer - Bing");

            this.mapBox1.Map.BackgroundLayer.Add(bingLayer);
            GeometryFactory gf = new GeometryFactory(new PrecisionModel(), 3857);

#if DotSpatialProjections
            var mathTransform = LayerTools.Wgs84toGoogleMercator;
            var geom = GeometryTransform.TransformBox(
                new Envelope(-9.205626, -9.123736, 38.690993, 38.740837), 
                mathTransform.Source, mathTransform.Target);
#else
            IMathTransform mathTransform = LayerTools.Wgs84toGoogleMercator.MathTransform;
            Envelope geom = GeometryTransform.TransformBox(
                new Envelope(-9.205626, -9.123736, 38.690993, 38.740837),
                mathTransform);
#endif

            //Adds a pushpin layer
            VectorLayer pushPinLayer = new VectorLayer("PushPins");
            List<IGeometry> geos = new List<IGeometry>();
            geos.Add(gf.CreatePoint(geom.Centre));
            var geoProvider = new FeatureProvider(geos);
            pushPinLayer.DataSource = geoProvider;
            //this.mapBox1.Map.Layers.Add(pushPinLayer);

            this.mapBox1.Map.ZoomToBox(geom);
            this.mapBox1.Map.Zoom = 8500;
            this.mapBox1.Refresh();
        }
        private void TestWriteZMValuesShapeFile(bool testM)
        {
            var points = new Coordinate[3];
            points[0] = new Coordinate(0, 0);
            points[1] = new Coordinate(1, 0);
            points[2] = new Coordinate(1, 1);

            var csFactory = NetTopologySuite.Geometries.Implementation.DotSpatialAffineCoordinateSequenceFactory.Instance;
            var sequence = csFactory.Create(3, Ordinates.XYZM);
            for (var i = 0; i < 3; i ++)
            {
                sequence.SetOrdinate(i, Ordinate.X, points[i].X);
                sequence.SetOrdinate(i, Ordinate.Y, points[i].Y);
                sequence.SetOrdinate(i, Ordinate.Z, 1 + i);
                if (testM) 
                    sequence.SetOrdinate(i, Ordinate.M, 11 + i);
            }
            var lineString = Factory.CreateLineString(sequence);

            var attributes = new AttributesTable();
            attributes.AddAttribute("FOO", "Trond");

            var feature = new Feature(Factory.CreateMultiLineString(new[] { lineString }), attributes);
            var features = new Feature[1];
            features[0] = feature;

            var shpWriter = new ShapefileDataWriter("ZMtest", Factory)
            {
                Header = ShapefileDataWriter.GetHeader(features[0], features.Length)
            };
            shpWriter.Write(features);

            // Now let's read the file and verify that we got Z and M back
            var factory = new GeometryFactory(NetTopologySuite.Geometries.Implementation.DotSpatialAffineCoordinateSequenceFactory.Instance);

            using (var reader = new ShapefileDataReader("ZMtest", factory))
            {
                reader.Read();
                var geom = reader.Geometry;

                for (var i = 0; i < 3; i++)
                {
                    var c = geom.Coordinates[i];
                    Assert.AreEqual(i + 1, c.Z);             
                }

                if (testM)
                {
                    sequence = ((ILineString) geom).CoordinateSequence;
                    for (var i = 0; i < 3; i++)
                    {
                        Assert.AreEqual(sequence.GetOrdinate(i, Ordinate.M), 11 + i);
                    }
                }

                // Run a simple attribute test too
                var v = reader.GetString(0);
                Assert.AreEqual(v, "Trond");
            }
        }   
Example #6
0
        public static Point GoogleToWgs(Point p)
        {
            GeometryFactory factory = new NetTopologySuite.Geometries.GeometryFactory();
            Point           result  = GeometryTransform.TransformGeometry(p, LayerTools.GoogleMercatorToWgs84.MathTransform, factory) as Point;

            return(result);
        }
		public static void main(string[] args)
		{
			ExtendedCoordinateSequenceFactory seqFact = ExtendedCoordinateSequenceFactory.Instance();
			
			ExtendedCoordinate[] array1 = new ExtendedCoordinate[] { new ExtendedCoordinate(0, 0, 0, 91), 
                new ExtendedCoordinate(10, 0, 0, 92), new ExtendedCoordinate(10, 10, 0, 93), 
                new ExtendedCoordinate(0, 10, 0, 94), new ExtendedCoordinate(0, 0, 0, 91)};
			ICoordinateSequence seq1 = seqFact.Create(array1);
			
			ICoordinateSequence seq2 = seqFact.Create(new ExtendedCoordinate[] { new ExtendedCoordinate(5, 5, 0, 91), 
                new ExtendedCoordinate(15, 5, 0, 92), new ExtendedCoordinate(15, 15, 0, 93), 
                new ExtendedCoordinate(5, 15, 0, 94), new ExtendedCoordinate(5, 5, 0, 91)});
			
			GeometryFactory fact = new GeometryFactory(ExtendedCoordinateSequenceFactory.Instance());

            IGeometry g1 = fact.CreatePolygon(fact.CreateLinearRing(seq1), null);
            IGeometry g2 = fact.CreatePolygon(fact.CreateLinearRing(seq2), null);
			
			Console.WriteLine("WKT for g1: " + g1);
			Console.WriteLine("Internal rep for g1: " + ((IPolygon) g1).ExteriorRing.CoordinateSequence);
			
			Console.WriteLine("WKT for g2: " + g2);
            Console.WriteLine("Internal rep for g2: " + ((IPolygon)g2).ExteriorRing.CoordinateSequence);

            IGeometry gInt = g1.Intersection(g2);
			
			Console.WriteLine("WKT for gInt: " + gInt);
            Console.WriteLine("Internal rep for gInt: " + ((IPolygon)gInt).ExteriorRing.CoordinateSequence);
		}
 public XmlTestFactory(PrecisionModel pm, IGeometryOperation geometryOperation, IResultMatcher resultMatcher)
 {
     ObjGeometryFactory = new GeometryFactory(pm);
     _geometryOperation = geometryOperation;
     _resultMatcher = resultMatcher;
     _objReader = new WKTOrWKBReader(ObjGeometryFactory);
 }
Example #9
0
 public static ILineString GetALine()
 {
     var p1 = new Coordinate(0, 0);
     var p2 = new Coordinate(10, 10);
     var coordinatesp = new[] { p1, p2 };
     var line1 = new GeometryFactory().CreateLineString(coordinatesp);
     return line1;
 }
Example #10
0
 public static ILineString GetASecondLine()
 {
     var q1 = new Coordinate(0, 10);
     var q2 = new Coordinate(10, 0);
     var coordinatesq = new[] { q1, q2 };
     var line2 = new GeometryFactory().CreateLineString(coordinatesq);
     return line2;
 }
 public void TestPackedCoordinateSequence() {
     var pcsFactory = new GeometryFactory(PackedCoordinateSequenceFactory.DoubleFactory);
     var geom0 = Read(pcsFactory, "POLYGON ((210 210, 210 220, 220 220, 220 210, 210 210))");
     var geom1 = Read("POLYGON ((225 225, 225 215, 215 215, 215 225, 225 225))");
     var cbo = new CommonBitsOp(true);
     var result = cbo.Intersection(geom0, geom1);
     var expected = geom0.Intersection(geom1);
     //Geometry expected = read("POLYGON ((220 215, 215 215, 215 220, 220 220, 220 215))");
     CheckEqual(expected, result);
 }
		public virtual void  Intersection(string wktA, string wktB, PrecisionModel pm)
		{
			Console.WriteLine("Running example using Precision Model = " + pm);
			GeometryFactory fact = new GeometryFactory(pm);
			WKTReader wktRdr = new WKTReader(fact);
			
			IGeometry A = wktRdr.Read(wktA);
			IGeometry B = wktRdr.Read(wktB);
			IGeometry C = A.Intersection(B);
			
			Console.WriteLine("A intersection B = " + C);
		}
        public GeometryPrecisionReducerTest()
        {
            pmFloat = new PrecisionModel();
            pmFixed1 = new PrecisionModel(1);
            reducer = new GeometryPrecisionReducer(pmFixed1);
            reducerKeepCollapse = new GeometryPrecisionReducer(pmFixed1);

            gfFloat = new GeometryFactory(pmFloat, 0);
            reader = new WKTReader(gfFloat);

            reducerKeepCollapse.RemoveCollapsedComponents = false;
        }
 public void CoordinateTransformationTransformsQueryHavingDifferentSpatialReferenceAsTransformationTarget()
 {
     MockRepository repository = new MockRepository();
     FeatureProviderBase provider = repository.CreateMock<FeatureProviderBase>();
     BufferedCoordinateFactory coordFactory = new BufferedCoordinateFactory();
     BufferedCoordinateSequenceFactory coordSeqFactory = new BufferedCoordinateSequenceFactory(coordFactory);
     IGeometryFactory<BufferedCoordinate> geoFactory = new GeometryFactory<BufferedCoordinate>(coordSeqFactory);
     IMatrixFactory<DoubleComponent> matrixFactory = new LinearFactory<DoubleComponent>();
     ICoordinateTransformationFactory transformFactory =
         new CoordinateTransformationFactory<BufferedCoordinate>(coordFactory, geoFactory, matrixFactory);
     SetupResult.For(provider.CoordinateTransformation).Return(transformFactory);
 }
        private static GeoAPI.Geometries.ILineString CreateSineLine(GeoAPI.Geometries.Coordinate offset,
                                                                    double scaleY = 100)
        {
            var factory = new NetTopologySuite.Geometries.GeometryFactory();
            var cs      = factory.CoordinateSequenceFactory.Create(181, 2);

            for (int i = 0; i <= 180; i++)
            {
                cs.SetOrdinate(i, GeoAPI.Geometries.Ordinate.X, offset.X + 2 * i);
                cs.SetOrdinate(i, GeoAPI.Geometries.Ordinate.Y, offset.Y + scaleY * System.Math.Sin(2d * i * System.Math.PI / 180d));
            }
            return(factory.CreateLineString(cs));
        }
		public static void main(string[] args)
		{
			// create a factory using default values (e.g. floating precision)
			GeometryFactory fact = new GeometryFactory();
			
			IPoint p1 = fact.CreatePoint(new Coordinate(0, 0));
			Console.WriteLine(p1);
			
			IPoint p2 = fact.CreatePoint(new Coordinate(1, 1));
			Console.WriteLine(p1);
			
			IMultiPoint mpt = fact.CreateMultiPoint(new Coordinate[]{ new Coordinate(0, 0), new Coordinate(1, 1), });
			Console.WriteLine(mpt);
		}
Example #17
0
        public void check_difference_results_with_fixed_precision()
        {
            GeometryFactory precisionModel = new GeometryFactory(new PrecisionModel(100));
            WKTReader reader = new WKTReader(precisionModel);
            IGeometry p1 = reader.Read(@"POLYGON ((504927.9 6228865.64, 504969.88 6228833.89, 504980.82 6228861.76, 504927.9 6228865.64))");
            IGeometry p2 = reader.Read(@"POLYGON ((504927.9 6228865.64, 504951.14 6228848.06, 504957.42 6228863.47, 504927.9 6228865.64))");
            IGeometry test = p1.Difference(p2);
            Assert.That(test, Is.Not.Null);
            Assert.That(test.IsEmpty, Is.False);

            const string expected = @"POLYGON ((504927.9 6228865.64, 504980.82 6228861.76, 504969.88 6228833.89, 504951.14 6228848.06, 504957.42 6228863.47, 504927.9 6228865.64))";
            string actual = test.AsText();
            Assert.That(actual, Is.EqualTo(expected));
        }
        /// <summary>
        /// 
        /// </summary>
		public virtual void Run()
		{
			GeometryFactory fact = new GeometryFactory();
			WKTReader wktRdr = new WKTReader(fact);
			
			string wktA = "POLYGON((40 100, 40 20, 120 20, 120 100, 40 100))";
			string wktB = "LINESTRING(20 80, 80 60, 100 140)";
			IGeometry A = wktRdr.Read(wktA);
			IGeometry B = wktRdr.Read(wktB);
            IGeometry C = A.Intersection(B);
			Console.WriteLine("A = " + A);
			Console.WriteLine("B = " + B);
			Console.WriteLine("A intersection B = " + C);
			Console.WriteLine("A relate C = " + A.Relate(B));
		}
        private void FormMovingObjectOverTileLayer_Load(object sender, EventArgs e)
        {

            //Lisbon...
#if DotSpatialProjections
            var mathTransform = LayerTools.Wgs84toGoogleMercator;
            var geom = GeometryTransform.TransformBox(
                new Envelope(-9.205626, -9.123736, 38.690993, 38.740837),
                mathTransform.Source, mathTransform.Target);
#else
            var mathTransform = LayerTools.Wgs84toGoogleMercator.MathTransform;
            GeoAPI.Geometries.Envelope geom = GeometryTransform.TransformBox(
                new Envelope(-9.205626, -9.123736, 38.690993, 38.740837),
                mathTransform);
#endif


            //Google Background
            TileAsyncLayer layer2 = new TileAsyncLayer(new OsmTileSource(), "TileLayer - OSM");


            this.mapBox1.Map.BackgroundLayer.Add(layer2);
            var gf = new GeometryFactory(new PrecisionModel(), 3857);

            //Adds a static layer
            var staticLayer = new VectorLayer("Fixed Marker");
            //position = geom.GetCentroid();
            var aux = new List<IGeometry>();
            aux.Add(gf.CreatePoint(geom.Centre));
            staticLayer.Style.Symbol = Resources.PumpSmall;
            var geoProviderFixed = new SharpMap.Data.Providers.FeatureProvider(aux);
            staticLayer.DataSource = geoProviderFixed;
            this.mapBox1.Map.Layers.Add(staticLayer);

            
            //Adds a moving variable layer
            VectorLayer pushPinLayer = new VectorLayer("PushPins");
            position = geom.Centre;
            geos.Add(gf.CreatePoint(position));
            pushPinLayer.Style.Symbol = Resources.OutfallSmall;
            var geoProvider = new SharpMap.Data.Providers.FeatureProvider(geos);
            pushPinLayer.DataSource = geoProvider;
            this.mapBox1.Map.VariableLayers.Add(pushPinLayer);

            this.mapBox1.Map.ZoomToBox(geom);
            this.mapBox1.Refresh();

        }
        public void TestCopyGeometryWithNonDefaultDimension()
        {
            GeometryFactory gf = new GeometryFactory(CoordinateArraySequenceFactory.Instance);
            ICoordinateSequence mpSeq = gf.CoordinateSequenceFactory.Create(1, 2);
            mpSeq.SetOrdinate(0, Ordinate.X, 50);
            mpSeq.SetOrdinate(0, Ordinate.Y, -2);

            IPoint g = gf.CreatePoint(mpSeq);
            IPoint geometryN = (IPoint)g.GetGeometryN(0);
            ICoordinateSequence gSeq = geometryN.CoordinateSequence;
            Assert.AreEqual(2, gSeq.Dimension);

            IPoint g2 = (IPoint)Factory.CreateGeometry(g);
            ICoordinateSequence g2Seq = g2.CoordinateSequence;
            Assert.AreEqual(2, g2Seq.Dimension);
        }
        public void TestMultiPointDim4()
        {
            GeometryFactory gf = new GeometryFactory(new PackedCoordinateSequenceFactory());
            ICoordinateSequence mpSeq = gf.CoordinateSequenceFactory.Create(1, Ordinates.XYZM);
            mpSeq.SetOrdinate(0, Ordinate.X, 50);
            mpSeq.SetOrdinate(0, Ordinate.Y, -2);
            mpSeq.SetOrdinate(0, Ordinate.Z, 10);
            mpSeq.SetOrdinate(0, Ordinate.M, 20);

            IMultiPoint mp = gf.CreateMultiPoint(mpSeq);
            ICoordinateSequence pSeq = ((Point)mp.GetGeometryN(0)).CoordinateSequence;
            Assert.AreEqual(4, pSeq.Dimension);
            Assert.AreEqual(Ordinates.XYZM, pSeq.Ordinates);
            for (int i = 0; i < 4; i++)
                Assert.AreEqual(mpSeq.GetOrdinate(0, (Ordinate)i), pSeq.GetOrdinate(0, (Ordinate)i));
        }
        /// <summary>
        /// Imports a shapefile into a database table.
        /// </summary>
        /// <remarks>
        /// This method assumes a table has already been crated in the database.
        /// Calling this method does not close the connection that is passed in.
        /// </remarks>
        /// <param name="filename"></param>
        /// <param name="connectionstring"></param>
        /// <param name="tableName"></param>
        /// <returns></returns>
        public static int ImportShapefile(string filename, string connectionstring, string tableName)
        {
            using (SqlConnection connection = new SqlConnection(connectionstring))
            {
                int rowsAdded = -1;
                PrecisionModel pm = new PrecisionModel();
                GeometryFactory geometryFactory = new GeometryFactory(pm, -1);

                DataTable shpDataTable = CreateDataTable(filename, tableName, geometryFactory);
                string createTableSql = CreateDbTable(shpDataTable, true);

                SqlCommand createTableCommand = new SqlCommand(createTableSql, connection);
                connection.Open();
                createTableCommand.ExecuteNonQuery();

                string sqlSelect = String.Format("select * from {0}", tableName);
                SqlDataAdapter selectCommand = new SqlDataAdapter(sqlSelect, connection);

                // use a data adaptor - saves donig the inserts ourselves
                SqlDataAdapter dataAdapter = new SqlDataAdapter();
                dataAdapter.SelectCommand = new SqlCommand(sqlSelect, connection);
                SqlCommandBuilder custCB = new SqlCommandBuilder(dataAdapter);
                DataSet ds = new DataSet();

                // fill dataset
                dataAdapter.Fill(ds, shpDataTable.TableName);

                // copy rows from our datatable to the empty table in the DataSet
                int i = 0;
                foreach (DataRow row in shpDataTable.Rows)
                {
                    DataRow newRow = ds.Tables[0].NewRow();
                    newRow.ItemArray = row.ItemArray;
                    //gotcha! - new row still needs to be added to the table.
                    //NewRow() just creates a new row with the same schema as the table. It does
                    //not add it to the table.
                    ds.Tables[0].Rows.Add(newRow);
                    i++;
                }

                // update all the rows in batch
                rowsAdded = dataAdapter.Update(ds, shpDataTable.TableName);
                int iRows = shpDataTable.Rows.Count;
                Debug.Assert(rowsAdded != iRows, String.Format("{0} of {1] rows were added to the database.", rowsAdded, shpDataTable.Rows.Count));
                return rowsAdded;
            }
        }
		public static void main(string[] args)
		{
			// read a point from a WKT string (using the default point factory)
			IGeometry g1 = new WKTReader().Read("LINESTRING (0 0, 10 10, 20 20)");
			Console.WriteLine("Geometry 1: " + g1);
			
			// create a point by specifying the coordinates directly
			var coordinates = new [] { new Coordinate(0, 0), 
                new Coordinate(10, 10), new Coordinate(20, 20) };
			// use the default factory, which gives full double-precision
			IGeometry g2 = new GeometryFactory().CreateLineString(coordinates);
			Console.WriteLine("Geometry 2: " + g2);
			
			// compute the intersection of the two geometries
			IGeometry g3 = g1.Intersection(g2);
			Console.WriteLine("G1 intersection G2: " + g3);
		}
    public VectorLayer CreateGeometryLayer()
    {
        var gf = new NetTopologySuite.Geometries.GeometryFactory();
        var fdt = new FeatureDataTable();
        fdt.Columns.Add(new DataColumn("Name", typeof (String)));

        fdt.BeginLoadData();
        var fdr = (FeatureDataRow)fdt.LoadDataRow(new[] {(object) "Mayence"}, true);
        fdr.Geometry = gf.CreatePoint(new Point(8.1, 50.0));
        fdt.EndLoadData();

        var vLayer = new VectorLayer("GeometryProvider");
        vLayer.DataSource = new FeatureProvider(fdt);
        vLayer.SRID = 4326;

        return vLayer;
    }
        /// <summary>
        /// Creates a DataTable representing the information in a shape file.
        /// </summary>
        /// <param name="filename">The filename (minus the . and extension) to read.</param>
        /// <param name="tableName">The name to give to the table.</param>
        /// <param name="geometryFactory">The geometry factory to use when creating the objects.</param>
        /// <returns>DataTable representing the data </returns>
        public static DataTable CreateDataTable(string filename, string tableName, GeometryFactory geometryFactory)
        {
            if (filename == null)
                throw new ArgumentNullException("filename");
            if (tableName == null)
                throw new ArgumentNullException("tableName");
            if (geometryFactory == null)
                throw new ArgumentNullException("geometryFactory");

            ShapefileDataReader shpfileDataReader = new ShapefileDataReader(filename, geometryFactory);
            DataTable table = new DataTable(tableName);

            // use ICustomTypeDescriptor to get the properies/ fields. This way we can get the 
            // length of the dbase char fields. Because the dbase char field is translated into a string
            // property, we lost the length of the field. We need to know the length of the
            // field when creating the table in the database.

            IEnumerator enumerator = shpfileDataReader.GetEnumerator();
            bool moreRecords = enumerator.MoveNext();
            ICustomTypeDescriptor typeDescriptor = (ICustomTypeDescriptor)enumerator.Current;
            foreach (PropertyDescriptor property in typeDescriptor.GetProperties())
            {
                ColumnStructure column = (ColumnStructure)property;
                Type fieldType = column.PropertyType;
                DataColumn datacolumn = new DataColumn(column.Name, fieldType);
                if (fieldType == typeof(string))
                    // use MaxLength to pass the length of the field in the dbase file
                    datacolumn.MaxLength = column.Length;
                table.Columns.Add(datacolumn);
            }

            // add the rows - need a do-while loop because we read one row in order to determine the fields
            int iRecordCount = 0;
            object[] values = new object[shpfileDataReader.FieldCount];
            do
            {
                iRecordCount++;
                shpfileDataReader.GetValues(values);
                table.Rows.Add(values);
                moreRecords = enumerator.MoveNext();
            }
            while (moreRecords);
            return table;
        }
        public void TestSerializable()
        {
            var fact = new GeometryFactory();
            var gsf = new NetTopologySuite.Utilities.GeometricShapeFactory(fact) ;
            gsf.Size = 250; 
            var g = (Geometry)gsf.CreateCircle();

            // serialize the object
            byte[] bytes = null;
            Assert.DoesNotThrow(() => bytes = SerializationUtility.Serialize(g));            

            // Assert that there was some serialized content produced
            Assert.IsNotNull(bytes, "There was no serialized packet produced");
            Assert.IsTrue(bytes.Length > 0, "There was no data in the serialized packet produced");

            // deserialize and check
            var gCopy = SerializationUtility.Deserialize<Geometry>(bytes);
            Assert.IsTrue(gCopy.EqualsExact(g), "The deserialized object does not match the original");
        }
        public void TestGrid()
        {
            // Use fixed PM to try and get at least some points hitting the boundary
            GeometryFactory geomFactory = new GeometryFactory(pmFixed_1);
            //		GeometryFactory geomFactory = new GeometryFactory();
		
            PerturbedGridPolygonBuilder gridBuilder = new PerturbedGridPolygonBuilder(geomFactory);
            gridBuilder.NumLines = 20;
            gridBuilder.LineWidth = 10.0;
            IGeometry area = gridBuilder.Geometry;
		
            SimpleRayCrossingPointInAreaLocator pia = new SimpleRayCrossingPointInAreaLocator(area); 

            PointInAreaStressTester gridTester = new PointInAreaStressTester(geomFactory, area);
            gridTester.NumPoints = 100000;
            gridTester.TestPointInAreaLocator = pia;
		
            bool isCorrect = gridTester.Run();
            Assert.IsTrue(isCorrect);
        }
    public VectorLayer CreateGeometryLayer()
    {
        var gf  = new NetTopologySuite.Geometries.GeometryFactory();
        var fdt = new FeatureDataTable();

        fdt.Columns.Add(new DataColumn("Name", typeof(String)));

        fdt.BeginLoadData();
        var fdr = (FeatureDataRow)fdt.LoadDataRow(new[] { (object)"Mayence" }, true);

        fdr.Geometry = gf.CreatePoint(new Point(8.1, 50.0));
        fdt.EndLoadData();

        var vLayer = new VectorLayer("GeometryProvider");

        vLayer.DataSource = new GeometryFeatureProvider(fdt);
        vLayer.SRID       = 4326;

        return(vLayer);
    }
        public void check_difference_results_with_fixed_precision()
        {
            GeometryFactory precisionModel = new GeometryFactory(new PrecisionModel(100));
            WKTReader reader = new WKTReader(precisionModel);
            IGeometry p1 = reader.Read(@"POLYGON ((504927.9 6228865.64, 504969.88 6228833.89, 504980.82 6228861.76, 504927.9 6228865.64))");
            IGeometry p2 = reader.Read(@"POLYGON ((504927.9 6228865.64, 504951.14 6228848.06, 504957.42 6228863.47, 504927.9 6228865.64))");
            IGeometry test = p1.Difference(p2);
            Assert.That(test, Is.Not.Null);
            Assert.That(test.IsEmpty, Is.False);

            const string expected = @"POLYGON ((504927.9 6228865.64, 504980.82 6228861.76, 504969.88 6228833.89, 504951.14 6228848.06, 504957.42 6228863.47, 504927.9 6228865.64))";
            var res = reader.Read(expected);
            res.Normalize();
            test.Normalize();
            Console.WriteLine(test.AsText());
            Console.WriteLine(res.AsText());
            var hd = new HausdorffSimilarityMeasure();
            var resD  = hd.Measure(test, res);
            Assert.That(1-resD, Is.LessThan(1e7));
        }
Example #30
0
        /// <summary>
        ///     Converts a Microsoft.Spatial GeographyPolygon to a Polygon.
        /// </summary>
        /// <param name="geographyPolygon">The Microsoft.Spatial GeographyPolygon.</param>
        /// <returns></returns>
        public static Polygon ToNtsPolygon(this GeographyPolygon geographyPolygon)
        {
            if (geographyPolygon == null)
            {
                return(null);
            }

            var coords = new List <Coordinate>();

            foreach (var ring in geographyPolygon.Rings)
            {
                foreach (var coord in ring.Points)
                {
                    coords.Add(new Coordinate(coord.Longitude, coord.Latitude));
                }
            }

            var geomFactory = new GeometryFactory(new PrecisionModel(), 4326);

            coords.RemoveAt(coords.Count - 1);
            //coords.Sort(new CoordinateComparer(CalculateCentre(coords)));
            var first = coords.First();

            coords.Add(new Coordinate(first.X, first.Y));
            var sequence = new CoordinateArraySequence(coords.ToArray());
            var poly     = new Polygon(
                new LinearRing(sequence, geomFactory),
                geomFactory);

            // Reverse if this is counter clock-wise
            if (poly.Shell.IsCCW)
            {
                poly.Shell.Reverse();
            }
            return(poly);
        }
Example #31
0
 /**
  * See {@link SpatialContext#SpatialContext(com.spatial4j.core.distance.DistanceUnits, com.spatial4j.core.distance.DistanceCalculator, com.spatial4j.core.shape.Rectangle)}.
  *
  * @param geometryFactory optional
  */
 public NtsSpatialContext(GeometryFactory geometryFactory, bool geo, DistanceCalculator calculator, Rectangle worldBounds)
     : base(geo, calculator, worldBounds)
 {
     this.geometryFactory = geometryFactory ?? new GeometryFactory();
 }
        public void ReadShapeAtIndex_SendNegativeIndex_ShouldThrowException()
        {
            // Arrange.
            m_TmpFile = new TempFileWriter("shape.shp", ShpFiles.Read("UnifiedChecksMaterial"));
            m_Reader = new IO.ShapeFile.Extended.ShapeReader(m_TmpFile.Path);
            IGeometryFactory factory = new GeometryFactory();

            // Act.
            m_Reader.ReadShapeAtIndex(-1, factory);
        }
        public void ReadAllShapes_TryReadAfterDisposed_ShouldThrowException()
        {
            // Arrange.
            m_TmpFile = new TempFileWriter("shape.shp", ShpFiles.Read("UnifiedChecksMaterial"));
            m_Reader = new IO.ShapeFile.Extended.ShapeReader(m_TmpFile.Path);
            IGeometryFactory factory = new GeometryFactory();

            // Act.
            m_Reader.Dispose();
            m_Reader.ReadAllShapes(factory);
        }
Example #34
0
        private void LoadParcels(List <PointD> pt, Color color, string labelname)
        {
            SharpMap.Map map = new SharpMap.Map();
            List <GeoAPI.Geometries.Coordinate> vertices = new List <GeoAPI.Geometries.Coordinate>();


            foreach (PointD i in pt)
            {
                GeoAPI.Geometries.Coordinate p = new GeoAPI.Geometries.Coordinate();
                p.X = i.X;
                p.Y = i.Y;
                vertices.Add(p);
            }
            GeoAPI.Geometries.Coordinate l = new GeoAPI.Geometries.Coordinate();
            l.X = pt[0].X;
            l.Y = pt[0].Y;
            vertices.Add(l);

            //Collection<GeoAPI.Geometries.IGeometry> geom = new Collection<GeoAPI.Geometries.IGeometry>();



            GeometryFactory gf = new NetTopologySuite.Geometries.GeometryFactory();

            GeoAPI.Geometries.ILinearRing shell = gf.CreateLinearRing(vertices.ToArray());

            GeoAPI.Geometries.IPolygon polygon = gf.CreatePolygon(shell, null);


            SharpMap.Data.Providers.GeometryProvider geomProvider = new SharpMap.Data.Providers.GeometryProvider(polygon);

            SharpMap.Layers.VectorLayer layerParcels = new SharpMap.Layers.VectorLayer("Parcels");

            SharpMap.Styles.VectorStyle style = new SharpMap.Styles.VectorStyle();



            style.Fill    = new SolidBrush(Color.FromArgb(200, color));
            style.Outline = new Pen(new SolidBrush(color));

            layerParcels.Style = style;
            layerParcels.Style.EnableOutline = true;


            layerParcels.DataSource    = geomProvider;
            layerParcels.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

            mapBox1.ActiveTool = SharpMap.Forms.MapBox.Tools.Pan;

            var fdt = new SharpMap.Data.FeatureDataTable();

            fdt.Columns.Add(new System.Data.DataColumn("id", typeof(uint)));
            fdt.Columns.Add(new System.Data.DataColumn("label", typeof(string)));
            var fdr = (SharpMap.Data.FeatureDataRow)fdt.NewRow();

            fdr.ItemArray = new object[] { 1, labelname };
            fdr.Geometry  = polygon;
            fdt.AddRow(fdr);

            var dataprovider = new SharpMap.Data.Providers.GeometryFeatureProvider(fdt);

            var ll = new SharpMap.Layers.LabelLayer("llayer");

            ll.DataSource  = dataprovider;
            ll.LabelColumn = "label";
            ll.Style.Font  = new Font("Eurostile Extended", 16, FontStyle.Bold);



            mapBox1.Map.Layers.Add(layerParcels);
            mapBox1.Map.Layers.Add(ll);



            mapBox1.Map.ZoomToExtents();
            mapBox1.Refresh();
        }
        public List <Object> CalculateDataTable(string polyfile)
        {
            //List<GeoAPI.Geometries.IGeometry> polys = new List<GeoAPI.Geometries.IGeometry>();
            List <GeoAPI.Geometries.IGeometry> squares = new List <GeoAPI.Geometries.IGeometry>();
            ArrayList     polys       = new ArrayList();
            List <Object> infoTable   = new List <Object>();
            double        squareArea  = 0;//0.015625;
            double        gridArea    = 0;
            double        polygonArea = 0;
            string        catchmentID = "";

            //////////////
            string gridfile = @"M:\DotSpatTopology\tests\NLDAS_Grid_Reference.shp";//"";
            string gridproj = @"M:\DotSpatTopology\tests\NLDAS_Grid_Reference.prj";
            //////////////

            Guid   gid       = Guid.NewGuid();
            string directory = @"M:\\TransientStorage\\" + gid.ToString() + "\\";


            //This block is for getting and setting shapefiles for NLDAS Grid

            /**
             * client.DownloadFile("https://ldas.gsfc.nasa.gov/nldas/gis/NLDAS_Grid_Reference.zip", @"M:\\TransientStorage\\NLDAS.zip");
             * ZipFile.ExtractToDirectory(@"M:\\TransientStorage\\NLDAS.zip", @"M:\\TransientStorage\\NLDAS");
             * unzippedLocation = (@"M:\\TransientStorage\\NLDAS");
             * foreach (string file in Directory.GetFiles(unzippedLocation))
             * {
             *  if (Path.GetExtension(file).Equals(".shp"))
             *  {
             *      gridfile = file;
             *  }
             *  else if (Path.GetExtension(file).Equals(".prj"))
             *  {
             *      gridproj = file;
             *  }
             * }
             * client.Dispose();**/


            ShapefileDataReader reader2 = new ShapefileDataReader(gridfile, NetTopologySuite.Geometries.GeometryFactory.Default);

            while (reader2.Read())
            {
                squares.Add(reader2.Geometry);
                gridArea += reader2.Geometry.Area;
            }

            reader2.Dispose();



            //if (polyfile.StartsWith(@"{""type"": ""FeatureCollection"""))
            if (polyfile.StartsWith(@"{""type"":"))//.geojson
            {
                Boolean  version1      = true;
                string[] featureParams = new string[3];
                string   jsonfile      = polyfile;
                var      readera       = new NetTopologySuite.IO.GeoJsonReader();
                NetTopologySuite.Features.FeatureCollection result = readera.Read <NetTopologySuite.Features.FeatureCollection>(jsonfile);
                if (result[0].Attributes.GetNames().Contains("HUC_8"))
                {
                    version1         = false;
                    featureParams[0] = "OBJECTID";
                    featureParams[1] = "HUC_8";
                    featureParams[2] = "HUC_12";
                }
                else if (result[0].Attributes.GetNames().Contains("HUC8"))
                {
                    version1         = true;
                    featureParams[0] = "COMID";
                    featureParams[1] = "HUC8";
                    featureParams[2] = "HUC12";
                }
                else
                {
                    version1         = false;
                    featureParams[0] = null;
                    featureParams[1] = null;
                    featureParams[2] = null;
                }


                List <Object> huc8Table = new List <Object>();
                huc8Table.Add(new KeyValuePair <string, string>("HUC 8 ID: ", result[0].Attributes[featureParams[1]].ToString()));

                for (int i = 0; i < result.Count; i++)
                {
                    List <Object> huc12Table = new List <Object>();
                    if (version1)
                    {
                        huc12Table.Add(new KeyValuePair <string, string>("HUC 12 ID: ", null));
                    }
                    else
                    {
                        huc12Table.Add(new KeyValuePair <string, string>("HUC 12 ID: ", result[i].Attributes["HUC_12"].ToString()));
                    }

                    catchmentID = result[i].Attributes[featureParams[0]].ToString();
                    huc12Table.Add(new KeyValuePair <string, string>("Catchment ID: ", catchmentID));
                    foreach (GeoAPI.Geometries.IGeometry s in squares)
                    {
                        double interArea = 0.0;
                        squareArea = s.Area;
                        if (result[i].Geometry.Intersects(s))
                        {
                            GeoAPI.Geometries.IGeometry intersection = result[i].Geometry.Intersection(s);
                            interArea += intersection.Area;
                            double percent2 = (interArea / squareArea) * 100;
                            Dictionary <string, string> catchTable = new Dictionary <string, string>();
                            //catchTable.Add("catchmentID", catchmentID);
                            catchTable.Add("latitude", s.Centroid.X.ToString());
                            catchTable.Add("longitude", s.Centroid.Y.ToString());
                            catchTable.Add("cellArea", squareArea.ToString());
                            catchTable.Add("containedArea", interArea.ToString());
                            catchTable.Add("percentArea", percent2.ToString());
                            huc12Table.Add(catchTable);
                        }
                    }
                    huc8Table.Add(huc12Table);
                }
                infoTable.Add(huc8Table);
            }
            else                                                    //Huc ID
            {
                catchmentID = polyfile;
                string ending = polyfile + ".zip";

                WebClient     client = new WebClient();
                DirectoryInfo di     = Directory.CreateDirectory(directory);
                client.DownloadFile("ftp://newftp.epa.gov/exposure/NHDV1/HUC12_Boundries/" + ending, directory + ending);

                string projfile = "";
                string dataFile = "";

                ZipFile.ExtractToDirectory(directory + ending, directory + polyfile);
                string unzippedLocation = (directory + polyfile + "\\" + polyfile); //+ "\\NHDPlus" + polyfile + "\\Drainage");
                foreach (string file in Directory.GetFiles(unzippedLocation))
                {
                    if (Path.GetExtension(file).Equals(".shp"))
                    {
                        polyfile = file;
                    }
                    else if (Path.GetExtension(file).Equals(".prj"))
                    {
                        projfile = file;
                    }
                    else if (Path.GetExtension(file).Equals(".dbf"))
                    {
                        dataFile = file;
                    }
                }

                //This block is for setting projection parameters of input shapefile and projecting it to NLDAS grid
                //Reprojecting of coordinates is not needed for NHDPlus V2

                string   line       = System.IO.File.ReadAllText(projfile);
                string[] projParams = { "PARAMETER", @"PARAMETER[""latitude_Of_origin"",0]," };//@"PARAMETER[""false_easting"",0],", @"PARAMETER[""false_northing"",0],", @"PARAMETER[""central_meridian"",0],", @"PARAMETER[""standard_parallel_1"",0],", @"PARAMETER[""standard_parallel_2"",0],", @"PARAMETER[""latitude_Of_origin"",0]," };
                int      ptr        = 0;
                foreach (string x in projParams)
                {
                    if (line.Contains(x))
                    {
                        ptr = line.IndexOf(x);
                    }
                    else if (!line.Contains(x) && !x.Equals("PARAMETER"))
                    {
                        line = line.Insert(ptr, x);
                    }
                }
                string line2 = System.IO.File.ReadAllText(gridproj);

                IProjectedCoordinateSystem  pcs = CoordinateSystemWktReader.Parse(line) as IProjectedCoordinateSystem;
                IGeographicCoordinateSystem gcs = GeographicCoordinateSystem.WGS84 as IGeographicCoordinateSystem;

                CoordinateTransformationFactory ctfac       = new CoordinateTransformationFactory();
                ICoordinateTransformation       transformTo = ctfac.CreateFromCoordinateSystems(pcs, gcs);
                IMathTransform inverseTransformTo           = transformTo.MathTransform;


                //Read geometries from both shapefiles and store in array lists
                //As well as calculate shapefile areas ahead of time
                ShapefileDataReader reader = new ShapefileDataReader(polyfile, NetTopologySuite.Geometries.GeometryFactory.Default);
                while (reader.Read())
                {
                    //Reprojection not needed for NHDPLUSV2
                    CoordinateList cordlist = new CoordinateList();
                    foreach (Coordinate coord in reader.Geometry.Coordinates)
                    {
                        double[] newCoord = { coord.X, coord.Y };
                        newCoord = inverseTransformTo.Transform(newCoord);
                        Coordinate newpt = new Coordinate(newCoord[0], newCoord[1]);
                        cordlist.Add(newpt);
                    }
                    Coordinate[]     listofpts  = cordlist.ToCoordinateArray();
                    IGeometryFactory geoFactory = new NetTopologySuite.Geometries.GeometryFactory();
                    NetTopologySuite.Geometries.LinearRing linear = (NetTopologySuite.Geometries.LinearRing) new GeometryFactory().CreateLinearRing(listofpts);
                    Polygon projPoly = new Polygon(linear, null, geoFactory);

                    polys.Add(projPoly);
                    polygonArea += projPoly.Area;
                }
                reader.Dispose();

                List <Object> huc8Table = new List <Object>();
                huc8Table.Add(new KeyValuePair <string, string>("HUC 8 ID: ", catchmentID));

                foreach (Polygon p in polys)
                {
                    List <Object> huc12Table = new List <Object>();
                    huc12Table.Add(new KeyValuePair <string, string>("HUC 12 ID: ", null));
                    catchmentID = null;//result[i].Attributes["OBJECTID"].ToString();
                    huc12Table.Add(new KeyValuePair <string, string>("Catchment ID: ", catchmentID));
                    foreach (GeoAPI.Geometries.IGeometry s in squares)
                    {
                        double interArea = 0.0;
                        squareArea = s.Area;
                        if (p.Intersects(s))
                        {
                            GeoAPI.Geometries.IGeometry intersection = p.Intersection(s);
                            interArea += intersection.Area;
                            double percent2 = (interArea / squareArea) * 100;
                            Dictionary <string, string> catchTable = new Dictionary <string, string>();
                            //catchTable.Add("catchmentID", catchmentID);
                            catchTable.Add("latitude", s.Centroid.X.ToString());
                            catchTable.Add("longitude", s.Centroid.Y.ToString());
                            catchTable.Add("cellArea", squareArea.ToString());
                            catchTable.Add("containedArea", interArea.ToString());
                            catchTable.Add("percentArea", percent2.ToString());
                            huc12Table.Add(catchTable);
                        }
                    }
                    huc8Table.Add(huc12Table);
                }
                infoTable.Add(huc8Table);
            }

            //System.IO.DirectoryInfo del = new DirectoryInfo(directory);

            /*
             * foreach (FileInfo file in del.GetFiles())
             * {
             *  file.Delete();
             * }
             * foreach (DirectoryInfo dir in del.GetDirectories())
             * {
             *  dir.Delete(true);
             * }*/
            //del.Delete(true);
            /////
            //infoTable.Add(new List<Object>() { elapsedTime, elapsedTime, elapsedTime, elapsedTime });
            //////

            return(infoTable);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="NtsProvider"/> class
 /// using the given <paramref name="precisionModel"/>.
 /// </summary>
 /// <param name="precisionModel">
 /// The <see cref="NetTopologySuite.Geometries.PrecisionModel"/>
 /// to use for define the precision of the geometry operations.
 /// </param>
 /// <seealso cref="PrecisionModels"/>
 /// <seealso cref="NetTopologySuite.Geometries.GeometryFactory"/>
 protected internal NtsProvider(NetTopologySuite.Geometries.PrecisionModel precisionModel)
 {
     geometryFactory = new NetTopologySuite.Geometries.GeometryFactory(precisionModel);
 }
Example #37
0
 /// <summary>
 /// Constructs a <c>MultiPoint</c>.
 /// </summary>
 /// <param name="points">
 /// The <c>Point</c>s for this <c>MultiPoint</c>
 /// , or <c>null</c> or an empty array to create the empty point.
 /// Elements may be empty <c>Point</c>s, but not <c>null</c>s.
 /// </param>
 /// <param name="factory"></param>
 public MultiPoint(Point[] points, GeometryFactory factory) : base(points, factory)
 {
 }
Example #38
0
        public List <Object> CalculateDataTable(string polyfile)
        {
            //Calling EPA WATERS:
            //https://ofmpub.epa.gov/waters10/SpatialAssignment.Service?pGeometry=POINT(-76.7498+37.5)&pLayer=NHDPLUS_CATCHMENT&pAssignmentHint=9894716&pReturnGeometry=TRUE
            //List<GeoAPI.Geometries.IGeometry> polys = new List<GeoAPI.Geometries.IGeometry>();
            List <GeoAPI.Geometries.IGeometry> squares = new List <GeoAPI.Geometries.IGeometry>();
            ArrayList     polys       = new ArrayList();
            ArrayList     polyfeats   = new ArrayList();
            List <Object> infoTable   = new List <Object>();
            double        squareArea  = 0;//0.015625;
            double        gridArea    = 0;
            double        polygonArea = 0;
            string        catchmentID = "";


            //////////////
            string gridfile = @"M:\DotSpatTopology\tests\NLDAS_Grid_Reference.shp";//"";
            string gridproj = @"M:\DotSpatTopology\tests\NLDAS_Grid_Reference.prj";
            //////////////

            Guid   gid       = Guid.NewGuid();
            string directory = @"M:\\TransientStorage\\" + gid.ToString() + "\\";


            //This block is for getting and setting shapefiles for NLDAS Grid

            /**
             * client.DownloadFile("https://ldas.gsfc.nasa.gov/nldas/gis/NLDAS_Grid_Reference.zip", @"M:\\TransientStorage\\NLDAS.zip");
             * ZipFile.ExtractToDirectory(@"M:\\TransientStorage\\NLDAS.zip", @"M:\\TransientStorage\\NLDAS");
             * unzippedLocation = (@"M:\\TransientStorage\\NLDAS");
             * foreach (string file in Directory.GetFiles(unzippedLocation))
             * {
             *  if (Path.GetExtension(file).Equals(".shp"))
             *  {
             *      gridfile = file;
             *  }
             *  else if (Path.GetExtension(file).Equals(".prj"))
             *  {
             *      gridproj = file;
             *  }
             * }
             * client.Dispose();**/


            ShapefileDataReader reader2 = new ShapefileDataReader(gridfile, NetTopologySuite.Geometries.GeometryFactory.Default);

            while (reader2.Read())
            {
                squares.Add(reader2.Geometry);
                gridArea += reader2.Geometry.Area;
            }

            reader2.Dispose();



            //if (polyfile.StartsWith(@"{""type"": ""FeatureCollection"""))
            if (polyfile.StartsWith(@"{""type"":"))//.geojson
            {
                Boolean  version1      = true;
                string[] featureParams = new string[3];
                string   jsonfile      = polyfile;
                var      readera       = new NetTopologySuite.IO.GeoJsonReader();
                NetTopologySuite.Features.FeatureCollection result = readera.Read <NetTopologySuite.Features.FeatureCollection>(jsonfile);
                if (result[0].Attributes.GetNames().Contains("HUC_8"))
                {
                    version1         = false;
                    featureParams[0] = "OBJECTID";
                    featureParams[1] = "HUC_8";
                    featureParams[2] = "HUC_12";
                }
                else if (result[0].Attributes.GetNames().Contains("HUC8"))
                {
                    version1         = true;
                    featureParams[0] = "COMID";
                    featureParams[1] = "HUC8";
                    featureParams[2] = "HUC12";
                }
                else
                {
                    version1         = false;
                    featureParams[0] = null;
                    featureParams[1] = null;
                    featureParams[2] = null;
                }


                List <Object> huc8Table        = new List <Object>();
                Dictionary <string, string> h8 = new Dictionary <string, string>();
                h8.Add("HUC 8 ID: ", result[0].Attributes[featureParams[1]].ToString());
                huc8Table.Add(h8);
                //huc8Table.Add(new KeyValuePair<string, string>("HUC 8 ID: ", result[0].Attributes[featureParams[1]].ToString()));

                for (int i = 0; i < result.Count; i++)
                {
                    List <Object> huc12Table = new List <Object>();
                    if (version1)
                    {
                        huc12Table.Add(new KeyValuePair <string, string>("HUC 12 ID: ", null));
                    }
                    else
                    {
                        Dictionary <string, string> h12 = new Dictionary <string, string>();
                        h12.Add("HUC 12 ID: ", result[i].Attributes["HUC_12"].ToString());
                        huc12Table.Add(h12);
                        //huc12Table.Add(new KeyValuePair<string, string>("HUC 12 ID: ", result[i].Attributes["HUC_12"].ToString()));
                    }

                    catchmentID = result[i].Attributes[featureParams[0]].ToString();
                    Dictionary <string, string> cm = new Dictionary <string, string>();
                    cm.Add("Catchment ID: ", catchmentID);
                    huc12Table.Add(cm);
                    //huc12Table.Add(new KeyValuePair<string, string>("Catchment ID: ", catchmentID));
                    foreach (GeoAPI.Geometries.IGeometry s in squares)
                    {
                        double interArea = 0.0;
                        squareArea = s.Area;
                        if (result[i].Geometry.Intersects(s))
                        {
                            GeoAPI.Geometries.IGeometry intersection = result[i].Geometry.Intersection(s);
                            interArea += intersection.Area;
                            double percent2 = (interArea / squareArea) * 100;
                            Dictionary <string, string> catchTable = new Dictionary <string, string>();
                            //catchTable.Add("catchmentID", catchmentID);
                            catchTable.Add("latitude", s.Centroid.X.ToString());
                            catchTable.Add("longitude", s.Centroid.Y.ToString());
                            catchTable.Add("cellArea", squareArea.ToString());
                            catchTable.Add("containedArea", interArea.ToString());
                            catchTable.Add("percentArea", percent2.ToString());
                            huc12Table.Add(catchTable);
                        }
                    }
                    huc8Table.Add(huc12Table);
                }
                infoTable.Add(huc8Table);
            }
            else                                                    //Huc ID
            {
                catchmentID = polyfile;
                string ending = polyfile + ".zip";

                WebClient     client = new WebClient();
                DirectoryInfo di     = Directory.CreateDirectory(directory);
                client.DownloadFile("ftp://newftp.epa.gov/exposure/NHDV1/HUC12_Boundries/" + ending, directory + ending);

                string projfile = "";
                string dataFile = "";

                ZipFile.ExtractToDirectory(directory + ending, directory + polyfile);
                string unzippedLocation = (directory + polyfile + "\\" + polyfile); //+ "\\NHDPlus" + polyfile + "\\Drainage");
                foreach (string file in Directory.GetFiles(unzippedLocation))
                {
                    if (Path.GetExtension(file).Equals(".shp"))
                    {
                        polyfile = file;
                    }
                    else if (Path.GetExtension(file).Equals(".prj"))
                    {
                        projfile = file;
                    }
                    else if (Path.GetExtension(file).Equals(".dbf"))
                    {
                        dataFile = file;
                    }
                }

                //This block is for setting projection parameters of input shapefile and projecting it to NLDAS grid
                //Reprojecting of coordinates is not needed for NHDPlus V2
                string line = System.IO.File.ReadAllText(projfile);
                //string line = @"PROJCS[""unnamed"",GEOGCS[""unnamed ellipse"",DATUM[""unknown"",SPHEROID[""unnamed"",6378137,0]],PRIMEM[""Greenwich"",0],UNIT[""degree"",0.0174532925199433]],PROJECTION[""Mercator_2SP""],PARAMETER[""latitude_of_origin"",0],PARAMETER[""standard_parallel_1"",0],PARAMETER[""central_meridian"",0],PARAMETER[""false_easting"",0],PARAMETER[""false_northing"",0],UNIT[""Meter"",1]]";//System.IO.File.ReadAllText(projfile);

                string[] projParams = { "PARAMETER", @"PARAMETER[""latitude_of_origin"",0]," };//@"PARAMETER[""false_easting"",0],", @"PARAMETER[""false_northing"",0],", @"PARAMETER[""central_meridian"",0],", @"PARAMETER[""standard_parallel_1"",0],", @"PARAMETER[""standard_parallel_2"",0],", @"PARAMETER[""latitude_Of_origin"",0]," };

                int ptr = 0;
                foreach (string x in projParams)
                {
                    if (line.Contains(x))
                    {
                        ptr = line.IndexOf(x);
                    }
                    else if (!line.Contains(x) && !x.Equals("PARAMETER"))
                    {
                        line = line.Insert(ptr, x);
                    }
                }
                string line2 = System.IO.File.ReadAllText(gridproj);

                IProjectedCoordinateSystem  pcs = CoordinateSystemWktReader.Parse(line) as IProjectedCoordinateSystem;
                IGeographicCoordinateSystem gcs = GeographicCoordinateSystem.WGS84 as IGeographicCoordinateSystem;

                CoordinateTransformationFactory ctfac       = new CoordinateTransformationFactory();
                ICoordinateTransformation       transformTo = ctfac.CreateFromCoordinateSystems(pcs, gcs);
                IMathTransform inverseTransformTo           = transformTo.MathTransform;


                //Read geometries from both shapefiles and store in array lists

                ShapefileDataReader reader = new ShapefileDataReader(polyfile, NetTopologySuite.Geometries.GeometryFactory.Default);
                DbaseFileHeader     header = reader.DbaseHeader;
                string huc8 = "";
                while (reader.Read())
                {
                    //Reprojection not needed for NHDPLUSV2
                    CoordinateList cordlist = new CoordinateList();
                    foreach (Coordinate coord in reader.Geometry.Coordinates)
                    {
                        double[] newCoord = { coord.X, coord.Y };
                        newCoord = inverseTransformTo.Transform(newCoord);
                        Coordinate newpt = new Coordinate(newCoord[0], newCoord[1]);
                        cordlist.Add(newpt);
                    }
                    Coordinate[]     listofpts  = cordlist.ToCoordinateArray();
                    IGeometryFactory geoFactory = new NetTopologySuite.Geometries.GeometryFactory();
                    NetTopologySuite.Geometries.LinearRing linear = (NetTopologySuite.Geometries.LinearRing) new GeometryFactory().CreateLinearRing(listofpts);

                    Feature         feature         = new Feature();
                    AttributesTable attributesTable = new AttributesTable();
                    string[]        keys            = new string[header.NumFields];
                    IGeometry       geometry        = (Geometry)reader.Geometry;
                    for (int i = 0; i < header.NumFields; i++)
                    {
                        DbaseFieldDescriptor fldDescriptor = header.Fields[i];
                        keys[i] = fldDescriptor.Name;
                        attributesTable.AddAttribute(fldDescriptor.Name, reader.GetValue(i));
                    }
                    feature.Geometry   = geometry;
                    feature.Attributes = attributesTable;
                    polyfeats.Add(feature.Attributes);
                    huc8 = attributesTable.GetValues()[5].ToString();
                    Polygon projPoly = new Polygon(linear, null, geoFactory);
                    polys.Add(projPoly);
                    polygonArea += projPoly.Area;
                }
                reader.Dispose();

                List <Object> huc8Table        = new List <Object>();
                Dictionary <string, string> h8 = new Dictionary <string, string>();
                h8.Add("HUC 8 ID: ", catchmentID);
                huc8Table.Add(h8);

                int j = 0;
                foreach (Polygon p in polys)
                {
                    List <Object> huc12Table       = new List <Object>();
                    Dictionary <string, string> cm = new Dictionary <string, string>();
                    //
                    AttributesTable tab     = (AttributesTable)polyfeats[j];
                    object[]        valuesl = tab.GetValues();
                    cm.Add("HUC 12 ID: ", valuesl[17].ToString());
                    huc12Table.Add(cm);
                    //huc12Table.Add(new KeyValuePair<string, string>("HUC 12 ID: ", null));
                    catchmentID = null;//result[i].Attributes["OBJECTID"].ToString();

                    Dictionary <string, string> cm2 = new Dictionary <string, string>();
                    cm2.Add("Catchment ID: ", catchmentID);
                    huc12Table.Add(cm2);
                    //huc12Table.Add(new KeyValuePair<string, string>("Catchment ID: ", catchmentID));
                    foreach (GeoAPI.Geometries.IGeometry s in squares)
                    {
                        double interArea = 0.0;
                        squareArea = s.Area;
                        if (p.Intersects(s))
                        {
                            GeoAPI.Geometries.IGeometry intersection = p.Intersection(s);
                            interArea += intersection.Area;
                            double percent2 = (interArea / squareArea) * 100;
                            Dictionary <string, string> catchTable = new Dictionary <string, string>();
                            //catchTable.Add("catchmentID", catchmentID);
                            catchTable.Add("latitude", s.Centroid.X.ToString());
                            catchTable.Add("longitude", s.Centroid.Y.ToString());
                            catchTable.Add("cellArea", squareArea.ToString());
                            catchTable.Add("containedArea", interArea.ToString());
                            catchTable.Add("percentArea", percent2.ToString());
                            huc12Table.Add(catchTable);
                        }
                    }
                    huc8Table.Add(huc12Table);
                    j++;
                }
                infoTable.Add(huc8Table);
            }

            //System.IO.DirectoryInfo del = new DirectoryInfo(directory);

            /*
             * foreach (FileInfo file in del.GetFiles())
             * {
             *  file.Delete();
             * }
             * foreach (DirectoryInfo dir in del.GetDirectories())
             * {
             *  dir.Delete(true);
             * }*/
            //del.Delete(true);

            return(infoTable);
        }
Example #39
0
        /* BEGIN ADDED BY MPAUL42: monoGIS team */

        /// <summary>
        /// Constructs a <c>Polygon</c> with the given exterior boundary.
        /// </summary>
        /// <param name="shell">
        /// The outer boundary of the new <c>Polygon</c>,
        /// or <c>null</c> or an empty <c>LinearRing</c> if the empty
        /// polygon is to be created.
        /// </param>
        /// <param name="factory"></param>
        public Polygon(LinearRing shell, GeometryFactory factory) : this(shell, null, factory)
        {
        }
Example #40
0
 /// <summary>
 /// Constructs a <c>LinearRing</c> with the vertices specified
 /// by the given <see cref="CoordinateSequence"/>.
 /// </summary>
 /// <param name="points">A sequence points forming a closed and simple linestring,
 /// or <c>null</c> to create the empty geometry.</param>
 /// <param name="factory">The factory that creates this <c>LinearRing</c></param>
 /// <exception cref="ArgumentException">If the ring is not closed, or has too few points</exception>
 public LinearRing(CoordinateSequence points, GeometryFactory factory)
     : base(points, factory)
 {
     ValidateConstruction();
 }
Example #41
0
 /// <summary>
 /// Constructs a <c>MultiPolygon</c>.
 /// </summary>
 /// <param name="polygons">
 /// The <c>Polygon</c>s for this <c>MultiPolygon</c>
 /// , or <c>null</c> or an empty array to create the empty point.
 /// Elements may be empty <c>Polygon</c>s, but not <c>null</c>
 /// s. The polygons must conform to the assertions specified in the
 /// <see href="http://www.opengis.org/techno/specs.htm"/> OpenGIS Simple Features
 /// Specification for SQL.
 /// </param>
 /// <param name="factory"></param>
 public MultiPolygon(Polygon[] polygons, GeometryFactory factory) : base(polygons, factory)
 {
 }
        public void TestML()
        {
            {
                const double scale = 2.0E10;
                IPrecisionModel precisionModel = new PrecisionModel(scale);
                IGeometryFactory geometryFactory = new GeometryFactory(precisionModel);

                var reader = new WKTReader(geometryFactory);
                var lineStringA = (ILineString)
                    reader.Read("LINESTRING (-93.40178610435 -235.5437531975, -401.24229900825 403.69365857925)");
                var lineStringB = (ILineString)
                    reader.Read("LINESTRING (-50.0134121926 -145.44686640725, -357.8539250965 493.7905453695)");
                var lineStringC = (ILineString)
                    reader.Read("LINESTRING (-193.8964147753 -30.64653554935, -186.68866383205 -34.1176054623)");

                var middlePoint = (IPoint) reader.Read("POINT (-203.93366864454998 174.171839481125)");

                var lineStrings = new List<ILineString>();
                lineStrings.Add(lineStringA);
                lineStrings.Add(lineStringB);
                lineStrings.Add(lineStringC);

                var noder = new GeometryNoder(geometryFactory.PrecisionModel);
                var nodedLineStrings = noder.Node(lineStrings.ToArray());

                var shortestDistanceToPointBeforeNoding = double.MaxValue;

                foreach (var lineString in lineStrings)
                {
                    shortestDistanceToPointBeforeNoding = Math.Min(lineString.Distance(middlePoint),
                                                                   shortestDistanceToPointBeforeNoding);
                }

                var shortestDistanceToPointAfterNoding = Double.MaxValue;

                foreach (var lineString in nodedLineStrings)
                {
                    shortestDistanceToPointAfterNoding = Math.Min(lineString.Distance(middlePoint),
                                                                  shortestDistanceToPointAfterNoding);
                }

                var difference = Math.Abs(shortestDistanceToPointAfterNoding - shortestDistanceToPointBeforeNoding);


                Console.WriteLine("Scale: {0}", scale);
                Console.WriteLine("Distance to point before noding: {0}", shortestDistanceToPointBeforeNoding);
                Console.WriteLine("Distance to point after noding:  {0}", shortestDistanceToPointAfterNoding);
                Console.WriteLine("Difference is {0} and should be lesser than {1}", difference, 1.0/scale);

                const double roughTolerance = 10.0;
                Assert.IsTrue(difference < roughTolerance, "this difference should should be lesser than " + 1.0/scale);

            }
        }
Example #43
0
        public static System.Collections.Generic.List <OSM.API.v0_6.GeoPoint> GetUnionPolygon(
            System.Collections.Generic.IEnumerable <System.Collections.Generic.IEnumerable <OSM.API.v0_6.GeoPoint> > polygons)
        {
            NetTopologySuite.Geometries.GeometryFactory geomFactory = new NetTopologySuite.Geometries.GeometryFactory();


            System.Collections.Generic.List <NetTopologySuite.Geometries.Geometry> lsPolygons =
                new System.Collections.Generic.List <NetTopologySuite.Geometries.Geometry>();

            foreach (System.Collections.Generic.IEnumerable <OSM.API.v0_6.GeoPoint> coords in polygons)
            {
                NetTopologySuite.Geometries.Polygon poly = geomFactory.CreatePolygon(ToNetTopologyCoordinates(coords));
                lsPolygons.Add(poly);
            }


            NetTopologySuite.Geometries.Geometry ig = NetTopologySuite.Operation.Union.CascadedPolygonUnion.Union(lsPolygons);
            System.Console.WriteLine(ig.GetType().FullName);



            if (ig is NetTopologySuite.Geometries.Polygon)
            {
                System.Console.WriteLine("mulip");
                goto SIMPLIFY_POLYGON_AND_GET_UNION;
            }


            if (!(ig is NetTopologySuite.Geometries.MultiPolygon))
            {
                System.Console.WriteLine("Error: Geometry is not a multipolygon!");
                throw new System.InvalidOperationException("Geometry is not a multipolygon");
            }


            NetTopologySuite.Geometries.MultiPolygon lalala = (NetTopologySuite.Geometries.MultiPolygon)ig;

            // var convaveHull = ConcaveHull.Init.foo(lalala.Coordinates);
            // convaveHull = ToCounterClockWise(convaveHull);
            // return convaveHull;



            // var cc = new NetTopologySuite.Hull.ConcaveHull(ig, 0);
            // var cc = new NetTopologySuite.Hull.ConcaveHull(ig, 0.00049);
            var cc = new NetTopologySuite.Hull.ConcaveHull(ig, 0.00001);

            ig = cc.GetConcaveHull;

SIMPLIFY_POLYGON_AND_GET_UNION:

            ig = NetTopologySuite.Simplify.DouglasPeuckerSimplifier.Simplify(ig, 0.00001);
            NetTopologySuite.Geometries.Polygon unionPolygon = (NetTopologySuite.Geometries.Polygon)ig;



            System.Console.WriteLine(unionPolygon.Shell.Coordinates);



            System.Collections.Generic.List <OSM.API.v0_6.GeoPoint> lsUnionPolygonPoints = new System.Collections.Generic.List <OSM.API.v0_6.GeoPoint>();

            for (int i = 0; i < unionPolygon.Shell.Coordinates.Length; ++i)
            {
                lsUnionPolygonPoints.Add(new OSM.API.v0_6.GeoPoint(unionPolygon.Shell.Coordinates[i].X, unionPolygon.Shell.Coordinates[i].Y));
            }

            lsUnionPolygonPoints = ToCounterClockWise(lsUnionPolygonPoints);

            return(lsUnionPolygonPoints);
        }
 private void ComputeConvexHull()
 {
     GeometryFactory fact = new GeometryFactory();
     Coordinate[] coords = GetPointArray();
     ConvexHull hull = new ConvexHull(coords, fact);
     _convexHull = hull.GetConvexHull();
 }
Example #45
0
 /// <summary>
 /// Constructs a <c>MultiLineString</c>.
 /// </summary>
 /// <param name="lineStrings">
 /// The <c>LineString</c>s for this <c>MultiLineString</c>,
 /// or <c>null</c> or an empty array to create the empty
 /// point. Elements may be empty <c>LineString</c>s,
 /// but not <c>null</c>s.
 /// </param>
 /// <param name="factory"></param>
 public MultiLineString(LineString[] lineStrings, GeometryFactory factory)
     : base(lineStrings, factory)
 {
 }