public static bool IsNodeInBuilding(Node node, ICompleteOsmGeo building) { if (building is Node buildingNode) { return(DistanceMeters(node, buildingNode) <= 1); } else if (building is CompleteWay buildingWay) { var point = new NetTopologySuite.Geometries.Point(node.Longitude.Value, node.Latitude.Value); if (buildingWay.Nodes.Length < 4 || (buildingWay.Nodes.First() != buildingWay.Nodes.Last())) { return(false); } var ring = new NetTopologySuite.Geometries.LinearRing( buildingWay.Nodes.Select(n => new Coordinate(n.Longitude.Value, n.Latitude.Value)).ToArray()); var polygon = new NetTopologySuite.Geometries.Polygon(ring); return(point.Within(polygon)); } else if (building is CompleteRelation buildingRelation) { // "in" means that even if I land in the center of a donut, I'm still "in" the building. // This isn't 100% accurate (false negative) for polygons where the closed outer ring is defined by more than 2 open ways. return(buildingRelation.Members.Any(m => m.Role != "inner" && IsNodeInBuilding(node, m.Member))); } throw new Exception("ICompleteOsmGeo wasn't a Node, Way or Relation."); }
// METHOD IsCCW() IS MODIFIED FROM ANOTHER WORK AND IS ORIGINALLY BASED ON GeoTools.NET: /* * Copyright (C) 2002 Urban Science Applications, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ /// <summary> /// Tests whether a ring is oriented counter-clockwise. /// </summary> /// <param name="ring">Ring to test.</param> /// <returns>Returns true if ring is oriented counter-clockwise.</returns> public static bool IsCCW(LinearRing ring) { Coordinate PrevPoint, NextPoint; Coordinate p; // Check if the ring has enough vertices to be a ring if (ring.Coordinates.Length < 3) throw (new ArgumentException("Invalid LinearRing")); // find the point with the largest Y coordinate var hip = ring.Coordinates[0]; int hii = 0; for (int i = 1; i < ring.Coordinates.Length; i++) { p = ring.Coordinates[i]; if (p.Y > hip.Y) { hip = p; hii = i; } } // Point left to Hip int iPrev = hii - 1; if (iPrev < 0) iPrev = ring.Coordinates.Length - 2; // Point right to Hip int iNext = hii + 1; if (iNext >= ring.Coordinates.Length) iNext = 1; PrevPoint = ring.Coordinates[iPrev]; NextPoint = ring.Coordinates[iNext]; // translate so that hip is at the origin. // This will not affect the area calculation, and will avoid // finite-accuracy errors (i.e very small vectors with very large coordinates) // This also simplifies the discriminant calculation. double prev2x = PrevPoint.X - hip.X; double prev2y = PrevPoint.Y - hip.Y; double next2x = NextPoint.X - hip.X; double next2y = NextPoint.Y - hip.Y; // compute cross-product of vectors hip->next and hip->prev // (e.g. area of parallelogram they enclose) double disc = next2x*prev2y - next2y*prev2x; // If disc is exactly 0, lines are collinear. There are two possible cases: // (1) the lines lie along the x axis in opposite directions // (2) the line lie on top of one another // (2) should never happen, so we're going to ignore it! // (Might want to assert this) // (1) is handled by checking if next is left of prev ==> CCW if (disc == 0.0) { // poly is CCW if prev x is right of next x return (PrevPoint.X > NextPoint.X); } else { // if area is positive, points are ordered CCW return (disc > 0.0); } }
public static IPolygon ToPolygon(this Envelope envelope) { ILinearRing ring = new LinearRing(new Coordinate[] { new Coordinate(envelope.MinX, envelope.MinY), new Coordinate(envelope.MinX, envelope.MaxY), new Coordinate(envelope.MaxX, envelope.MaxY), new Coordinate(envelope.MaxX, envelope.MinY), new Coordinate(envelope.MinX, envelope.MinY) }); return new Polygon(ring); }
/// <summary> /// Constructs a <c>Polygon</c> with the given exterior boundary and /// interior boundaries. /// </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 /// point is to be created. /// </param> /// <param name="holes"> /// The inner boundaries of the new <c>Polygon</c> /// , or <c>null</c> or empty <c>LinearRing</c>s if the empty /// point is to be created. /// </param> /// <param name="factory"></param> public Polygon(LinearRing shell, LinearRing[] holes, GeometryFactory factory) : base(factory) { if (shell == null) { shell = Factory.CreateLinearRing(); } if (holes == null) { holes = new LinearRing[] { } } ; if (HasNullElements <LinearRing>(holes)) { throw new ArgumentException("holes must not contain null elements"); } if (shell.IsEmpty && HasNonEmptyElements(holes)) { throw new ArgumentException("shell is empty but holes are not"); } _shell = shell; _holes = holes; }
/// <inheritdoc/> /// <remarks> /// The <see cref="Polygon.ExteriorRing"/> is guaranteed to be orientated counter-clockwise. /// <br/>The <see cref="Polygon.InteriorRings"/> are guaranteed to be orientated clockwise. /// </remarks> public override Polygon CreatePolygon(LinearRing shell, LinearRing[] holes) { if (shell != null) { if (!shell.IsCCW) { shell = ReverseRing(shell); } } if (holes != null) { for (int i = 0; i < holes.Length; i++) { if (holes[i].IsCCW) { holes[i] = ReverseRing(holes[i]); } } } return(base.CreatePolygon(shell, holes)); }
/// <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 geometry is to be created.</param> /// <returns>the created Polygon</returns> /// <exception cref="ArgumentException">If the boundary ring is invalid</exception> public virtual Polygon CreatePolygon(LinearRing shell) { return(CreatePolygon(shell, null)); }
/// <summary> /// Constructs a <c>Polygon</c> with the given exterior boundary and /// interior boundaries. /// </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 point is to be created. /// </param> /// <param name="holes"> /// The inner boundaries of the new <c>Polygon</c>, or /// <c>null</c> or empty <c>LinearRing</c> s if /// the empty point is to be created. /// </param> /// <returns>A <see cref="Polygon"/> object</returns> public virtual Polygon CreatePolygon(LinearRing shell, LinearRing[] holes) { return(new Polygon(shell, holes, this)); }
private IGeometry BuildPolygon() { if (this.rings.Count == 0) { return Polygon.Empty; } ILinearRing shell = new LinearRing(this.rings[0]); ILinearRing[] holes = this.rings.GetRange(1, this.rings.Count - 1) .ConvertAll<ILinearRing>(delegate(Coordinate[] coordinates) { return new LinearRing(coordinates); }).ToArray(); this.rings.Clear(); return new Polygon(shell, holes); }
private static LinearRing CreateWKBLinearRing(BinaryReader reader, WkbByteOrder byteOrder) { //l.Vertices.AddRange(ReadCoordinates(reader, byteOrder)); Point[] arrPoint = ReadCoordinates(reader, byteOrder); Coordinate clasurePoint = null; //if polygon isn't closed, add the first point to the end (this shouldn't occur for correct WKB data) if (arrPoint[0].X != arrPoint[arrPoint.Length - 1].X || arrPoint[0].Y != arrPoint[arrPoint.Length - 1].Y) { clasurePoint = new Coordinate(arrPoint[0].X, arrPoint[0].Y); } Coordinate[] arrCoordinate; if (clasurePoint == null) { arrCoordinate = new Coordinate[arrPoint.Length]; } else { arrCoordinate = new Coordinate[arrPoint.Length+1]; } for (int i = 0; i < arrPoint.Length; i++) arrCoordinate[i] = new Coordinate(arrPoint[i].X, arrPoint[i].Y); if (clasurePoint != null) arrCoordinate[arrCoordinate.Length - 1] = clasurePoint; LinearRing l = new LinearRing(arrCoordinate); return l; }
private Polygon readPolygon() { br.BaseStream.Seek(4 * 8, SeekOrigin.Current); // Skip bounding box int numparts = br.ReadInt32(); int numpoints = br.ReadInt32(); pos += 4 * 8 + 8; // parts[] contain accumulated number of points in each polygon part int[] parts = new int[numparts+1]; for (int i = 0; i < numparts; i++) parts[i] = br.ReadInt32(); parts[numparts] = numpoints; pos += 4 * numparts; // polygon to be read ILinearRing p = null; // potential holes in polygon List<ILinearRing> holes = new List<ILinearRing>(); for (int i = 0; i < numparts; i++) { // read points var points = readPolygonPart(parts[i + 1] - parts[i]); if (p == null) // first polygon is boundary p = new LinearRing(points.ToArray()); else // subsequent polygons are holes holes.Add(new LinearRing(points.ToArray())); } return new Polygon(p, holes.ToArray()); }
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); }
/// <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> public Polygon(LinearRing shell) : this(shell, null, DefaultFactory) { }
/// <summary> /// Abbreviation to counter clockwise function /// </summary> /// <param name="self">The ring</param> /// <returns><c>true</c> if the ring is oriented counter clockwise</returns> public static bool IsCCW(this LinearRing self) { return(NetTopologySuite.Algorithm.Orientation.IsCCW(self.Coordinates)); }
private void UpdateNonClosedRing(LinearRing ring) { Coordinate[] pts = ring.Coordinates; pts[0].X += 0.0001; }
/// <summary> /// This method produces instances of type Polygon/>. /// </summary> /// <returns>The created geometries</returns> internal override Collection<SimpleGisShape> createGeometries() { SimpleGisShape shp = null; XmlReader outerBoundaryReader = null; XmlReader innerBoundariesReader = null; IPathNode polygonNode = new PathNode(_GMLNS, "Polygon", (NameTable)_xmlReader.NameTable); IPathNode outerBoundaryNode = new PathNode(_GMLNS, "outerBoundaryIs", (NameTable)_xmlReader.NameTable); IPathNode exteriorNode = new PathNode(_GMLNS, "exterior", (NameTable)_xmlReader.NameTable); IPathNode outerBoundaryNodeAlt = new AlternativePathNodesCollection(outerBoundaryNode, exteriorNode); IPathNode innerBoundaryNode = new PathNode(_GMLNS, "innerBoundaryIs", (NameTable)_xmlReader.NameTable); IPathNode interiorNode = new PathNode(_GMLNS, "interior", (NameTable)_xmlReader.NameTable); IPathNode innerBoundaryNodeAlt = new AlternativePathNodesCollection(innerBoundaryNode, interiorNode); IPathNode linearRingNode = new PathNode(_GMLNS, "LinearRing", (NameTable)_xmlReader.NameTable); string[] labelValue = new string[1]; try { ParseBoundingBox(); // Reading the entire feature's node makes it possible to collect label values that may appear before or after the geometry property while ((_featureReader = GetSubReaderOf(_xmlReader, null, _featureNode)) != null) { while ((_geomReader = GetSubReaderOf(_featureReader, null, _propertyNode)) != null) { bool isSelected; int uid; List<string> ll = ParseProperties(_geomReader, out isSelected, out uid); _geomReader = GetSubReaderOf(_featureReader, labelValue, polygonNode); ILinearRing shell = null; List<ILinearRing> holes = new List<ILinearRing>(); if ( (outerBoundaryReader = GetSubReaderOf(_geomReader, null, outerBoundaryNodeAlt, linearRingNode, _CoordinatesNode)) != null) shell = new LinearRing(ParseCoordinates(outerBoundaryReader)); while ( (innerBoundariesReader = GetSubReaderOf(_geomReader, null, innerBoundaryNodeAlt, linearRingNode, _CoordinatesNode)) != null) holes.Add(new LinearRing(ParseCoordinates(innerBoundariesReader))); Polygon polygon = new Polygon(shell, holes.ToArray()); shp = new SimpleGisShape(polygon); shp.IsSelected = isSelected; shp.UID = uid; _shapes.Add(shp); FillShapeFields(shp, ll); } } } catch (Exception ex) { throw ex; } return _shapes; }
private static LinearRing ReverseRing(LinearRing ring) { return((LinearRing)ring.Reverse()); }
/// <inheritdoc/> /// <remarks> /// The <see cref="Polygon.ExteriorRing"/> is guaranteed to be orientated counter-clockwise. /// </remarks> public override Polygon CreatePolygon(LinearRing shell) { return(CreatePolygon(shell, null)); }
/// <summary> /// Initializes a new instance of the <see cref="Polygon"/> class. /// </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 /// point is to be created. /// </param> /// <param name="holes"> /// The inner boundaries of the new <c>Polygon</c> /// , or <c>null</c> or empty <c>LinearRing</c>s if the empty /// point is to be created. /// </param> /// <remarks> /// For create this <see cref="Geometry"/> is used a standard <see cref="GeometryFactory"/> /// with <see cref="PrecisionModel" /> <c> == </c> <see cref="PrecisionModels.Floating"/>. /// </remarks> public Polygon(LinearRing shell, LinearRing[] holes) : this(shell, holes, DefaultFactory) { }
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); }
/* 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) { }
private IGeometry ReadPolygon(int dim, int lrsDim, SdoGeometry sdoGeom) { ILinearRing shell = null; //ILinearRing[] holes = new LinearRing[sdoGeom.ElemArray.Length - 1]; ILinearRing[] holes = new LinearRing[0]; var info = sdoGeom.ElemArray; var infoSize = info.Length / 3; int i = 0; int idxInteriorRings = 0; while (i < infoSize) { ICoordinateSequence cs = null; int numCompounds = 0; //if (info.getElementType(i).isCompound()) //{ // numCompounds = info.getNumCompounds(i); // cs = Add(cs, GetCompoundCSeq(i + 1, i + numCompounds, sdoGeom)); //} //else //{ cs = Add(cs, GetElementCSeq(i, sdoGeom, false)); //} //if (info.getElementType(i).isInteriorRing()) //{ // holes[idxInteriorRings] = factory // .CreateLinearRing(cs); // holes[idxInteriorRings].SRID = (int)sdoGeom.Sdo_Srid; // idxInteriorRings++; //} //else //{ shell = factory.CreateLinearRing(cs); shell.SRID = (int)sdoGeom.Sdo_Srid; //} i += 1 + numCompounds; } IPolygon polygon = factory.CreatePolygon(shell, holes); polygon.SRID = (int)sdoGeom.Sdo_Srid; return polygon; }
public static IEnumerable <IPoint> FromLinearRing(NTSLinearRing linearRing) => linearRing.Coordinates.Select(point => new Point(point));
private ILinearRing CreateLinearRing(int dim, int lrs, Decimal[] elemInfo, int elemIndex, List<Coordinate> coords) { int sOffset = StartingOffset(elemInfo, elemIndex); SdoEType etype = EType(elemInfo, elemIndex); int interpretation = Interpretation(elemInfo, elemIndex); int length = coords.Count*dim; if (!(sOffset <= length)) throw new ArgumentException("ELEM_INFO STARTING_OFFSET " + sOffset + " inconsistent with ORDINATES length " + coords.Count); if (etype != SdoEType.Polygon && etype != SdoEType.PolygonExterior && etype != SdoEType.PolygonInterior) { throw new ArgumentException("ETYPE " + etype + " inconsistent with expected POLYGON, POLYGON_EXTERIOR or POLYGON_INTERIOR"); } if (interpretation != 1 && interpretation != 3) { return null; } ILinearRing ring; int len = (dim + lrs); int start = (sOffset - 1)/len; int eOffset = StartingOffset(elemInfo, elemIndex + 1); // -1 for end int end = (eOffset != -1) ? ((eOffset - 1)/len) : coords.Count; if (interpretation == 1) { ring = new LinearRing(ToPointArray(SubList(coords, start, end))); } else { // interpretation == 3 // rectangle does not maintain measures List<Coordinate> pts = new List<Coordinate>(5); List<Coordinate> ptssrc = SubList(coords, start, end); Coordinate min = ptssrc[0]; Coordinate max = ptssrc[1]; pts.AddRange(new[] { min, new Coordinate(max.X, min.Y), max, new Coordinate(min.X, max.Y) , min }); ring = _factory.CreateLinearRing(pts.ToArray()); } return ring; }
/// <summary> /// Creates a Polygon using the next token in the stream. /// </summary> /// <param name="tokenizer">Tokenizer over a stream of text in Well-known Text /// format. The next tokens must form a <Polygon Text>.</param> /// <returns>Returns a Polygon specified by the next token /// in the stream</returns> /// <remarks> /// ParseException is thown if the coordinates used to create the Polygon /// shell and holes do not form closed linestrings, or if an unexpected /// token is encountered. /// </remarks> private static Polygon ReadPolygonText(WktStreamTokenizer tokenizer) { string nextToken = GetNextEmptyOrOpener(tokenizer); if (nextToken == "EMPTY") return new Polygon(new LinearRing(new List<Coordinate>().ToArray())); var points = GetCoordinates(tokenizer); var arrexteriorring = new Coordinate[points.Count]; for (int i = 0; i < arrexteriorring.Length; i++) arrexteriorring[i] = new Coordinate(points[i].X, points[i].Y); var exteriorRing = new LinearRing(arrexteriorring); nextToken = GetNextCloserOrComma(tokenizer); var interiorRings = new List<ILinearRing>(); while (nextToken == ",") { var holes = GetCoordinates(tokenizer); var arrholes = new Coordinate[holes.Count]; for (int i = 0; i < arrholes.Length; i++) arrholes[i] = new Coordinate(holes[i].X, holes[i].Y); //Add holes interiorRings.Add(new LinearRing(arrholes)); nextToken = GetNextCloserOrComma(tokenizer); } Polygon pol = new Polygon(exteriorRing, interiorRings.ToArray()); return pol; }
private IGeometry ReadPolygon(int dim, int lrsDim, SdoGeometry sdoGeom) { LinearRing shell = null; LinearRing[] holes = new LinearRing[sdoGeom.getNumElements() - 1]; decimal[] info = sdoGeom.ElemArray; int i = 0; int idxInteriorRings = 0; while (i < info.Length) { ICoordinateSequence cs = null; int numCompounds = 0; if (info.getElementType(i).isCompound()) { numCompounds = info.getNumCompounds(i); cs = Add(cs, GetCompoundCSeq(i + 1, i + numCompounds, sdoGeom)); } else { cs = Add(cs, GetElementCSeq(i, sdoGeom, false)); } if (info.getElementType(i).isInteriorRing()) { holes[idxInteriorRings] = factory .CreateLinearRing(cs); holes[idxInteriorRings].SRID = (int)sdoGeom.Sdo_Srid; idxInteriorRings++; } else { shell = factory.CreateLinearRing(cs); shell.SRID = (int)sdoGeom.Sdo_Srid; } i += 1 + numCompounds; } IPolygon polygon = factory.CreatePolygon(shell, holes); polygon.SRID = (int)sdoGeom.Sdo_Srid; return polygon; }