/** * Making a Polygon valid may Creates * <ul> * <li>an Empty Polygon if input has no valid coordinate</li> * <li>a Point if input has only one valid coordinate</li> * <li>a LineString if input has only a valid segment</li> * <li>a Polygon in most cases</li> * <li>a MultiPolygon if input has a self-intersection</li> * <li>a GeometryCollection if input has degenerate parts (ex. degenerate * holes)</li> * </ul> * * @param polygon the Polygon to make valid * @return a valid Geometry which may be of any type if the source geometry * is not valid. */ private NetTopologySuite.Geometries.Geometry makePolygonValid(Polygon polygon) { //This first step analyze linear components and Create degenerate geometries //of dimension 0 or 1 if they do not form valid LinearRings //If degenerate geometries are found, it may produce a GeometryCollection with //heterogeneous dimension NetTopologySuite.Geometries.Geometry geom = makePolygonComponentsValid(polygon); List <NetTopologySuite.Geometries.Geometry> list = new(); for (int i = 0; i < geom.NumGeometries; i++) { NetTopologySuite.Geometries.Geometry component = geom.GetGeometryN(i); if (component is Polygon) { NetTopologySuite.Geometries.Geometry nodedPolygon = nodePolygon((Polygon)component); for (int j = 0; j < nodedPolygon.NumGeometries; j++) { list.Add(nodedPolygon.GetGeometryN(j)); } } else { list.Add(component); } } return(polygon.Factory.BuildGeometry(list)); }
private void gatherDim4(NetTopologySuite.Geometries.Geometry geometry, Dictionary <Coordinate, Double> map) { if (geometry is Point) { gatherDim4(((Point)geometry).CoordinateSequence, map); } else if (geometry is LineString) { gatherDim4(((LineString)geometry).CoordinateSequence, map); } else if (geometry is Polygon) { Polygon polygon = (Polygon)geometry; gatherDim4(polygon.ExteriorRing.CoordinateSequence, map); for (int i = 0; i < polygon.NumInteriorRings; i++) { gatherDim4(polygon.GetInteriorRingN(i).CoordinateSequence, map); } } else { for (int i = 0; i < geometry.NumGeometries; i++) { gatherDim4(geometry.GetGeometryN(i), map); } } }
/// <summary> /// Reads a shapefile into a arraylist of features that need converting from x,y coordinates to Long and Lat coordinates /// </summary> /// <param name="filename">name of the shapefile (the file that has all the polygons for the footpaths)</param> /// <param name="fact">the class that generates the structure of the points</param> /// <returns></returns> public ArrayList ReadSHP(string filename, GeometryFactory fact) { ArrayList features = new ArrayList(); //Array list for all the coordinates from the shapefile ShapefileDataReader sfDataReader = new ShapefileDataReader(filename, fact); ShapefileHeader shpHeader = sfDataReader.ShapeHeader; DbaseFileHeader DHeader = sfDataReader.DbaseHeader; while (sfDataReader.Read() == true) { Feature feature = new Feature(); AttributesTable atTable = new AttributesTable(); string[] keys = new string[DHeader.NumFields]; Geometry geometry = sfDataReader.Geometry; for (int i = 0; i < DHeader.NumFields; i++) { DbaseFieldDescriptor fldDescriptor = DHeader.Fields[i]; keys[i] = fldDescriptor.Name; atTable.Add(fldDescriptor.Name, sfDataReader.GetValue(i)); } feature.Geometry = geometry; feature.Attributes = atTable; features.Add(feature); } sfDataReader.Close(); sfDataReader.Dispose(); return(features); }
public void AddOverlay(ArrayList features) { for (int i = 0; i < features.Count; i++) { Feature feat = (Feature)features[i]; Geometry Geo = feat.Geometry; GMapOverlay polygons = new GMapOverlay("Polygons"); List <PointLatLng> PLL = new List <PointLatLng>(); LatList.Clear(); LongList.Clear(); List <double> LatLong = new List <double>(); for (int k = 0; k < Geo.Coordinates.Length; k++) { LatLong = LongLatCalculation(Geo.Coordinates[k].X, Geo.Coordinates[k].Y); LatList.Add(LatLong[0]); LongList.Add(LatLong[1]); PLL.Add(new PointLatLng(LatLong[0], LatLong[1])); } //ListPLL.Add(PLL); GMapPolygon poly = new GMapPolygon(PLL, "Polygon"); poly.Fill = new SolidBrush(Color.Orange); poly.Stroke = new Pen(Color.Black); polygons.Polygons.Add(poly); gMapControl1.Overlays.Add(polygons); gMapControl1.Refresh(); } }
public static IGeometry mergeLines(Geometry g) { var merger = new LineMerger(); merger.Add(g); var lines = merger.GetMergedLineStrings(); return g.Factory.BuildGeometry(lines); }
/// <summary> /// Reads a shapefile into a arraylist of features that need converting from x,y coordinates to Long and Lat coordinates /// </summary> /// <param name="filename">name of the shapefile (the file that has all the polygons for the footpaths)</param> /// <param name="fact">the class that generates the structure of the points</param> /// <returns></returns> public ArrayList ReadSHP(string filename, GeometryFactory fact) { ArrayList features = new ArrayList(); //Array list for all the coordinates from the shapefile ShapefileDataReader sfDataReader = new ShapefileDataReader(filename, fact); //takes a file and a factory to build the geometries ShapefileHeader shpHeader = sfDataReader.ShapeHeader; //reads the headers of the file for checking and looping purposes DbaseFileHeader DHeader = sfDataReader.DbaseHeader; while (sfDataReader.Read() == true) //reading through all the data in the shapefile { Feature feature = new Feature(); //setting up a feature for each set of points AttributesTable atTable = new AttributesTable(); //table for the set of points string[] keys = new string[DHeader.NumFields]; Geometry geometry = sfDataReader.Geometry; for (int i = 0; i < DHeader.NumFields; i++) { DbaseFieldDescriptor fldDescriptor = DHeader.Fields[i]; keys[i] = fldDescriptor.Name; atTable.Add(fldDescriptor.Name, sfDataReader.GetValue(i)); } feature.Geometry = geometry; feature.Attributes = atTable; //setting the variables for the feature features.Add(feature); } sfDataReader.Close();//closing the reader sfDataReader.Dispose(); return(features); }
/// <summary> /// Converts from Mapsui Geometry type to NetTopologySuite Geometry type, then converts to GeoJSON. /// Writes the point list to wkt format, the uses Geometry2GeoJSON to convert to geojson /// </summary> /// <param name="pointList"></param> /// <returns>GeoJSON</returns> public static string CoordinatesToGeoJSON(List <Mapsui.Geometries.Point> pointList) { var wkt = ""; if (pointList.Count == 1) { var point = pointList[0]; wkt = Mapsui.Geometries.WellKnownText.GeometryToWKT.Write(point); } else if (pointList[0] == pointList[pointList.Count - 1]) { var polygon = new Mapsui.Geometries.Polygon(); foreach (var coord in pointList) { polygon.ExteriorRing.Vertices.Add(new Mapsui.Geometries.Point(coord.X, coord.Y)); } wkt = Mapsui.Geometries.WellKnownText.GeometryToWKT.Write(polygon); } else { var line = new Mapsui.Geometries.LineString(pointList); wkt = Mapsui.Geometries.WellKnownText.GeometryToWKT.Write(line); } WKTReader reader = new WKTReader(); NetTopologySuite.Geometries.Geometry geom = reader.Read(wkt); var geojson = DataDAO.Geometry2GeoJSON(geom); return(geojson); }
public static IGeometry MCIndexNoding(Geometry geom) { IList<ISegmentString> segs = CreateNodedSegmentStrings(geom); INoder noder = new MCIndexNoder(new IntersectionAdder(new RobustLineIntersector())); noder.ComputeNodes(segs); IList<ISegmentString> nodedSegStrings = noder.GetNodedSubstrings(); return FromSegmentStrings(nodedSegStrings); }
public static NetTopologySuite.Geometries.Geometry ProjectTo(this NetTopologySuite.Geometries.Geometry geometry, int srid) { var transformation = _coordinateSystemServices.CreateTransformation(geometry.SRID, srid); var result = geometry.Copy(); result.Apply(new MathTransformFilter((MathTransform)transformation.MathTransform)); return(result); }
public static IGeometry MCIndexNodingWithPrecision(Geometry geom, double scaleFactor) { List<ISegmentString> segs = CreateNodedSegmentStrings(geom); LineIntersector li = new RobustLineIntersector(); li.PrecisionModel = new PrecisionModel(scaleFactor); INoder noder = new MCIndexNoder(new IntersectionAdder(li)); noder.ComputeNodes(segs); IList<ISegmentString> nodedSegStrings = noder.GetNodedSubstrings(); return FromSegmentStrings(nodedSegStrings); }
public static CoordinateSequence GetCoordinateSequence(NTSGeometry geometry) { return(geometry switch { Point p => p.CoordinateSequence, MultiPoint mp => (mp.Geometries[0] as Point).CoordinateSequence, LineString ls => ls.CoordinateSequence, MultiLineString mls => (mls.Geometries[0] as LineString).CoordinateSequence, Polygon p => p.Shell.CoordinateSequence, MultiPolygon mp => (mp.Geometries[0] as Polygon).Shell.CoordinateSequence, _ => throw new ApplicationException("Unknown or null geometry"), });
ToNtsFeature(this CoreSpatial.IFeature feature, List <string> fieldNames) { NetTopologySuite.Geometries.Geometry geometry = null; var geo = feature.Geometry; switch (geo.GeometryType) { case GeometryType.Point: { var basicGeometry = (GeoPoint)geo.BasicGeometry; geometry = (NetTopologySuite.Geometries.Geometry)ToNtsPoint(basicGeometry); break; } case GeometryType.MultiPoint: { var basicGeometry = (CoreSpatial.BasicGeometrys.MultiPoint)geo.BasicGeometry; geometry = ToNtsMultiPoint(basicGeometry); break; } case GeometryType.PolyLine: { var basicGeometry = (CoreSpatial.BasicGeometrys.PolyLine)geo.BasicGeometry; geometry = basicGeometry.IsLineRing ? ToNtsLinearRing(basicGeometry) : ToNtsLineString(basicGeometry); break; } case GeometryType.MultiPolyLine: { var basicGeometry = (CoreSpatial.BasicGeometrys.MultiPolyLine)geo.BasicGeometry; geometry = ToNtsMultiLineString(basicGeometry); break; } case GeometryType.Polygon: { var basicGeometry = (CoreSpatial.BasicGeometrys.Polygon)geo.BasicGeometry; geometry = ToNtsPolygon(basicGeometry); break; } default: throw new Exception("not support GeometryType"); } var attrTable = feature.ToNtsAttributeTable(fieldNames); var result = new NetTopologySuite.Features.Feature(geometry, attrTable); return(result); }
private NetTopologySuite.Geometries.Geometry SimplifyGeometry(NetTopologySuite.Geometries.Geometry geometry, int nbPoints, int pow = 1) { if (geometry.NumPoints < nbPoints) { return(geometry); } if (!geometry.IsValid) { geometry = geometry.Buffer(0.001); } var newGeom = NetTopologySuite.Simplify.DouglasPeuckerSimplifier.Simplify(geometry, 0.005 * pow); return(SimplifyGeometry(newGeom, nbPoints, ++pow)); }
private static IGeometry BuildBufferLineSimplifiedSet(Geometry g, double distance) { var simpLines = new List<IGeometry>(); var lines = new List<ILineString>(); LinearComponentExtracter.GetLines(g, lines); foreach(var line in lines) { var pts = line.Coordinates; simpLines.Add(g.Factory.CreateLineString(BufferInputLineSimplifier.Simplify(pts, distance))); } var simpGeom = g.Factory.BuildGeometry(simpLines); return simpGeom; }
public static byte GetDimensions(NetTopologySuite.Geometries.Geometry g) { byte dimensions = 2; if (!double.IsNaN(g.Coordinate.Z)) { dimensions += 1; } if (!double.IsNaN(g.Coordinate.M)) { dimensions += 1; } return(dimensions); }
// Reursively remove geometries with a dimension less than dimension parameter private void removeLowerDimension(NetTopologySuite.Geometries.Geometry geometry, List <NetTopologySuite.Geometries.Geometry> result, Dimension dimension) { for (int i = 0; i < geometry.NumGeometries; i++) { NetTopologySuite.Geometries.Geometry g = geometry.GetGeometryN(i); if (g is GeometryCollection) { removeLowerDimension(g, result, dimension); } else if (g.Dimension >= dimension) { result.Add(g); } } }
/** * Decompose a geometry recursively into simple components. * * @param geometry input geometry * @param list a list of simple components (Point, LineString or Polygon) */ private static void decompose(NetTopologySuite.Geometries.Geometry geometry, ICollection <NetTopologySuite.Geometries.Geometry> list) { for (int i = 0; i < geometry.NumGeometries; i++) { NetTopologySuite.Geometries.Geometry component = geometry.GetGeometryN(i); if (component is GeometryCollection) { decompose(component, list); } else { list.Add(component); } } }
private string GeometryToGeoJson(NetTopologySuite.Geometries.Geometry geometry) { MultiPoint locations1 = new MultiPoint(new[] { new Point(8.681495, 49.41461), new Point(8.686507, 49.41943), new Point(8.687872, 49.420318) }); string geoJson; var serializer = GeoJsonSerializer.Create(); using (var stringWriter = new StringWriter()) using (var jsonWriter = new JsonTextWriter(stringWriter)) { serializer.Serialize(jsonWriter, geometry); geoJson = stringWriter.ToString(); } return(geoJson); }
/// <summary> /// Writes a geometry to a byte array using the specified encoding. /// </summary> /// <param name="g">The geometry to write</param> /// <param name="wkbByteOrder">Byte order</param> /// <returns>WKB representation of the geometry</returns> public static byte[] Write(Geometry g, WkbByteOrder wkbByteOrder) { MemoryStream ms = new MemoryStream(); BinaryWriter bw = new BinaryWriter(ms); //Write the byteorder format. bw.Write((byte) wkbByteOrder); //Write the type of this geometry WriteType(g, bw, wkbByteOrder); //Write the geometry WriteGeometry(g, bw, wkbByteOrder); return ms.ToArray(); }
/// <summary> /// /// </summary> /// <param name="geom"></param> /// <param name="ds"></param> protected override void OnExecuteIntersectionQuery(Geometry geom, FeatureDataSet ds) { FeatureDataTable dataTable = CreateFeatureDataTable(); dataTable.BeginLoadData(); foreach (Feature feature in _features) { if (PreparedGeometry.Intersects(feature.Geometry)) { CreateNewRow(dataTable, feature); } } dataTable.EndLoadData(); ds.Tables.Add(dataTable); }
private NetTopologySuite.Geometries.Geometry KmlGeometryToGeometry(SharpKml.Dom.Geometry geometry) { NetTopologySuite.Geometries.Geometry result = null; if (geometry is SharpKml.Dom.Point) { var kmlPoint = geometry as SharpKml.Dom.Point; result = new NetTopologySuite.Geometries.Point(new Coordinate(kmlPoint.Coordinate.Longitude, kmlPoint.Coordinate.Latitude)); } else if (geometry is SharpKml.Dom.Polygon) { var kmlPolygon = geometry as SharpKml.Dom.Polygon; if (kmlPolygon.OuterBoundary == null || kmlPolygon.OuterBoundary.LinearRing == null || kmlPolygon.OuterBoundary.LinearRing.Coordinates == null) { throw new Exception("Polygon is null"); } var coordinates = new Coordinate[kmlPolygon.OuterBoundary.LinearRing.Coordinates.Count]; int i = 0; foreach (var coordinate in kmlPolygon.OuterBoundary.LinearRing.Coordinates) { coordinates[i++] = new Coordinate(coordinate.Longitude, coordinate.Latitude); } result = new NetTopologySuite.Geometries.Polygon(new NetTopologySuite.Geometries.LinearRing(coordinates)); } else if (geometry is SharpKml.Dom.MultipleGeometry) { var mgeometry = geometry as SharpKml.Dom.MultipleGeometry; var polygons = new List <NetTopologySuite.Geometries.Polygon>(); foreach (var poly in mgeometry.Geometry) { var kmlPolygon = poly as SharpKml.Dom.Polygon; if (kmlPolygon.OuterBoundary == null || kmlPolygon.OuterBoundary.LinearRing == null || kmlPolygon.OuterBoundary.LinearRing.Coordinates == null) { throw new Exception("Polygon is null"); } var coordinates = new Coordinate[kmlPolygon.OuterBoundary.LinearRing.Coordinates.Count]; int i = 0; foreach (var coordinate in kmlPolygon.OuterBoundary.LinearRing.Coordinates) { coordinates[i++] = new Coordinate(coordinate.Longitude, coordinate.Latitude); } polygons.Add(new NetTopologySuite.Geometries.Polygon(new NetTopologySuite.Geometries.LinearRing(coordinates))); } result = new NetTopologySuite.Geometries.MultiPolygon(polygons.ToArray()); } return(result); }
public static IGeometry CheckNoding(Geometry geom) { var segs = CreateSegmentStrings(geom); var nv = new FastNodingValidator(segs); nv.FindAllIntersections = true; var res = nv.IsValid; var intPts = nv.Intersections; var pts = new IPoint[intPts.Count]; for (var i = 0; i < intPts.Count; i++) { var coord = intPts[i]; // use default factory in case intersections are not fixed pts[i] = FunctionsUtil.GetFactoryOrDefault(null).CreatePoint(coord); } return FunctionsUtil.GetFactoryOrDefault(null).CreateMultiPoint( pts); }
private string ExtractWKTFromKML(Stream stream, int points) { NetTopologySuite.Geometries.Geometry finalgeometry = null; try { stream.Seek(0, SeekOrigin.Begin); }catch (Exception) {} KmlFile file = KmlFile.Load(stream); Kml kml = file.Root as Kml; var placemarks = kml.Flatten().OfType <Placemark>(); foreach (var placemark in placemarks) { try { NetTopologySuite.Geometries.Geometry geometry = KmlGeometryToGeometry(placemark.Geometry); if (finalgeometry == null) { finalgeometry = geometry; } else { finalgeometry = finalgeometry.Union(geometry); } } catch (Exception) { //throw new Exception(string.Format("Error with placemark {0}", placemark.Name)); } } string wkt = null; if (finalgeometry != null) { finalgeometry = SimplifyGeometry(finalgeometry, points); foreach (var p in finalgeometry.Coordinates.ToArray()) { p.X = Math.Round(p.X, 2); p.Y = Math.Round(p.Y, 2); if (p is CoordinateZ) { p.Z = Math.Round(p.Z, 2); } } wkt = finalgeometry.AsText(); } return(wkt); }
/// <summary> /// Returns the geometry corresponding to the Object ID /// </summary> /// <param name="oid">Object ID</param> /// <returns>geometry</returns> public override Geometry GetGeometryByID(uint oid) { DataRow[] rows; Geometry geom = null; if (Table.Rows.Count == 0) { return(null); } string selectStatement = ObjectIdColumn + " = " + oid; rows = Table.Select(selectStatement); foreach (DataRow dr in rows) { geom = Factory.CreatePoint(new Coordinate((double)dr[XColumn], (double)dr[YColumn])); } return(geom); }
private static void BuildRing(Geometry ring, SpatialPipeline builder) { if (ring == null) { return; } var coords = ring.Coordinates.ToList(); coords.RemoveAt(coords.Count - 1); var first = coords.First(); builder.GeographyPipeline.BeginFigure(new GeographyPosition(first.Y, first.X, first.Z, null)); for (var i = 1; i < coords.Count; i++) { var next = coords[i]; builder.GeographyPipeline.LineTo(new GeographyPosition(next.Y, next.X, next.Z, null)); } builder.GeographyPipeline.LineTo(new GeographyPosition(first.Y, first.X, first.Z, null)); builder.GeographyPipeline.EndFigure(); }
public override bool EqualsExact(NetTopologySuite.Geometries.Geometry other, double tolerance) { if (other is CompoundCurve cc) { if (cc.NumGeometries == NumGeometries) { return(false); } for (int i = 0; i < NumGeometries; ++i) { var ls1 = GetGeometryN(i); var ls2 = cc.GetGeometryN(i); if (!ls1.EqualsExact(ls2, tolerance)) { return(false); } } return(true); } return(Linearize(tolerance).EqualsExact(other, tolerance)); }
/// <summary> /// Adds the overlay to the Google map by taking the lat and long coordinates /// </summary> /// <param name="features">List of features that contains x and y coordinates</param> public void AddOverlay(ArrayList features) { for (int i = 0; i < features.Count; i++) //process all features in the list { Feature feat = (Feature)features[i]; //extracts a feature from the list Geometry Geo = feat.Geometry; //Creates a geometry of that feature GMapOverlay polygons = new GMapOverlay("Polygons"); //initalises the polygon overlay List <PointLatLng> PLL = new List <PointLatLng>(); //initialises the lists needed to store the polygon points List <double> LatLong = new List <double>(); for (int k = 0; k < Geo.Coordinates.Length; k++) //runs through all the points associated with one feature { LatLong = LongLatCalculation(Geo.Coordinates[k].X, Geo.Coordinates[k].Y); //calculates the conversion from the x, y coordinates to the lat and long coordinates PLL.Add(new PointLatLng(LatLong[0], LatLong[1])); //Adds the points to a list which is used pass to the polygon constructor } GMapPolygon poly = new GMapPolygon(PLL, "Polygon"); //polygon constructor poly.Fill = new SolidBrush(Color.Orange); poly.Stroke = new Pen(Color.Black); polygons.Polygons.Add(poly); gMapControl1.Overlays.Add(polygons); //adds the polygons to the map in the form on an overlay gMapControl1.Refresh(); } }
/** * Node a LinearRing and return a MultiPolygon containing * <ul> * <li>a single Polygon if the LinearRing is simple</li> * <li>several Polygons if the LinearRing auto-intersects</li> * </ul> * This is used to repair auto-intersecting Polygons */ private NetTopologySuite.Geometries.Geometry getArealGeometryFromLinearRing(LinearRing ring) { if (ring.IsSimple) { return(ring.Factory.CreateMultiPolygon(new Polygon[] { ring.Factory.CreatePolygon(ring, EMPTY_RING_ARRAY) })); } else { // Node input LinearRing and extract unique segments ISet <LineString> lines = nodeLineString(ring.Coordinates, ring.Factory); lines = getSegments(lines); // Polygonize the line network Polygonizer polygonizer = new Polygonizer(); polygonizer.Add((ICollection <NetTopologySuite.Geometries.Geometry>)lines); // Computes intersections to determine the status of each polygon ICollection <NetTopologySuite.Geometries.Geometry> geoms = new List <NetTopologySuite.Geometries.Geometry>(); foreach (NetTopologySuite.Geometries.Geometry g in polygonizer.GetPolygons()) { Polygon polygon = (Polygon)g; Coordinate p = polygon.InteriorPoint.Coordinate; var location = RayCrossingCounter.LocatePointInRing(p, ring.CoordinateSequence); if (location == NetTopologySuite.Geometries.Location.Interior) { geoms.Add(polygon); } } NetTopologySuite.Geometries.Geometry unionPoly = UnaryUnionOp.Union(geoms); NetTopologySuite.Geometries.Geometry unionLines = UnaryUnionOp.Union(lines).Difference(unionPoly.Boundary); geoms.Clear(); decompose(unionPoly, geoms); decompose(unionLines, geoms); return(ring.Factory.BuildGeometry(geoms)); } }
/// <summary> /// Converts an NTS LineString to a Microsoft.Spatial GeogaphyLineString. /// </summary> /// <param name="lineString">The NTS LineString.</param> /// <returns></returns> public static GeographyLineString ToGeographyLineString(this Geometry lineString) { if (lineString == null) { return(null); } Debug.Assert(lineString.GeometryType == "LineString"); var builder = SpatialBuilder.Create(); var pipeLine = builder.GeographyPipeline; pipeLine.SetCoordinateSystem(CoordinateSystem.DefaultGeography); pipeLine.BeginGeography(SpatialType.LineString); var numPionts = lineString.NumPoints; for (var n = 0; n < numPionts; n++) { var pointN = lineString.GetGeometryN(n + 1); var lat = pointN.Coordinate.Y; var lon = pointN.Coordinate.X; var alt = pointN.Coordinate.Z; var m = pointN.Length; var position = new GeographyPosition(lat, lon, alt, m); if (n == 0) { pipeLine.BeginFigure(position); } else { pipeLine.LineTo(position); } } pipeLine.EndFigure(); pipeLine.EndGeography(); return((GeographyLineString)builder.ConstructedGeography); }
public static void FinalizePolygons(List <Polygon> polys) { polys.ForEach(p => p.RemoveDuplicateVertices()); polys.RemoveAll(p => p.Count < 3); try { var isects = GeometryUtils.GetIntersectionPoints(polys); if (isects.Count > 0) { var f = GeometryFactory.Floating; var iarray = polys.Select(p => p.ToIPolygon()).ToArray(); NetTopologySuite.Geometries.Geometry union = f.CreateMultiPolygon(iarray); union = isects.Aggregate(union, (current, vector) => current.Union(f.CreatePoint(new Coordinate(vector.X, vector.Y)).Buffer(0.0001, 1))); polys.Clear(); switch (union) { case NetTopologySuite.Geometries.Polygon polygon: polys.AddRange(polygon.ToElmaPolygons()); break; case MultiPolygon multiPolygon: polys.AddRange(multiPolygon.Geometries.Select(geometry => geometry as NetTopologySuite.Geometries.Polygon) .SelectMany(poly => poly.ToElmaPolygons())); break; } polys.ForEach(p => p.MarkVectorsAs(VectorMark.Selected)); } } finally { polys.ForEach(p => p.UpdateDecomposition()); } }
/// <summary> /// Initializes a new instance of the <see cref="MemoryProvider"/> /// </summary> /// <param name="geometry">Geometry to be in this datasource</param> public MemoryProvider(Geometry geometry) { _Features = new Features(); IFeature feature = _Features.New(); feature.Geometry = geometry; _Features.Add(feature); }
private void CheckIsValid(Geometry geom, bool expected) { IsValidOp validator = new IsValidOp(geom); bool isValid = validator.IsValid; Assert.IsTrue(isValid == expected); }
/// <summary> /// Writes the geometry to the binary writer. /// </summary> /// <param name="geometry">The geometry to be written.</param> /// <param name="bWriter"></param> /// <param name="byteorder">Byte order</param> private static void WriteGeometry(Geometry geometry, BinaryWriter bWriter, WkbByteOrder byteorder) { switch (geometry.GetType().FullName) { //Write the point. case "SharpMap.Geometries.Point": WritePoint((Point) geometry, bWriter, byteorder); break; case "SharpMap.Geometries.LineString": LineString ls = (LineString) geometry; WriteLineString(ls, bWriter, byteorder); break; case "SharpMap.Geometries.Polygon": WritePolygon((Polygon) geometry, bWriter, byteorder); break; //Write the Multipoint. case "SharpMap.Geometries.MultiPoint": WriteMultiPoint((MultiPoint) geometry, bWriter, byteorder); break; //Write the Multilinestring. case "SharpMap.Geometries.MultiLineString": WriteMultiLineString((MultiLineString) geometry, bWriter, byteorder); break; //Write the Multipolygon. case "SharpMap.Geometries.MultiPolygon": WriteMultiPolygon((MultiPolygon) geometry, bWriter, byteorder); break; //Write the Geometrycollection. case "SharpMap.Geometries.GeometryCollection": WriteGeometryCollection((GeometryCollection) geometry, bWriter, byteorder); break; //If the type is not of the above 7 throw an exception. default: throw new ArgumentException("Invalid Geometry Type"); } }
//private const byte WKBByteOrder = 0; /// <summary> /// Writes a geometry to a byte array using little endian byte encoding /// </summary> /// <param name="g">The geometry to write</param> /// <returns>WKB representation of the geometry</returns> public static byte[] Write(Geometry g) { return Write(g, WkbByteOrder.Ndr); }
void RunGeometry(Geometry g, int dimension, ByteOrder byteOrder, bool toHex, int srid) { bool includeSRID = false; if (srid >= 0) { includeSRID = true; g.SRID = srid; } WKBWriter wkbWriter = new WKBWriter(byteOrder, includeSRID, dimension==2 ? false : true); byte[] wkb = wkbWriter.Write(g); String wkbHex = null; if (toHex) wkbHex = WKBWriter.ToHex(wkb); if (toHex) wkb = WKBReader.HexToBytes(wkbHex); Geometry g2 = (Geometry)_wkbReader.Read(wkb); CoordinateSequenceComparator comp = (dimension == 2) ? Comp2 : Comp3; bool isEqual = (g.CompareTo(g2, comp) == 0); Assert.IsTrue(isEqual); if (includeSRID) { bool isSRIDEqual = g.SRID == g2.SRID; Assert.IsTrue(isSRIDEqual); } }
public NtsGeometry(NtsGeometryFactory factory, Geometry geometry) { Factory = factory; this.geometry = geometry; }
/// <summary> /// Returns a list containing a Coordinate from each Polygon, LineString, and Point /// found inside the specified point. Thus, if the specified point is /// not a GeometryCollection, an empty list will be returned. /// </summary> public static IList<Coordinate> GetCoordinates(Geometry geom) { var pts = new List<Coordinate>(); geom.Apply(new ConnectedElementPointFilter(pts)); return pts; }
public override bool EqualsTopologically(NetTopologySuite.Geometries.Geometry g) => g is CompoundCurve cc?cc.Components.SequenceEqual(Components) : Linearize().EqualsTopologically(g);
public SimplePointInAreaLocator(Geometry geom) { _geom = geom; }
/// <summary> /// Writes the type number for this geometry. /// </summary> /// <param name="geometry">The geometry to determine the type of.</param> /// <param name="bWriter">Binary Writer</param> /// <param name="byteorder">Byte order</param> private static void WriteType(Geometry geometry, BinaryWriter bWriter, WkbByteOrder byteorder) { //Determine the type of the geometry. switch (geometry.GetType().FullName) { //Points are type 1. case "SharpMap.Geometries.Point": WriteUInt32((uint) WKBGeometryType.wkbPoint, bWriter, byteorder); break; //Linestrings are type 2. case "SharpMap.Geometries.LineString": WriteUInt32((uint) WKBGeometryType.wkbLineString, bWriter, byteorder); break; //Polygons are type 3. case "SharpMap.Geometries.Polygon": WriteUInt32((uint) WKBGeometryType.wkbPolygon, bWriter, byteorder); break; //Mulitpoints are type 4. case "SharpMap.Geometries.MultiPoint": WriteUInt32((uint) WKBGeometryType.wkbMultiPoint, bWriter, byteorder); break; //Multilinestrings are type 5. case "SharpMap.Geometries.MultiLineString": WriteUInt32((uint) WKBGeometryType.wkbMultiLineString, bWriter, byteorder); break; //Multipolygons are type 6. case "SharpMap.Geometries.MultiPolygon": WriteUInt32((uint) WKBGeometryType.wkbMultiPolygon, bWriter, byteorder); break; //Geometrycollections are type 7. case "SharpMap.Geometries.GeometryCollection": WriteUInt32((uint) WKBGeometryType.wkbGeometryCollection, bWriter, byteorder); break; //If the type is not of the above 7 throw an exception. default: throw new ArgumentException("Invalid Geometry Type"); } }
/** * Repair an invalid geometry. * <br/> * If preserveGeomDim is true, makeValid will remove degenerated geometries * from the result, i.e geometries which dimension is lower than the input * geometry dimension (except for mixed GeometryCollection). * <br/> * A multi-geometry will always produce a multi-geometry (eventually empty * or made of a single component). A simple geometry may produce a * multi-geometry (ex. polygon with self-intersection will generally produce * a multi-polygon). In this case, it is up to the client to explode * multi-geometries if he needs to. * <br/> * If preserveGeomDim is off, it is up to the client to filter degenerate * geometries. * <br/> * WARNING : for geometries of dimension 1 (linear), duplicate coordinates * are preserved as much as possible. For geometries of dimension 2 (areal), * duplicate coordinates are generally removed due to the use of overlay * operations. * * @param geometry input geometry * @return a valid Geometry */ public NetTopologySuite.Geometries.Geometry makeValid(NetTopologySuite.Geometries.Geometry geometry) { // Input geometry is recursively exploded into a list of simple components List <NetTopologySuite.Geometries.Geometry> list = new(geometry.NumGeometries); decompose(geometry, list); // Each single component is made valid ICollection <NetTopologySuite.Geometries.Geometry> list2 = new List <NetTopologySuite.Geometries.Geometry>(); foreach (var component in list) { if (component is Point) { Point p = makePointValid((Point)component); if (!p.IsEmpty) { list2.Add(p); } } else if (component is LineString) { var geom = makeLineStringValid((LineString)component); for (int i = 0; i < geom.NumGeometries; i++) { if (!geom.GetGeometryN(i).IsEmpty) { list2.Add(geom.GetGeometryN(i)); } } } else if (component is Polygon) { var geom = makePolygonValid((Polygon)component); for (int i = 0; i < geom.NumGeometries; i++) { if (!geom.GetGeometryN(i).IsEmpty) { list2.Add(geom.GetGeometryN(i)); } } } else { //assert false : "Should never reach here"; } } list.Clear(); foreach (NetTopologySuite.Geometries.Geometry g in list2) { // If preserveGeomDim is true and original input geometry is not a GeometryCollection // components with a lower dimension than input geometry are removed if (preserveGeomDim && !geometry.GeometryType.Equals(NetTopologySuite.Geometries.Geometry.TypeNameGeometryCollection)) { removeLowerDimension(g, list, geometry.Dimension); } else { decompose(g, list); } } list2 = list; // In a MultiPolygon, polygons cannot touch or overlap each other // (adjacent polygons are not merged in the context of a mixed GeometryCollection) if (list2.Count > 1) { bool multiPolygon = true; foreach (var geom in list2) { if (geom.Dimension < Dimension.Surface) { multiPolygon = false; } } if (multiPolygon) { list2 = unionAdjacentPolygons(list2); } } if (0 == list2.Count) { GeometryFactory factory = geometry.Factory; if (geometry is Point) { return(factory.CreatePoint((Coordinate)null)); } else if (geometry is LinearRing) { return(factory.CreateLinearRing(EMPTY_COORD_ARRAY)); } else if (geometry is LineString) { return(factory.CreateLineString(EMPTY_COORD_ARRAY)); } else if (geometry is Polygon) { return(factory.CreatePolygon(factory.CreateLinearRing(EMPTY_COORD_ARRAY), EMPTY_RING_ARRAY)); } else if (geometry is MultiPoint) { return(factory.CreateMultiPoint(new Point[0])); } else if (geometry is MultiLineString) { return(factory.CreateMultiLineString(new LineString[0])); } else if (geometry is MultiPolygon) { return(factory.CreateMultiPolygon(new Polygon[0])); } else { return(factory.CreateGeometryCollection(new NetTopologySuite.Geometries.Geometry[0])); } } else { CoordinateSequenceFactory csFactory = geometry.Factory.CoordinateSequenceFactory; // Preserve 4th coordinate dimension as much as possible if preserveCoordDim is true if (preserveCoordDim && csFactory is PackedCoordinateSequenceFactory /*&& ((PackedCoordinateSequenceFactory)csFactory).Dimension == 4*/) { System.Collections.Generic.Dictionary <Coordinate, Double> map = new(); gatherDim4(geometry, map); list2 = restoreDim4(list2, map); } var result = geometry.Factory.BuildGeometry(list2); // If input geometry was a GeometryCollection and result is a simple geometry // Create a multi-geometry made of a single component if (geometry is GeometryCollection && !(result is GeometryCollection)) { if (geometry is MultiPoint && result is Point) { result = geometry.Factory.CreateMultiPoint(new Point[] { (Point)result }); } else if (geometry is MultiLineString && result is LineString) { result = geometry.Factory.CreateMultiLineString(new LineString[] { (LineString)result }); } else if (geometry is MultiPolygon && result is Polygon) { result = geometry.Factory.CreateMultiPolygon(new Polygon[] { (Polygon)result }); } } return(result); } }
/** * The method makes sure that outer and inner rings form valid LinearRings. * <p> * If outerRing is not a valid LinearRing, every linear component is * considered as a degenerated geometry of lower dimension (0 or 1) * </p> * <p> * If outerRing is a valid LinearRing but some innerRings are not, invalid * innerRings are transformed into LineString (or Point) and the returned * geometry may be a GeometryCollection of heterogeneous dimension. * </p> * * @param polygon simple Polygon to make valid * @return a Geometry which may not be a Polygon if the source Polygon is * invalid */ private NetTopologySuite.Geometries.Geometry makePolygonComponentsValid(Polygon polygon) { GeometryFactory factory = polygon.Factory; CoordinateSequence outerRingSeq = makeSequenceValid(polygon.ExteriorRing.CoordinateSequence, false, true); // The validated sequence of the outerRing does not form a valid LinearRing // -> build valid 0-dim or 1-dim geometry from all the rings if (outerRingSeq.Count == 0 || outerRingSeq.Count < 4) { List <NetTopologySuite.Geometries.Geometry> list = new(); if (outerRingSeq.Count > 0) { list.Add(makeLineStringValid(polygon.ExteriorRing)); } for (int i = 0; i < polygon.NumInteriorRings; i++) { NetTopologySuite.Geometries.Geometry g = makeLineStringValid(polygon.GetInteriorRingN(i)); if (!g.IsEmpty) { list.Add(g); } } if (0 == list.Count) { return(factory.CreatePolygon(outerRingSeq)); } else { return(factory.BuildGeometry(list)); } } // OuterRing forms a valid ring. // Inner rings may be degenerated else { List <LinearRing> innerRings = new(); List <NetTopologySuite.Geometries.Geometry> degeneratedRings = new(); for (int i = 0; i < polygon.NumInteriorRings; i++) { CoordinateSequence seq = makeSequenceValid(polygon.GetInteriorRingN(i).CoordinateSequence, false, true); if (seq.Count > 3) { innerRings.Add(factory.CreateLinearRing(seq)); } else if (seq.Count > 1) { degeneratedRings.Add(factory.CreateLineString(seq)); } else if (seq.Count == 1) { degeneratedRings.Add(factory.CreatePoint(seq)); } // seq.size == 0 } Polygon poly = factory.CreatePolygon(factory.CreateLinearRing(outerRingSeq), innerRings.ToArray()); if (0 == degeneratedRings.Count) { return(poly); } else { degeneratedRings.Insert(0, poly); return(factory.BuildGeometry(degeneratedRings)); } } }
public static IGeometry interiorPoint(Geometry g) { return g.InteriorPoint; }
public static IGeometry convexHull(Geometry g) { return g.ConvexHull(); }
public static IGeometry minimumBoundingCircle(Geometry g) { return (new MinimumBoundingCircle(g)).GetCircle(); }
public void ExecuteIntersectionQuery(Geometry geometry, FeatureDataSet ds) { ((ICanQueryLayer)_innerLayer).ExecuteIntersectionQuery(geometry, ds); }
public static IGeometry BufferLineSimplifier(Geometry g, double distance) { return BuildBufferLineSimplifiedSet(g, distance); }
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); }
public static IGeometry TranslateCentreToOrigin(Geometry g) { var centre = EnvelopeCentre(g); var trans = AffineTransformation.TranslationInstance(-centre.X, -centre.Y); return trans.Transform(g); }
public static IGeometry MinimumDiameterLine(Geometry g) { return (new MinimumDiameter(g)).Diameter; }
public static IGeometry boundary(Geometry g) { return g.Boundary; }
public static double MinimumDiameter(Geometry g) { return (new MinimumDiameter(g)).Diameter.Length; }
public static IGeometry centroid(Geometry g) { return g.Centroid; }
public static IGeometry MinimumBoundingCirclePoints(Geometry g) { return g.Factory.CreateLineString((new MinimumBoundingCircle(g)).GetExtremalPoints()); }
public static IGeometry densify(Geometry g, double distance) { return Densifier.Densify(g, distance); }
public static double MaximumDiameter(Geometry g) { return 2 * (new MinimumBoundingCircle(g)).GetRadius(); }
private bool CompareGeometries(Geometry a, Geometry b) { if (a != null && b != null && a.GetType().Name == b.GetType().Name) { Geometry aClone = (Geometry)a.Clone(); Geometry bClone = (Geometry)b.Clone(); aClone.Normalize(); bClone.Normalize(); return aClone.EqualsExact(bClone, _dTolerance); } return false; }
public static IGeometry Convert(IGeometryFactory factory, Geometry geometry) { throw new NotImplementedException(); }
public static DotSpatial.Topology.Geometry toDotSpatial(Geometry l) { if (l.GeometryType == "LineString") { return ToDotSpatialLineString((ILineString)l); } if (l.GeometryType == "Polygon") { Polygon p = l as Polygon; DotSpatial.Topology.Polygon dsp = ToDotSpatialPolygon((GeoAPI.Geometries.IPolygon)l); return (DotSpatial.Topology.Geometry)dsp; } return null; }
/// <summary> /// Creates a <c>Geometry</c> using the next token in the stream. /// </summary> /// <param name="tokens"> /// Tokenizer over a stream of text in Well-known Text /// format. The next tokens must form a <Geometry Tagged Text. /// </param> /// <returns>A <c>Geometry</c> specified by the next token /// in the stream.</returns> private NetTopologySuite.Geometries.Geometry ReadGeometryTaggedText(IList tokens) { /* * A new different implementation by Marc Jacquin: * this code manages also SRID values. */ NetTopologySuite.Geometries.Geometry returned = null; string sridValue = null; string type = tokens[0].ToString(); if (type == "SRID") //NOXLATE { sridValue = tokens[2].ToString(); // tokens.RemoveRange(0, 4); tokens.RemoveAt(0); tokens.RemoveAt(0); tokens.RemoveAt(0); tokens.RemoveAt(0); } else { type = GetNextWord(tokens); } if (type.Equals("POINT")) //NOXLATE { returned = ReadPointText(tokens); } else if (type.Equals("LINESTRING")) //NOXLATE { returned = ReadLineStringText(tokens); } else if (type.Equals("LINEARRING")) //NOXLATE { returned = ReadLinearRingText(tokens); } else if (type.Equals("POLYGON")) //NOXLATE { returned = ReadPolygonText(tokens); } else if (type.Equals("MULTIPOINT")) //NOXLATE { returned = ReadMultiPointText(tokens); } else if (type.Equals("MULTILINESTRING")) //NOXLATE { returned = ReadMultiLineStringText(tokens); } else if (type.Equals("MULTIPOLYGON")) //NOXLATE { returned = ReadMultiPolygonText(tokens); } else if (type.Equals("GEOMETRYCOLLECTION")) //NOXLATE { returned = ReadGeometryCollectionText(tokens); } else { throw new WktParseException(string.Format(Strings.ErrorParseUnknownType, type)); } if (returned == null) { throw new NullReferenceException(Strings.ErrorParseGeometryRead); } if (sridValue != null) { returned.SRID = Convert.ToInt32(sridValue); } return(returned); }