public void ParseAllWKTs()
        {
            CoordinateSystemFactory fac = new CoordinateSystemFactory();
            Int32        parsecount     = 0;
            StreamReader sr             = File.OpenText(@"SRID.csv");
            String       line           = "";

            while (!sr.EndOfStream)
            {
                line = sr.ReadLine();
                Int32 split = line.IndexOf(';');
                if (split > -1)
                {
                    String            srid = line.Substring(0, split);
                    String            wkt  = line.Substring(split + 1);
                    ICoordinateSystem cs   = CoordinateSystemWktReader.Parse(wkt) as ICoordinateSystem;
                    Assert.IsNotNull(cs, "Could not parse WKT: " + wkt);
                    parsecount++;
                }
            }
            sr.Close();
            Assert.AreEqual(parsecount, 2671, "Not all WKT was parsed");
        }
Example #2
0
        public static void Main(string[] args)
        {
            var nycBoroughs = Shapefile.OpenFile(@"C:\NYC Shape\nybb_13a\nybb.shp");
            var wktstring   = "PROJCS[\"NAD_1983_StatePlane_New_York_Long_Island_FIPS_3104_Feet\",GEOGCS[\"GCS_North_American_1983\",DATUM[\"D_North_American_1983\",SPHEROID[\"GRS_1980\",6378137.0,298.257222101]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Lambert_Conformal_Conic\"],PARAMETER[\"False_Easting\",984250.0],PARAMETER[\"False_Northing\",0.0],PARAMETER[\"Central_Meridian\",-74.0],PARAMETER[\"Standard_Parallel_1\",40.66666666666666],PARAMETER[\"Standard_Parallel_2\",41.03333333333333],PARAMETER[\"Latitude_Of_Origin\",40.16666666666666],UNIT[\"Foot_US\",0.3048006096012192]]";

            var latlongwkt = "GEOGCS [\"Longitude / Latitude (NAD 83)\",DATUM [\"NAD 83\",SPHEROID [\"GRS 80\",6378137,298.257222101]],PRIMEM [\"Greenwich\",0.000000],UNIT [\"Decimal Degree\",0.01745329251994330]]";
            var csvFile    = @"C:\NYC Shape\studylatlong.csv";
            var targetFile = @"C:\NYC Shape\nycstudieslatlong.csv";

            var studyData = new List <StudyInfo>();

            using (StreamReader sr = new StreamReader(csvFile))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    var tokens = line.Split(',');
                    var study  = StudyInfo.CreateFromStrings(tokens);
                    if (study.Latitude < 40 || study.Latitude > 42 ||
                        study.Longitude < -75 || study.Longitude > -70)
                    {
                    }
                    else
                    {
                        studyData.Add(StudyInfo.CreateFromStrings(tokens));
                    }
                }
                Console.WriteLine("# of Studies: " + studyData.Count());
            }

            ICoordinateSystem nycCS =
                CoordinateSystemWktReader.Parse(wktstring) as ICoordinateSystem;

            ICoordinateSystem baseCS =
                CoordinateSystemWktReader.Parse(latlongwkt) as ICoordinateSystem;

            var ctFactory = new CoordinateTransformationFactory();
            // Transform lat/long points into NYC UTM.
            var transformer = ctFactory.CreateFromCoordinateSystems(baseCS, nycCS);

            var nycStudies = new List <StudyInfo>();

            foreach (var study in studyData)
            {
                double[] fromPoint     = { study.Longitude, study.Latitude };
                double[] toPoint       = transformer.MathTransform.Transform(fromPoint);
                var      studyLocation = new Coordinate(toPoint[0], toPoint[1]);
                if (IsPointInShape(studyLocation, nycBoroughs.Features))
                {
                    nycStudies.Add(study);
                }
            }

            Console.WriteLine("# of NYC Studies: " + nycStudies.Count());

            using (StreamWriter sw = new StreamWriter(targetFile))
            {
                foreach (var study in nycStudies)
                {
                    sw.Write("" + study.StudyID);
                    sw.Write(",");
                }
                sw.WriteLine();
            }

            Console.WriteLine("Output written.");
            Console.ReadLine();
        }
Example #3
0
        /// <summary>
        /// Creates a spatial reference object given its Well-known text representation.
        /// The output object may be either a <see cref="IGeographicCoordinateSystem"/> or
        /// a <see cref="IProjectedCoordinateSystem"/>.
        /// </summary>
        /// <param name="WKT">The Well-known text representation for the spatial reference</param>
        /// <returns>The resulting spatial reference object</returns>
        public ICoordinateSystem CreateFromWkt(string WKT)
        {
            IInfo info = CoordinateSystemWktReader.Parse(WKT, Encoding);

            return(info as ICoordinateSystem);
        }
        public void ParseCoordSys()
        {
            CoordinateSystemFactory fac = new CoordinateSystemFactory();
            string wkt = "PROJCS[\"NAD83(HARN) / Texas Central (ftUS)\", GEOGCS[\"NAD83(HARN)\", DATUM[\"NAD83_High_Accuracy_Regional_Network\", SPHEROID[\"GRS 1980\", 6378137, 298.257222101, AUTHORITY[\"EPSG\", \"7019\"]], TOWGS84[725, 685, 536, 0, 0, 0, 0], AUTHORITY[\"EPSG\", \"6152\"]], PRIMEM[\"Greenwich\", 0, AUTHORITY[\"EPSG\", \"8901\"]], UNIT[\"degree\", 0.0174532925199433, AUTHORITY[\"EPSG\", \"9122\"]], AUTHORITY[\"EPSG\", \"4152\"]], PROJECTION[\"Lambert_Conformal_Conic_2SP\"], PARAMETER[\"standard_parallel_1\", 31.883333333333], PARAMETER[\"standard_parallel_2\", 30.1166666667], PARAMETER[\"latitude_of_origin\", 29.6666666667], PARAMETER[\"central_meridian\", -100.333333333333], PARAMETER[\"false_easting\", 2296583.333], PARAMETER[\"false_northing\", 9842500], UNIT[\"US survey foot\", 0.304800609601219, AUTHORITY[\"EPSG\", \"9003\"]], AUTHORITY[\"EPSG\", \"2918\"]]";
            ProjectedCoordinateSystem pcs = CoordinateSystemWktReader.Parse(wkt) as ProjectedCoordinateSystem;

            Assert.IsNotNull(pcs, "Could not parse WKT: " + wkt);

            Assert.AreEqual("NAD83(HARN) / Texas Central (ftUS)", pcs.Name);
            Assert.AreEqual("NAD83(HARN)", pcs.GeographicCoordinateSystem.Name);
            Assert.AreEqual("NAD83_High_Accuracy_Regional_Network", pcs.GeographicCoordinateSystem.HorizontalDatum.Name);
            Assert.AreEqual("GRS 1980", pcs.GeographicCoordinateSystem.HorizontalDatum.Ellipsoid.Name);
            Assert.AreEqual(6378137, pcs.GeographicCoordinateSystem.HorizontalDatum.Ellipsoid.SemiMajorAxis);
            Assert.AreEqual(298.257222101, pcs.GeographicCoordinateSystem.HorizontalDatum.Ellipsoid.InverseFlattening);
            Assert.AreEqual("EPSG", pcs.GeographicCoordinateSystem.HorizontalDatum.Ellipsoid.Authority);
            Assert.AreEqual(7019, pcs.GeographicCoordinateSystem.HorizontalDatum.Ellipsoid.AuthorityCode);
            Assert.AreEqual("EPSG", pcs.GeographicCoordinateSystem.HorizontalDatum.Authority);
            Assert.AreEqual(6152, pcs.GeographicCoordinateSystem.HorizontalDatum.AuthorityCode);
            Assert.AreEqual(new Wgs84ConversionInfo(725, 685, 536, 0, 0, 0, 0), pcs.GeographicCoordinateSystem.HorizontalDatum.Wgs84Parameters);
            Assert.AreEqual("Greenwich", pcs.GeographicCoordinateSystem.PrimeMeridian.Name);
            Assert.AreEqual(0, pcs.GeographicCoordinateSystem.PrimeMeridian.Longitude);
            Assert.AreEqual("EPSG", pcs.GeographicCoordinateSystem.PrimeMeridian.Authority);
            Assert.AreEqual(8901, pcs.GeographicCoordinateSystem.PrimeMeridian.AuthorityCode, 8901);
            Assert.AreEqual("degree", pcs.GeographicCoordinateSystem.AngularUnit.Name);
            Assert.AreEqual(0.0174532925199433, pcs.GeographicCoordinateSystem.AngularUnit.RadiansPerUnit);
            Assert.AreEqual("EPSG", pcs.GeographicCoordinateSystem.AngularUnit.Authority);
            Assert.AreEqual(9122, pcs.GeographicCoordinateSystem.AngularUnit.AuthorityCode);
            Assert.AreEqual("EPSG", pcs.GeographicCoordinateSystem.Authority);
            Assert.AreEqual(4152, pcs.GeographicCoordinateSystem.AuthorityCode, 4152);
            Assert.AreEqual("Lambert_Conformal_Conic_2SP", pcs.Projection.ClassName, "Projection Classname");

            ProjectionParameter latitude_of_origin = pcs.Projection.GetParameter("latitude_of_origin");

            Assert.IsNotNull(latitude_of_origin);
            Assert.AreEqual(29.6666666667, latitude_of_origin.Value);
            ProjectionParameter central_meridian = pcs.Projection.GetParameter("central_meridian");

            Assert.IsNotNull(central_meridian);
            Assert.AreEqual(-100.333333333333, central_meridian.Value);
            ProjectionParameter standard_parallel_1 = pcs.Projection.GetParameter("standard_parallel_1");

            Assert.IsNotNull(standard_parallel_1);
            Assert.AreEqual(31.883333333333, standard_parallel_1.Value);
            ProjectionParameter standard_parallel_2 = pcs.Projection.GetParameter("standard_parallel_2");

            Assert.IsNotNull(standard_parallel_2);
            Assert.AreEqual(30.1166666667, standard_parallel_2.Value);
            ProjectionParameter false_easting = pcs.Projection.GetParameter("false_easting");

            Assert.IsNotNull(false_easting);
            Assert.AreEqual(2296583.333, false_easting.Value);
            ProjectionParameter false_northing = pcs.Projection.GetParameter("false_northing");

            Assert.IsNotNull(false_northing);
            Assert.AreEqual(9842500, false_northing.Value);

            Assert.AreEqual("US survey foot", pcs.LinearUnit.Name);
            Assert.AreEqual(0.304800609601219, pcs.LinearUnit.MetersPerUnit);
            Assert.AreEqual("EPSG", pcs.LinearUnit.Authority);
            Assert.AreEqual(9003, pcs.LinearUnit.AuthorityCode);
            Assert.AreEqual("EPSG", pcs.Authority);
            Assert.AreEqual(2918, pcs.AuthorityCode);
            Assert.AreEqual(wkt, pcs.WKT);
        }
Example #5
0
 /// <summary>
 /// Creates a spatial reference object given its Well-known text representation.
 /// The output object may be either a <see cref="IGeographicCoordinateSystem"/> or
 /// a <see cref="IProjectedCoordinateSystem"/>.
 /// </summary>
 /// <param name="WKT">The Well-known text representation for the spatial reference</param>
 /// <returns>The resulting spatial reference object</returns>
 public ICoordinateSystem CreateFromWkt(string WKT)
 {
     return(CoordinateSystemWktReader.Parse(WKT) as ICoordinateSystem);
 }
Example #6
0
 public void TestReadUnit1()
 {
     string       wkt         = "UNIT[\"degree\",0.01745329251994433,AUTHORITY[\"EPSG\",\"9102\"]]";
     IAngularUnit angularUnit = CoordinateSystemWktReader.Create(wkt) as IAngularUnit;
 }
Example #7
0
        public void TestTransformAllWKTs()
        {
            //GeographicCoordinateSystem.WGS84
            CoordinateTransformationFactory fact = new CoordinateTransformationFactory();
            CoordinateSystemFactory         fac  = new CoordinateSystemFactory();
            int          parsecount = 0;
            StreamReader sr         = File.OpenText(@"..\..\SRID.csv");
            string       line       = "";

            while (!sr.EndOfStream)
            {
                line = sr.ReadLine();
                int split = line.IndexOf(';');
                if (split > -1)
                {
                    string            srid = line.Substring(0, split);
                    string            wkt  = line.Substring(split + 1);
                    ICoordinateSystem cs   = CoordinateSystemWktReader.Parse(wkt) as ICoordinateSystem;
                    if (cs == null)
                    {
                        continue;                                 //We check this in another test.
                    }
                    if (cs is IProjectedCoordinateSystem)
                    {
                        switch ((cs as IProjectedCoordinateSystem).Projection.ClassName)
                        {
                        //Skip not supported projections
                        case "Oblique_Stereographic":
                        case "Transverse_Mercator_South_Orientated":
                        case "Hotine_Oblique_Mercator":
                        case "Lambert_Conformal_Conic_1SP":
                        case "Krovak":
                        case "Cassini_Soldner":
                        case "Lambert_Azimuthal_Equal_Area":
                        case "Tunisia_Mining_Grid":
                        case "New_Zealand_Map_Grid":
                        case "Polyconic":
                        case "Lambert_Conformal_Conic_2SP_Belgium":
                        case "Polar_Stereographic":
                            continue;

                        default: break;
                        }
                    }
                    try
                    {
                        ICoordinateTransformation trans = fact.CreateFromCoordinateSystems(GeographicCoordinateSystem.WGS84, cs);
                    }
                    catch (Exception ex)
                    {
                        if (cs is IProjectedCoordinateSystem)
                        {
                            Assert.Fail("Could not create transformation from:\r\n" + wkt + "\r\n" + ex.Message + "\r\nClass name:" + (cs as IProjectedCoordinateSystem).Projection.ClassName);
                        }
                        else
                        {
                            Assert.Fail("Could not create transformation from:\r\n" + wkt + "\r\n" + ex.Message);
                        }
                    }
                    parsecount++;
                }
            }
            sr.Close();
            Assert.AreEqual(parsecount, 2536, "Not all WKT was processed");
        }
Example #8
0
        /// <summary>
        /// Creates a spatial reference object given its Well-known text representation.
        /// The output object may be either a <see cref="GeographicCoordinateSystem"/> or
        /// a <see cref="ProjectedCoordinateSystem"/>.
        /// </summary>
        /// <param name="WKT">The Well-known text representation for the spatial reference</param>
        /// <returns>The resulting spatial reference object</returns>
        public CoordinateSystem CreateFromWkt(string WKT)
        {
            var info = CoordinateSystemWktReader.Parse(WKT);

            return(info as CoordinateSystem);
        }
Example #9
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);
        }
        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);
        }
Example #11
0
        private ICoordinateSystem GetCoordinateSystem(string CoordSysWKT)
        {
            ICoordinateSystem fromCS = CoordinateSystemWktReader.Parse(CoordSysWKT) as ICoordinateSystem;

            return(fromCS);
        }
Example #12
0
        public static ICoordinateSystem Read(string fileName, Encoding encoding = null)
        {
            string csStr = encoding == null?File.ReadAllText(fileName, Encoding.Default) : File.ReadAllText(fileName, encoding);

            var cs = (encoding == null ? CoordinateSystemWktReader.Parse(csStr, Encoding.Default) : CoordinateSystemWktReader.Parse(csStr, encoding)) as ICoordinateSystem;

            return(cs);
        }