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."); }
private static bool IsSameStructurePolygon(Polygon g1, Polygon g2) { if (g1.NumInteriorRings != g2.NumInteriorRings) return false; // could check for both empty or nonempty here return true; }
public void CheckIsPointInRegion(double x, double y) { var geom = new NetTopologySuite.Geometries.Polygon( new LinearRing(new Coordinate[] { //逆时针绘制 new Coordinate(10, 0), new Coordinate(10, 10), new Coordinate(0, 10), new Coordinate(0, 0), new Coordinate(10, 0), })); //设置坐标系 geom.SRID = srid; var point = new NetTopologySuite.Geometries.Point(x, y) { SRID = srid }; //https://stackoverflow.com/questions/53820355/fast-find-if-points-belong-to-polygon-nettopologysuite-geometries-c-net-cor var prepGeom = NetTopologySuite.Geometries.Prepared.PreparedGeometryFactory.Prepare(geom); var isContain = prepGeom.Contains(point); Console.WriteLine(isContain ? $"点({x},{y})包含在面以内" : $"点({x},{y})不包含在面以内"); }
public VectorLayer getPolygonPoints(PointF points, VectorLayer veclayer) { //VectorLayer veclayer = (VectorLayer)m_viewBox.Map.GetLayerByName("province"); SharpMap.Layers.VectorLayer laySelected = new SharpMap.Layers.VectorLayer("Selection");; CustomTheme myTheme = new CustomTheme(FeatureColoured); ShapeFile vecshp = (ShapeFile)veclayer.DataSource; ShapeFile shp = vecshp; if (!shp.IsOpen) { shp.Open(); } FeatureDataSet featDataSet = new FeatureDataSet(); FeatureDataTable featDataTable = null; //将point的大地坐标转为经纬度 Projection pj = new Projection(); points = pj.GetLatLonFromXY(points, cfg.pjPara); // 获取feature数量 uint featCount = (uint)shp.GetFeatureCount(); for (uint index = 0; index < featCount; index++) { FeatureDataRow r = shp.GetFeature(index); GeoAPI.Geometries.Coordinate[] geomes = r.Geometry.Coordinates; double[] geomsX = new double[geomes.Length]; double[] geomsY = new double[geomes.Length]; for (int j = 0; j < geomes.Length; j++) { geomsX[j] = geomes[j].X; geomsY[j] = geomes[j].Y; } if ((points.X < geomsX.Min()) || (points.X > geomsX.Max()) || (points.Y < geomsY.Min()) || (points.Y > geomsY.Max())) { continue; } PointF p1 = new PointF(); p1.X = points.X; p1.Y = points.Y; if (InPolygon(geomes, p1)) { //首先把geomes传出去,供其他使用 ContourGeomes = geomes; //如果在某区域内,选中某个区域,放入新图层 laySelected.DataSource = new SharpMap.Data.Providers.GeometryProvider(shp.GetFeature(index)); polygon = ((NetTopologySuite.Geometries.Polygon)r.Geometry); laySelected.Style.Fill = new System.Drawing.SolidBrush(Color.HotPink); laySelected.CoordinateTransformation = veclayer.CoordinateTransformation; } } return(laySelected); }
TcsGeometry(this Polygon polygon) { var shell = polygon.Shell.TcsGeometry(); var holes = polygon.Holes.Select(TcsGeometry).ToList(); var result = new CoreSpatial.BasicGeometrys.Polygon(shell, holes); return(result); }
public ComplexPolygon GetComplexPolygonFromGeometry(Geometry geom) { ComplexPolygon output = new ComplexPolygon(); if (geom is NetTopologySuite.Geometries.Polygon) { NetTopologySuite.Geometries.Polygon p = geom as NetTopologySuite.Geometries.Polygon; if (p.ExteriorRing == null) { foreach (Coordinate coord in p.Coordinates) { output.Polygon.AddPoint(coord.X, coord.Y); } } else { foreach (Coordinate coord in p.ExteriorRing.Coordinates) { output.Polygon.AddPoint(coord.X, coord.Y); } } foreach (LineString lstr in p.InteriorRings) { Utils.Geometry.Polygon poly = new Utils.Geometry.Polygon(); foreach (Coordinate coord in lstr.Coordinates) { poly.AddPoint(coord.X, coord.Y); } output.SubPolygons.Add(poly); } } else if (geom is MultiPolygon) { MultiPolygon mp = geom as MultiPolygon; int geomIndex = 0; foreach (Geometry subGeom in mp.Geometries) { ComplexPolygon cp = GetComplexPolygonFromGeometry(subGeom); if (geomIndex == 0) { output.Polygon = cp.Polygon; output.SubPolygons.AddRange(cp.SubPolygons); } else { output.SubPolygons.AddRange(cp.Polygons); } geomIndex++; } } return(output); }
internal static IEnumerable <Polygon> ToElmaPolygons(this NetTopologySuite.Geometries.Polygon poly) { var p = new Polygon(poly.Shell); p.UpdateDecomposition(); yield return(p); foreach (var linearRing in poly.Holes) { p = new Polygon(linearRing); p.UpdateDecomposition(); yield return(p); } }
public IPath PolygonToDrawingPolygon(Geometry place, GeoArea drawingArea, double resolutionX, double resolutionY) { var lineSegmentList = new List <LinearLineSegment>(); NetTopologySuite.Geometries.Polygon p = (NetTopologySuite.Geometries.Polygon)place; var typeConvertedPoints = p.ExteriorRing.Coordinates.Select(o => new SixLabors.ImageSharp.PointF((float)((o.X - drawingArea.WestLongitude) * (1 / resolutionX)), (float)((o.Y - drawingArea.SouthLatitude) * (1 / resolutionY)))); var path = new SixLabors.ImageSharp.Drawing.Path(new LinearLineSegment(typeConvertedPoints.ToArray())).AsClosedPath(); foreach (var hole in p.InteriorRings) { typeConvertedPoints = hole.Coordinates.Select(o => new SixLabors.ImageSharp.PointF((float)((o.X - drawingArea.WestLongitude) * (1 / resolutionX)), (float)((o.Y - drawingArea.SouthLatitude) * (1 / resolutionY)))); var tempHole = new SixLabors.ImageSharp.Drawing.Path(new LinearLineSegment(typeConvertedPoints.ToArray())).AsClosedPath(); path = path.Clip(tempHole); } return(path); }
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); }
private async Task AddTestData() { var point = new NetTopologySuite.Geometries.Point(new Coordinate(10, 10)); point.SRID = srid; _dbContext.Cities.Add(new City() { CityName = "ChengDu", Location = point }); var line = new NetTopologySuite.Geometries.LineString(new Coordinate[] { new Coordinate(0, 0), new Coordinate(10, 0), new Coordinate(10, 10), new Coordinate(0, 10) }); line.SRID = srid; _dbContext.Roads.Add(new Road() { RoadName = "Road Name 1", Line = line }); var border = new NetTopologySuite.Geometries.Polygon(new LinearRing(new Coordinate[] { new Coordinate(0, 0), new Coordinate(10, 0), new Coordinate(10, 10), new Coordinate(0, 10), new Coordinate(0, 0) })); border.SRID = srid; _dbContext.Countries.Add(new Country() { CountryName = "China", Border = border }); await _dbContext.SaveChangesAsync(); }
public ActionResult GetStrassenabschnittByBbox(double minX, double minY, double maxX, double maxY) { try { Coordinate bottomLeft = new Coordinate(minX, minY); Coordinate topRight = new Coordinate(maxX, maxY); Coordinate bottomRight = new Coordinate(maxX, minY); Coordinate topLeft = new Coordinate(minX, maxY); ILinearRing linearRing = new LinearRing(new Coordinate[] { topLeft, topRight, bottomRight, bottomLeft, topLeft }); IGeometry filterGeom = new NetTopologySuite.Geometries.Polygon(linearRing, GISService.CreateGeometryFactory()); IList <StrassenabschnittGIS> strassenabschnitte = strassenabschnittGISService.GetCurrentBySpatialFilter(filterGeom); strassenabschnitte = strassenabschnitte.Where(s => s.Shape.Intersects(filterGeom)).ToList(); return(Content(geoJSONParseService.GenereateGeoJsonStringfromEntities(strassenabschnitte), "application/json")); } catch (Exception exc) { return(Content(GeoJSONStrings.GeoJSONFailure(exc.Message), "application/json")); } }
public IActionResult CreatePolygon(string countryName) { var geom = new NetTopologySuite.Geometries.Polygon( new LinearRing(new Coordinate[] { //逆时针绘制 new Coordinate(10, 0), new Coordinate(10, 10), new Coordinate(0, 10), new Coordinate(0, 0), new Coordinate(10, 0), })); //设置坐标系 geom.SRID = srid; _dbContext.Countries.Add(new Country() { CountryName = countryName, Border = geom }); _dbContext.SaveChanges(); return(Json("ok")); }
public VectorLayer getPolygonPoints(PointF points, VectorLayer veclayer) { //VectorLayer veclayer = (VectorLayer)m_viewBox.Map.GetLayerByName("province"); SharpMap.Layers.VectorLayer laySelected = new SharpMap.Layers.VectorLayer("Selection"); ; CustomTheme myTheme = new CustomTheme(FeatureColoured); ShapeFile vecshp = (ShapeFile)veclayer.DataSource; ShapeFile shp = vecshp; if (!shp.IsOpen) shp.Open(); FeatureDataSet featDataSet = new FeatureDataSet(); FeatureDataTable featDataTable = null; //将point的大地坐标转为经纬度 Projection pj = new Projection(); points = pj.GetLatLonFromXY(points,cfg.pjPara); // 获取feature数量 uint featCount = (uint)shp.GetFeatureCount(); for (uint index = 0; index < featCount; index++) { FeatureDataRow r = shp.GetFeature(index); GeoAPI.Geometries.Coordinate[] geomes = r.Geometry.Coordinates; double[] geomsX = new double[geomes.Length]; double[] geomsY = new double[geomes.Length]; for (int j = 0; j < geomes.Length; j++) { geomsX[j] = geomes[j].X; geomsY[j] = geomes[j].Y; } if ((points.X < geomsX.Min()) || (points.X > geomsX.Max()) || (points.Y < geomsY.Min()) || (points.Y > geomsY.Max())) { continue; } PointF p1 = new PointF(); p1.X = points.X; p1.Y = points.Y; if (InPolygon(geomes, p1)) { //首先把geomes传出去,供其他使用 ContourGeomes = geomes; //如果在某区域内,选中某个区域,放入新图层 laySelected.DataSource = new SharpMap.Data.Providers.GeometryProvider(shp.GetFeature(index)); polygon = ((NetTopologySuite.Geometries.Polygon)r.Geometry); laySelected.Style.Fill = new System.Drawing.SolidBrush(Color.HotPink); laySelected.CoordinateTransformation = veclayer.CoordinateTransformation; } } return laySelected; }
public void TestGetContains() { DaoCriteria crit = new DaoCriteria(); Coordinate[] coords = new Coordinate[5]; coords[0] = new Coordinate(99, 99); coords[1] = new Coordinate(201, 99); coords[2] = new Coordinate(201, 151); coords[3] = new Coordinate(99, 151); coords[4] = new Coordinate(99, 99); IGeometry poly = new Polygon(new LinearRing(coords)); poly.SRID = Srid; crit.Expressions.Add(new WithinExpression("Shape", poly)); IList<PointClass> points = _pointDao.Get(crit); Assert.AreEqual(6, points.Count, "Wrong number of points."); IList<LineClass> lines = _lineDao.Get(crit); Assert.AreEqual(1, lines.Count, "Wrong number of lines."); poly.SRID = Srid; IList<PolyClass> polys = _polyDao.Get(crit); Assert.AreEqual(1, polys.Count, "Wrong number of polygons."); }
public void EqualsNullThrowsBugFix() { var polygon = new Polygon(null); var result = polygon.Equals(null); Assert.IsNotNull(result); }
public void IntersectWhenEmptyTest() { var _cache = new SpatialCache<Coordinate, object, TestCacheObject>(); var _key1 = new Coordinate { X = 1.5, Y = 3.0 }; var _key2 = new Coordinate { X = 3.0, Y = 1.5 }; var _key3 = new Coordinate { X = 1.707210, Y = 1.006074 }; var _key4 = new Coordinate { X = 4.708210, Y = 4.006074 }; var _spatialItem1 = new SpatialCacheItem<Coordinate, object, TestCacheObject> { SpatialKey = _key1 }; var _spatialItem2 = new SpatialCacheItem<Coordinate, object, TestCacheObject> { SpatialKey = _key2 }; var _spatialItem3 = new SpatialCacheItem<Coordinate, object, TestCacheObject> { SpatialKey = _key3 }; var _spatialItem4 = new SpatialCacheItem<Coordinate, object, TestCacheObject> { SpatialKey = _key4 }; _cache.AddOrGetExisting(_spatialItem1.SpatialKey, _spatialItem1); _cache.AddOrGetExisting(_spatialItem2.SpatialKey, _spatialItem2); _cache.AddOrGetExisting(_spatialItem3.SpatialKey, _spatialItem3); _cache.AddOrGetExisting(_spatialItem4.SpatialKey, _spatialItem4); var _polygon = new Polygon(new LinearRing(new[] { new GeoAPI.Geometries.Coordinate(10, 40), new GeoAPI.Geometries.Coordinate(20, 40), new GeoAPI.Geometries.Coordinate(2, 1), new GeoAPI.Geometries.Coordinate(10, 10), new GeoAPI.Geometries.Coordinate(10, 40) })); var _items = _cache.Intersect(_polygon); Assert.AreEqual(0, _items.Count()); }
public void TestSimplifyBadPoly() { var geom = new WKTReader().Read("POLYGON ((1 1, 1 1, 1 1, 1 1, 1 1))"); var geom2 = new Polygon(new LinearRing(new Coordinate[] { new Coordinate(1, 1), new Coordinate(1, 1), new Coordinate(1, 1), new Coordinate(1, 1), new Coordinate(1, 1) })); Debug.WriteLine("Bad polygon: " + geom); var simple = DouglasPeuckerSimplifier.Simplify(geom, 0.1); Debug.WriteLine("Simple bad polygon: " + simple); Assert.AreEqual(geom.GetType(), simple.GetType()); Assert.AreNotEqual(geom, simple, "Simplify didn't do anything to this invalid polygon."); // This happens with JTS 1.9.0, 1.8.0 still returns GeometryCollection.Empty Assert.AreEqual(geom.GetType(), Polygon.Empty); }
private static Polygon CreateWKBPolygon(BinaryReader reader, WkbByteOrder byteOrder) { // Get the Number of rings in this Polygon. int numRings = (int) ReadUInt32(reader, byteOrder); Debug.Assert(numRings >= 1, "Number of rings in polygon must be 1 or more."); var externalRing = CreateWKBLinearRing(reader, byteOrder); var interiorRings = new ILinearRing[numRings]; // Create a new array of linearrings for the interior rings. for (int i = 0; i < (numRings - 1); i++) interiorRings[i] = CreateWKBLinearRing(reader, byteOrder); Polygon shell = new Polygon(externalRing, interiorRings); // Create and return the Poylgon. return shell; }
/// <summary> /// Converts a Polygon to <Polygon Text> format, then /// Appends it to the writer. /// </summary> /// <param name="polygon">The Polygon to process.</param> /// <param name="writer"></param> private static void AppendPolygonText(Polygon polygon, StringWriter writer) { if (polygon == null || polygon.IsEmpty) writer.Write("EMPTY"); else { writer.Write("("); AppendLineStringText(polygon.ExteriorRing as LineString, writer); for (int i = 0; i < polygon.InteriorRings.Length; i++) { writer.Write(", "); AppendLineStringText(polygon.InteriorRings[i] as LineString, writer); } writer.Write(")"); } }
private void M_DotMap_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) { if (m_AddFeaType != FeaType.None) { Coordinate coord = m_DotMap.PixelToProj(e.Location);//点击的屏幕未知转换成坐标系中的点 switch (m_AddFeaType) { case FeaType.Point: { CreatePointDlg f = UCVectorDataEditing.m_CreatePointDlg; if (f == null) { return; } var layer = f.m_PointLayer; IFeatureSet PointF = (layer as FeatureLayer).FeatureSet; GeoAPI.Geometries.IPoint pPoint = new NetTopologySuite.Geometries.Point(coord); IFeature currentFeature = PointF.AddFeature(pPoint); PointF.InitializeVertices(); m_DotMap.ResetBuffer(); } break; case FeaType.Polyline: { CreatePolylineDlg f = UCVectorDataEditing.m_CreatePolylineDlg; if (f == null) { return; } var layer = f.m_PolylineLayer; IFeatureSet LineF = (layer as FeatureLayer).FeatureSet; if (e.Button == System.Windows.Forms.MouseButtons.Left) { if (f.IsFirstPoint) { //一开始就要加入至少两个点 f.CoordList.Add(coord); f.CoordList.Add(coord); LineString line = new LineString(f.CoordList.ToArray()); IFeature lineFeature = LineF.AddFeature(line); f.IsFirstPoint = false; } else { LineF.Features.RemoveAt(LineF.Features.Count - 1); if (f.CoordList[0] == f.CoordList[1]) { f.CoordList.RemoveAt(1); } f.CoordList.Add(coord); LineString line = new LineString(f.CoordList.ToArray()); IFeature lineFeature = LineF.AddFeature(line); m_DotMap.ResetBuffer(); } } else if (e.Button == System.Windows.Forms.MouseButtons.Right) { LineF.InitializeVertices(); f.IsFirstPoint = true; f.CoordList.Clear(); m_DotMap.ResetBuffer(); } } break; case FeaType.Polygon: { CreatePolygonDlg f = UCVectorDataEditing.m_CreatePolygonDlg; if (f == null) { return; } var layer = f.m_PolygonLayer; IFeatureSet PolygonF = (layer as FeatureLayer).FeatureSet; if (e.Button == System.Windows.Forms.MouseButtons.Left) { if (f.IsFirstPoint) { for (int i = 0; i < 4; i++) { f.CoordList.Add(coord); } ILinearRing LineRing = new LinearRing(f.CoordList.ToArray()); NetTopologySuite.Geometries.Polygon pPolygon = new NetTopologySuite.Geometries.Polygon(LineRing); IFeature polygonFeature = PolygonF.AddFeature(pPolygon); f.IsFirstPoint = false; } else { PolygonF.Features.RemoveAt(PolygonF.Features.Count - 1); if (f.CoordList[0] == f.CoordList[1]) { f.CoordList.RemoveAt(1); } //组成面的点必须形成一个闭环 因此要先把最新加入的点去掉,加入绘制点之后再加入第一个点 f.CoordList.RemoveAt(f.CoordList.Count - 1); f.CoordList.Add(coord); f.CoordList.Add(f.CoordList[0]); ILinearRing LineRing = new LinearRing(f.CoordList.ToArray()); NetTopologySuite.Geometries.Polygon pPolygon = new NetTopologySuite.Geometries.Polygon(LineRing); IFeature lineFeature = PolygonF.AddFeature(pPolygon); m_DotMap.ResetBuffer(); } } else if (e.Button == System.Windows.Forms.MouseButtons.Right) { PolygonF.InitializeVertices(); f.IsFirstPoint = true; f.CoordList.Clear(); m_DotMap.ResetBuffer(); } } break; } } }
/// <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; }
/** See {@link #unwrapDateline(Geometry)}. */ private static int UnwrapDateline(Polygon poly) { var exteriorRing = poly.ExteriorRing; int cross = UnwrapDateline(exteriorRing); if (cross > 0) { for (int i = 0; i < poly.NumInteriorRings; i++) { var innerLineString = poly.GetInteriorRingN(i); UnwrapDateline(innerLineString); for (int shiftCount = 0; !exteriorRing.Contains(innerLineString); shiftCount++) { if (shiftCount > cross) throw new ArgumentException("The inner ring doesn't appear to be within the exterior: " + exteriorRing + " inner: " + innerLineString); ShiftGeomByX(innerLineString, 360); } } poly.GeometryChanged(); } return cross; }
public void ReadByGeoFilter_ReadWithWholeTriangleInBounds_ShouldReturnTriangle() { Envelope boundsWithWholeTriangle = new Envelope(-0.62331, 0.63774, -0.02304, 0.76942); // Arrange. m_TempFiles = new TempFileCloudUploader[] { new TempFileCloudUploader("test.shp", ShpFiles.Read("UnifiedChecksMaterial")), new TempFileCloudUploader("test.dbf", DbfFiles.Read("UnifiedChecksMaterial")), }; Polygon expectedTriangle = new Polygon(new LinearRing(new Coordinate[] { new Coordinate(0.068181818181818,0.578282828282829), new Coordinate(0.421717171717172,0.070707070707071), new Coordinate(-0.457070707070707,0.080808080808081), new Coordinate(0.068181818181818,0.578282828282829), })); string expectedShapeMetadata = "Triangle"; m_shapeDataReader = new ShapeDataReader(new ShapefileStreamProviderRegistry(GetProvider(m_TempFiles[0].Path), GetProvider(m_TempFiles[1].Path))); // Act. IEnumerable<IShapefileFeature> results = m_shapeDataReader.ReadByMBRFilter(boundsWithWholeTriangle); // Assert. Assert.IsNotNull(results); IShapefileFeature result = results.Single(); Assert.IsNotNull(result); Assert.IsInstanceOf<ShapefileFeature>(result); Assert.AreEqual(((ShapefileFeature)result).FeatureId, 1); Assert.IsNotNull(result.Attributes); HelperMethods.AssertPolygonsEqual(result.Geometry as IPolygon, expectedTriangle); object shapeNameData = result.Attributes["ShapeName"]; Assert.IsInstanceOf<string>(shapeNameData); Assert.AreEqual((string)shapeNameData, expectedShapeMetadata); }
/// <summary> /// Gets the geometry for the triangles in a triangulated subdivision as a <see cref="IGeometryCollection"/> /// of triangular <see cref="IPolygon"/>s. /// </summary> /// <param name="geomFact">the GeometryFactory to use</param> /// <returns>a GeometryCollection of triangular Polygons</returns> public IGeometryCollection GetTriangles(IGeometryFactory geomFact) { var triPtsList = GetTriangleCoordinates(false); IPolygon[] tris = new Polygon[triPtsList.Count]; int i = 0; foreach (var triPt in triPtsList) { tris[i++] = geomFact .CreatePolygon(geomFact.CreateLinearRing(triPt), null); } return geomFact.CreateGeometryCollection(tris); }
public void IntersectWhenRegionNameTest() { const string REGION = "TestRegion1"; var _cache = new SpatialCache<Coordinate, object, TestCacheObject>(); var _key1 = new Coordinate { X = 1.0, Y = 3.0 }; var _key2 = new Coordinate { X = 1.5, Y = 1.5 }; var _key3 = new Coordinate { X = 1.5, Y = 2.5 }; var _key4 = new Coordinate { X = 6.0, Y = 2.5 }; var _spatialItem1 = new SpatialCacheItem<Coordinate, object, TestCacheObject> { SpatialKey = _key1 }; var _spatialItem2 = new SpatialCacheItem<Coordinate, object, TestCacheObject> { SpatialKey = _key2 }; var _spatialItem3 = new SpatialCacheItem<Coordinate, object, TestCacheObject> { SpatialKey = _key3 }; var _spatialItem4 = new SpatialCacheItem<Coordinate, object, TestCacheObject> { SpatialKey = _key4 }; _cache.AddOrGetExisting(_spatialItem1.SpatialKey, _spatialItem1, REGION); _cache.AddOrGetExisting(_spatialItem2.SpatialKey, _spatialItem2, "TestRegion2"); _cache.AddOrGetExisting(_spatialItem3.SpatialKey, _spatialItem3, "TestRegion3"); _cache.AddOrGetExisting(_spatialItem4.SpatialKey, _spatialItem4, "TestRegion4"); var _polygon = new Polygon(new LinearRing(new[] { new GeoAPI.Geometries.Coordinate(1, 4), new GeoAPI.Geometries.Coordinate(2, 4), new GeoAPI.Geometries.Coordinate(2, 1), new GeoAPI.Geometries.Coordinate(1, 1), new GeoAPI.Geometries.Coordinate(1, 4) })); var _items = _cache.Intersect(_polygon, REGION); Assert.AreEqual(1, _items.Count()); }
/// <summary> /// Writes a polygon. /// </summary> /// <param name="poly">The polygon to be written.</param> /// <param name="bWriter">Stream to write to.</param> /// <param name="byteorder">Byte order</param> private static void WritePolygon(Polygon poly, BinaryWriter bWriter, WkbByteOrder byteorder) { //Get the number of rings in this polygon. int numRings = poly.InteriorRings.Length + 1; //Write the number of rings to the stream (add one for the shell) WriteUInt32((uint) numRings, bWriter, byteorder); //Write the exterior of this polygon. WriteLineString(poly.ExteriorRing as LineString, bWriter, byteorder); //Loop on the number of rings - 1 because we already wrote the shell. foreach (LinearRing lr in poly.InteriorRings) //Write the (lineString)LinearRing. WriteLineString(lr, bWriter, byteorder); }
// draws polygon and then path around polygon private void drawPolygon(Polygon ge, Graphics gr, Style c) { System.Drawing.Drawing2D.GraphicsPath gp = CreatePath(ge.ExteriorRing); var hulls = ge.InteriorRings; for (int h = 0; h < hulls.Count(); h++) gp.AddPath(CreatePath(hulls[h]), false); gp.FillMode = System.Drawing.Drawing2D.FillMode.Alternate; gr.FillPath(c.brush, gp); if (c.pen.Width > 0) gr.DrawPath(c.pen, gp); }
public void MoveFeature(Coordinate coord) { if (selectFea == null || m_CurrentFeaLyr == null) { return; } //确保目标图层只选中编辑的那一个要素,因为后面会把选中要素移除 m_CurrentFeaLyr.UnSelectAll(); m_CurrentFeaLyr.Selection.Clear(); m_CurrentFeaLyr.Select(selectFea); //move Coordinate moveCoord = new Coordinate(); moveCoord.X = coord.X - selectFea.Geometry.Coordinates[0].X; moveCoord.Y = coord.Y - selectFea.Geometry.Coordinates[0].Y; if (selectFea.FeatureType == FeatureType.Point) { Coordinate resultCoord = new Coordinate(); //move resultCoord.X = selectFea.Geometry.Coordinate.X + moveCoord.X; resultCoord.Y = selectFea.Geometry.Coordinate.Y + moveCoord.Y; IPoint pPoint = new NetTopologySuite.Geometries.Point(resultCoord); lFeaM = m_InputFeaSet.AddFeature(pPoint); for (int i = 0; i < selectFea.DataRow.ItemArray.Count(); i++) { lFeaM.DataRow[i] = selectFea.DataRow[i]; } } else if (selectFea.FeatureType == FeatureType.Line) { //move for (int i = 0; i < selectFea.Geometry.NumPoints; i++) { Coordinate resultCoord = new Coordinate(); resultCoord.X = selectFea.Geometry.Coordinates[i].X + moveCoord.X; resultCoord.Y = selectFea.Geometry.Coordinates[i].Y + moveCoord.Y; CoordList.Add(resultCoord); } ILineString pLine = new LineString(CoordList.ToArray()); lFeaM = m_InputFeaSet.AddFeature(pLine); for (int i = 0; i < selectFea.DataRow.ItemArray.Count(); i++) { lFeaM.DataRow[i] = selectFea.DataRow[i]; } CoordList.Clear(); } else if (selectFea.FeatureType == FeatureType.Polygon) { //move for (int i = 0; i < selectFea.Geometry.NumPoints; i++) { Coordinate resultCoord = new Coordinate(); resultCoord.X = selectFea.Geometry.Coordinates[i].X + moveCoord.X; resultCoord.Y = selectFea.Geometry.Coordinates[i].Y + moveCoord.Y; CoordList.Add(resultCoord); } ILinearRing LineRing = new LinearRing(CoordList.ToArray()); IPolygon pPolygon = new NetTopologySuite.Geometries.Polygon(LineRing); lFeaM = m_InputFeaSet.AddFeature(pPolygon); for (int i = 0; i < selectFea.DataRow.ItemArray.Count(); i++) { lFeaM.DataRow[i] = selectFea.DataRow[i]; } CoordList.Clear(); } //m_CurrentFeaLyr.FeatureSet.AddFeature(lFeaM.Geometry); m_CurrentFeaLyr.RemoveSelectedFeatures(); MainWindow.m_DotMap.ResetBuffer(); MainWindow.m_DotMap.Refresh(); if (MessageBox.Show("Save edit?", "", MessageBoxButton.YesNo) == MessageBoxResult.Yes) { m_CurrentFeaLyr.FeatureSet.Save(); MessageBox.Show("Save successfully!"); } //移除图层重新加载,因为底层bug 移动节点之后选择要素会报错。 MainWindow.m_AddFeaType = Enum.FeaType.None; MainWindow.m_DotMap.FunctionMode = FunctionMode.None; MainWindow.m_DotMap.Cursor = System.Windows.Forms.Cursors.Default; string shpPath = m_CurrentFeaLyr.FeatureSet.FilePath; string name = m_CurrentFeaLyr.LegendText; var symbol = m_CurrentFeaLyr.Symbolizer; var extent = m_CurrentFeaLyr.Extent; IFeatureSet s = Shapefile.Open(shpPath); MainWindow.m_DotMap.Layers.Remove(m_CurrentFeaLyr as IMapLayer); var result = MainWindow.m_DotMap.Layers.Add(s); result.Symbolizer = symbol; result.Projection = MainWindow.m_DotMap.Projection; result.LegendText = name; //result.Select((result as FeatureLayer).FeatureSet.Features[(result as FeatureLayer).FeatureSet.Features.Count - 1]); this.Close(); }
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); }
/// <summary> /// Converts a Polygon to <Polygon Tagged Text> format, /// then Appends it to the writer. /// </summary> /// <param name="polygon">Th Polygon to process.</param> /// <param name="writer">The stream writer to Append to.</param> private static void AppendPolygonTaggedText(Polygon polygon, StringWriter writer) { writer.Write("POLYGON "); AppendPolygonText(polygon, writer); }
public void MoveNode(Coordinate coord) { GeoAPI.Geometries.IPoint pPoint = new NetTopologySuite.Geometries.Point(coord); //确保目标图层只选中编辑的那一个要素,因为后面会把选中要素移除 m_CurrentFeaLyr.UnSelectAll(); m_CurrentFeaLyr.Selection.Clear(); m_CurrentFeaLyr.Select(selectFea); if (AllPointLayer?.Selection.Count == 0 || Points?.Count == 0 || selectFea == null || m_CurrentFeaLyr == null) { return; } //移除点图层选中要素,并用pPoint替换选中点 IFeature resFea = AllPointLayer.FeatureSet.AddFeature(pPoint); bool hasAdd = false; foreach (var fea in AllPointLayer.Selection.ToFeatureList()) { for (int i = 0; i < Points.Count; i++) { if (Points[i].Intersects(fea.Geometry)) { Points[i] = pPoint; hasAdd = true; break; } } if (hasAdd) { break; } } AllPointLayer.RemoveSelectedFeatures(); //AllPointLayer.UnSelectAll(); //AllPointLayer.Selection.Clear(); AllPointLayer.FeatureSet.Save(); List <Coordinate> temp = new List <Coordinate>(); IFeature resultFeature = null; foreach (var point in Points) { temp.Add(new Coordinate(point.X, point.Y)); } if (selectFea.FeatureType == FeatureType.Line) { LineString line = new LineString(temp.ToArray()); try { resultFeature = m_InputFeaSet.AddFeature(line); } catch { resultFeature = m_InputFeaSet.AddFeature(line); } resultFeature.DataRow.BeginEdit(); for (int i = 0; i < resultFeature.DataRow.ItemArray.Count(); i++) { resultFeature.DataRow[i] = selectFea.DataRow[i]; } resultFeature.DataRow.EndEdit(); } else if (selectFea.FeatureType == FeatureType.Polygon) { ILinearRing LineRing = new LinearRing(temp.ToArray()); NetTopologySuite.Geometries.Polygon pPolygon = new NetTopologySuite.Geometries.Polygon(LineRing); try { resultFeature = m_InputFeaSet.AddFeature(pPolygon); } catch { resultFeature = m_InputFeaSet.AddFeature(pPolygon); } resultFeature.DataRow.BeginEdit(); for (int i = 0; i < resultFeature.DataRow.ItemArray.Count(); i++) { resultFeature.DataRow[i] = selectFea.DataRow[i]; } resultFeature.DataRow.EndEdit(); } m_CurrentFeaLyr.RemoveSelectedFeatures(); //this.selectFea = resultFeature; //this.ReBinding(); //m_CurrentFeaLyr.Select(selectFea); MainWindow.m_DotMap.ResetBuffer(); MainWindow.m_DotMap.Refresh(); if (MessageBox.Show("Save edit?", "", MessageBoxButton.YesNo) == MessageBoxResult.Yes) { m_CurrentFeaLyr.FeatureSet.Save(); MessageBox.Show("Save successfully!"); } //移除图层重新加载,因为底层bug 移动节点之后选择要素会报错。 MainWindow.m_AddFeaType = Enum.FeaType.None; MainWindow.m_DotMap.FunctionMode = FunctionMode.None; MainWindow.m_DotMap.Cursor = System.Windows.Forms.Cursors.Default; var layer = MainWindow.m_DotMap.Layers.Where(u => u.LegendText == "AllNodes").FirstOrDefault(); if (layer != null) { MainWindow.m_DotMap.Layers.Remove(layer); } string shpPath = m_CurrentFeaLyr.FeatureSet.FilePath; string name = m_CurrentFeaLyr.LegendText; var symbol = m_CurrentFeaLyr.Symbolizer; var extent = m_CurrentFeaLyr.Extent; IFeatureSet s = Shapefile.Open(shpPath); MainWindow.m_DotMap.Layers.Remove(m_CurrentFeaLyr as IMapLayer); var result = MainWindow.m_DotMap.Layers.Add(s); result.Symbolizer = symbol; result.Projection = MainWindow.m_DotMap.Projection; result.LegendText = name; result.Select((result as FeatureLayer).FeatureSet.Features[(result as FeatureLayer).FeatureSet.Features.Count - 1]); result.ZoomToSelectedFeatures(); this.Close(); }
public void ReadByGeoFilter_ReadAllInBounds_ShouldReturnAllShapesAndCorrectDbfData() { // Arrange. m_TempFiles = new TempFileCloudUploader[] { new TempFileCloudUploader("test.shp", ShpFiles.Read("UnifiedChecksMaterial")), new TempFileCloudUploader("test.dbf", DbfFiles.Read("UnifiedChecksMaterial")), }; IPolygon[] expectedResult = new Polygon[] { new Polygon(new LinearRing(new Coordinate[] { new Coordinate(-0.815656565656566, -0.439393939393939), new Coordinate(-0.353535353535354, -0.795454545454545), new Coordinate(-0.888888888888889,-0.929292929292929), new Coordinate(-1.151515151515152, -0.419191919191919), new Coordinate(-0.815656565656566,-0.439393939393939), })), new Polygon(new LinearRing(new Coordinate[] { new Coordinate(0.068181818181818,0.578282828282829), new Coordinate(0.421717171717172,0.070707070707071), new Coordinate(-0.457070707070707,0.080808080808081), new Coordinate(0.068181818181818,0.578282828282829), })) }; string[] expectedShapeMetadata = new string[] { "Rectangle", "Triangle" }; m_shapeDataReader = new ShapeDataReader(new ShapefileStreamProviderRegistry(GetProvider(m_TempFiles[0].Path), GetProvider(m_TempFiles[1].Path))); // Act. IEnumerable<IShapefileFeature> results = m_shapeDataReader.ReadByMBRFilter(m_shapeDataReader.ShapefileBounds); // Assert. Assert.IsNotNull(results); int currIndex = 0; foreach (IShapefileFeature result in results) { Assert.IsNotNull(result); Assert.IsInstanceOf<ShapefileFeature>(result); ShapefileFeature sf = (ShapefileFeature)result; Assert.AreEqual(sf.FeatureId, currIndex); Assert.IsNotNull(result.Attributes); HelperMethods.AssertPolygonsEqual(result.Geometry as IPolygon, expectedResult[currIndex]); object shapeNameData = result.Attributes["ShapeName"]; Assert.IsInstanceOf<string>(shapeNameData); Assert.AreEqual((string)shapeNameData, expectedShapeMetadata[currIndex++]); } }
/// <summary> /// /// </summary> public CoversTest() : base() { polygon1 = new Polygon(new LinearRing(array1)); polygon2 = new Polygon(new LinearRing(array2)); }
public void ReadByGeoFilter_ReadWithRectangleMBRPartiallyInBounds_ShouldReturnRectangle() { Envelope boundsWithWholeTriangle = new Envelope(-1.17459, -1.00231, -1.09803, -0.80861); // Arrange. m_TempFiles = new TempFileCloudUploader[] { new TempFileCloudUploader("test.shp", ShpFiles.Read("UnifiedChecksMaterial")), new TempFileCloudUploader("test.dbf", DbfFiles.Read("UnifiedChecksMaterial")), }; Polygon expectedTriangle = new Polygon(new LinearRing(new Coordinate[] { new Coordinate(-0.815656565656566, -0.439393939393939), new Coordinate(-0.353535353535354, -0.795454545454545), new Coordinate(-0.888888888888889,-0.929292929292929), new Coordinate(-1.151515151515152, -0.419191919191919), new Coordinate(-0.815656565656566,-0.439393939393939), })); string expectedShapeMetadata = "Rectangle"; m_shapeDataReader = new ShapeDataReader(new ShapefileStreamProviderRegistry(GetProvider(m_TempFiles[0].Path), GetProvider(m_TempFiles[1].Path))); // Act. IEnumerable<IShapefileFeature> results = m_shapeDataReader.ReadByMBRFilter(boundsWithWholeTriangle); // Assert. Assert.IsNotNull(results); IShapefileFeature result = results.Single(); Assert.IsNotNull(result); Assert.IsInstanceOf<ShapefileFeature>(result); Assert.AreEqual(((ShapefileFeature)result).FeatureId, 0); Assert.IsNotNull(result.Attributes); HelperMethods.AssertPolygonsEqual(result.Geometry as IPolygon, expectedTriangle); object shapeNameData = result.Attributes["ShapeName"]; Assert.IsInstanceOf<string>(shapeNameData); Assert.AreEqual((string)shapeNameData, expectedShapeMetadata); }
public void TestGetIntersects() { DaoCriteria crit = new DaoCriteria(); Coordinate[] coords = new Coordinate[5]; coords[0] = new Coordinate(100, 100); coords[1] = new Coordinate(200, 100); coords[2] = new Coordinate(200, 150); coords[3] = new Coordinate(100, 150); coords[4] = new Coordinate(100, 100); Geometry poly = new Polygon(new LinearRing(coords)); crit.Expressions.Add(new IntersectsExpression("Shape", poly)); IList<PointClass> points = _pointDao.Get(crit); Assert.AreEqual(6, points.Count, "Wrong number of points."); IList<LineClass> lines = _lineDao.Get(crit); Assert.AreEqual(2, lines.Count, "Wrong number of lines."); IList<PolyClass> polys = _polyDao.Get(crit); Assert.AreEqual(2, polys.Count, "Wrong number of polygons."); }
/// <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; }
static void Main(string[] args) { Console.OutputEncoding = Encoding.UTF8; var inputFile = "google_export.kmz"; var outputPath = "../hugo/content/shops/"; var outputDirectory = Directory.CreateDirectory(outputPath); Console.WriteLine("Cleaning up old files..."); foreach (var file in outputDirectory.EnumerateFiles("*.html")) { file.Delete(); } Console.WriteLine("Done."); var generatedPostDateString = "2019-06-09"; var colourMapping = getShopColourMapping(); var shopTypeMapping = getShopTypeMapping(); var districtBoundaryJson = File.ReadAllText("hksar_18_district_boundary.json", Encoding.UTF8); var geoJsonReader = new NetTopologySuite.IO.GeoJsonReader(); var featureCollection = geoJsonReader.Read <NetTopologySuite.Features.FeatureCollection>(districtBoundaryJson); var districtLocators = new Dictionary <string, IPointOnGeometryLocator>(featureCollection.Count + 1); // custom polygon for shops on map that have no physical presence var virtualShopCoordinates = new Coordinate[] { new Coordinate(114.0566591, 22.3235484), new Coordinate(114.1542176, 22.3105200), new Coordinate(114.1533560, 22.2981202), new Coordinate(114.1337037, 22.2922693), new Coordinate(114.1169433, 22.2812754), new Coordinate(114.1167716, 22.2423337), new Coordinate(114.0575151, 22.2418568), new Coordinate(114.0566591, 22.3235484), }; var virtualShopPolygon = new NetTopologySuite.Geometries.Polygon(new NetTopologySuite.Geometries.LinearRing(virtualShopCoordinates)); districtLocators.Add("網上商店", new IndexedPointInAreaLocator(virtualShopPolygon)); foreach (NetTopologySuite.Features.Feature feature in featureCollection) { districtLocators.Add(feature.Attributes["地區"].ToString(), new IndexedPointInAreaLocator(feature.Geometry)); } Stopwatch sw = Stopwatch.StartNew(); var counter = 0; { KmlFile kmlFile; using (var zipStream = File.OpenRead(inputFile)) using (var archive = new ZipArchive(zipStream, ZipArchiveMode.Read)) { var entry = archive.GetEntry("doc.kml"); using (var kmlStream = entry.Open()) using (var kmlStreamReader = new StreamReader(kmlStream)) using (var memoryStream = new MemoryStream()) using (var memoryStreamWriter = new StreamWriter(memoryStream)) { char[] buffer = new char[1024]; var bufferSpan = new Span <char>(buffer); int charactersRead; while ((charactersRead = kmlStreamReader.Read(bufferSpan)) > 0) { foreach (var character in bufferSpan.Slice(0, charactersRead)) { // remove invalid control characters from XML if (!Char.IsControl(character)) { memoryStreamWriter.Write(character); } } } memoryStreamWriter.Flush(); memoryStream.Seek(0, SeekOrigin.Begin); kmlFile = KmlFile.Load(memoryStream); } } if (kmlFile.Root is Kml kml) { // sample styleUrl: #icon-1507-0288D1 var styleUrlRegex = new Regex(@"^#icon-(\d+)-(\w+)"); // handle shop name collision cases var nameCountDict = new Dictionary <string, int>(); var invalidFileNameChars = new HashSet <char> { '<', '>', ':', '"', '/', '\\', '|', '?', '*', '#', '.', '\r', '\n' }; var reasonToEndRegex = new Regex(@"\b(原因|官方資訊)[\s\S]+", RegexOptions.Compiled); var hyperlinkRegex = new Regex(@"\b(?<!"")(https?://[^ <>()""]+)", RegexOptions.Compiled); foreach (var placemark in kml.Flatten().OfType <Placemark>()) // for testing: .Take(200)) { var lat = 0.0; var lng = 0.0; var district = "不詳"; if (placemark.Geometry is SharpKml.Dom.Point point) { lat = point.Coordinate.Latitude; lng = point.Coordinate.Longitude; foreach (var entry in districtLocators) { if (PointOnGeometryLocatorExtensions.Intersects(entry.Value, new NetTopologySuite.Geometries.Coordinate(lng, lat))) { district = entry.Key; break; } } } var nameBuilder = new StringBuilder(100); var fileNameBuilder = new StringBuilder(100); foreach (char c in placemark.Name) { // remove newlines for shop name if (c != '\r' && c != '\n') { nameBuilder.Append(c); } // remove invalid chars for file name if (!invalidFileNameChars.Contains(c)) { if (c == ' ') { // replace space in file name fileNameBuilder.Append('-'); } else { fileNameBuilder.Append(c); } } } // trim both names and prepend lat-lng to file name var name = nameBuilder.ToString().Trim(); var fileName = $"{lat.ToString("0.000")}-{lng.ToString("0.000")}-{fileNameBuilder.ToString().Trim('-')}"; // truncate file name to avoid crashing netlify build var fileNameStringInfo = new StringInfo(fileName); if (fileNameStringInfo.LengthInTextElements > 70) { fileName = fileNameStringInfo.SubstringByTextElements(0, 70) + "…"; } if (nameCountDict.TryGetValue(fileName, out int existingCount)) { int count = existingCount + 1; nameCountDict[fileName] = count; fileName = $"{fileName}-{count}"; } else { nameCountDict[fileName] = 1; } var colour = ""; var type = ""; string styleUrlString = placemark.StyleUrl.ToString(); var match = styleUrlRegex.Match(styleUrlString); if (match.Success) { // 1: shop type if (shopTypeMapping.TryGetValue(match.Groups[1].Value, out string shopType)) { type = shopType; } else { Console.WriteLine($"Unknown shop type: {match.Groups[1].Value} for {name}"); type = "種類不明"; } // 2: shop colour colour = colourMapping[match.Groups[2].Value]; } var description = placemark.Description?.Text; if (description == null) { Console.WriteLine($"Warning: Null description encountered: {name}"); description = ""; } using (var fileWriter = new StreamWriter(Path.Combine(outputPath, $"{fileName}.html"), false)) { // front matter fileWriter.WriteLine("---"); fileWriter.WriteLine($"title: '{name.Replace("'", "''")}'"); fileWriter.WriteLine($"date: {generatedPostDateString}"); fileWriter.WriteLine($"districts: {district}"); fileWriter.WriteLine($"colours: {colour}"); fileWriter.WriteLine($"categories: {type}"); fileWriter.WriteLine($"lat: {lat}"); fileWriter.WriteLine($"lng: {lng}"); fileWriter.WriteLine("---"); description = hyperlinkRegex.Replace(description, "<a href=\"$1\">$1</a>"); // description HTML if (colour == "黃店") { fileWriter.WriteLine(reasonToEndRegex.Replace(description, "")); } else { fileWriter.WriteLine(description); } } if (++counter % 100 == 0) { Console.WriteLine($"Processed {counter} records"); } } } } sw.Stop(); Console.WriteLine($"Total time taken to process {counter} records: {sw.Elapsed.TotalSeconds} seconds"); }
public void ReadByGeoFilter_ReadWithWholeRectangleInBoundsAndFlagSetToTrue_ShouldReturnRectangle() { Envelope boundsWithWholeTriangle = new Envelope(-1.39510, -0.12716, -1.13938, -0.22977); // Arrange. m_TempFiles = new TempFileWriter[] { new TempFileWriter("test.shp", ShpFiles.Read("UnifiedChecksMaterial")), new TempFileWriter("test.dbf", DbfFiles.Read("UnifiedChecksMaterial")), }; Polygon expectedTriangle = new Polygon(new LinearRing(new Coordinate[] { new Coordinate(-0.815656565656566, -0.439393939393939), new Coordinate(-0.353535353535354, -0.795454545454545), new Coordinate(-0.888888888888889,-0.929292929292929), new Coordinate(-1.151515151515152, -0.419191919191919), new Coordinate(-0.815656565656566,-0.439393939393939), })); string expectedShapeMetadata = "Rectangle"; m_shapeDataReader = new ShapeDataReader(m_TempFiles[0].Path); // Act. IEnumerable<IShapefileFeature> results = m_shapeDataReader.ReadByMBRFilter(boundsWithWholeTriangle, true); // Assert. Assert.IsNotNull(results); IShapefileFeature result = results.Single(); Assert.IsNotNull(result); Assert.IsInstanceOf<ShapefileFeature>(result); Assert.AreEqual(((ShapefileFeature)result).FeatureId, 0); Assert.IsNotNull(result.Attributes); HelperMethods.AssertPolygonsEqual(result.Geometry as IPolygon, expectedTriangle); object shapeNameData = result.Attributes["ShapeName"]; Assert.IsInstanceOf<string>(shapeNameData); Assert.AreEqual((string)shapeNameData, expectedShapeMetadata); }
public void ReadAllShapes_ReadAllPolygonsFromUnifiedWithNullAtEnd_ShouldReturnCorrectValues() { // Arrange. m_TmpFile = new TempFileWriter("UnifiedChecksMaterial.shp", ShpFiles.Read("UnifiedChecksMaterialNullAtEnd")); m_Reader = new IO.ShapeFile.Extended.ShapeReader(m_TmpFile.Path); IGeometryFactory factory = new GeometryFactory(); IPolygon[] expectedResult = new Polygon[] { new Polygon(new LinearRing(new Coordinate[] { new Coordinate(-0.815656565656566, -0.439393939393939), new Coordinate(-0.353535353535354, -0.795454545454545), new Coordinate(-0.888888888888889,-0.929292929292929), new Coordinate(-1.151515151515152, -0.419191919191919), new Coordinate(-0.815656565656566,-0.439393939393939), })), new Polygon(new LinearRing(new Coordinate[] { new Coordinate(0.068181818181818,0.578282828282829), new Coordinate(0.421717171717172,0.070707070707071), new Coordinate(-0.457070707070707,0.080808080808081), new Coordinate(0.068181818181818,0.578282828282829), })) }; // Act. IGeometry[] shapes = m_Reader.ReadAllShapes(factory).ToArray(); Assert.IsNotNull(shapes); Assert.AreEqual(shapes.Length, 2); for (int i = 0; i < shapes.Length; i++) { Assert.IsInstanceOf<IPolygon>(shapes[i]); HelperMethods.AssertPolygonsEqual(shapes[i] as IPolygon, expectedResult[i]); } }
public void ReadShapeAtIndex_ReadUnifiedCheckMaterialWithNulLInMiddle_ShouldReturnBothShapesCorrectly() { // Arrange. m_TmpFile = new TempFileWriter("shape.shp", ShpFiles.Read("UnifiedChecksMaterialNullInMiddle")); m_Reader = new IO.ShapeFile.Extended.ShapeReader(m_TmpFile.Path); IGeometryFactory factory = new GeometryFactory(); IPolygon[] expectedResult = new Polygon[] { new Polygon(new LinearRing(new Coordinate[] { new Coordinate(-0.815656565656566, -0.439393939393939), new Coordinate(-0.353535353535354, -0.795454545454545), new Coordinate(-0.888888888888889,-0.929292929292929), new Coordinate(-1.151515151515152, -0.419191919191919), new Coordinate(-0.815656565656566,-0.439393939393939), })), new Polygon(new LinearRing(new Coordinate[] { new Coordinate(0.068181818181818,0.578282828282829), new Coordinate(0.421717171717172,0.070707070707071), new Coordinate(-0.457070707070707,0.080808080808081), new Coordinate(0.068181818181818,0.578282828282829), })) }; // Act. for (int i = 0; i < expectedResult.Length; i++) { IGeometry result = m_Reader.ReadShapeAtIndex(i, factory); Assert.IsNotNull(result); Assert.IsInstanceOf<IPolygon>(result); HelperMethods.AssertPolygonsEqual(expectedResult[i], result as IPolygon); } }
public void ReadShapeAtIndex_ReadSecondUnifiedCheckMaterialShape_ShouldReturnTriangle() { // Arrange. m_TmpFile = new TempFileWriter("shape.shp", ShpFiles.Read("UnifiedChecksMaterial")); m_Reader = new IO.ShapeFile.Extended.ShapeReader(m_TmpFile.Path); IGeometryFactory factory = new GeometryFactory(); Polygon expectedPolygon = new Polygon(new LinearRing(new Coordinate[] { new Coordinate(0.068181818181818,0.578282828282829), new Coordinate(0.421717171717172,0.070707070707071), new Coordinate(-0.457070707070707,0.080808080808081), new Coordinate(0.068181818181818,0.578282828282829), })); // Act. IGeometry polygon = m_Reader.ReadShapeAtIndex(1, factory); Assert.IsNotNull(polygon); Assert.IsInstanceOf<IPolygon>(polygon); HelperMethods.AssertPolygonsEqual(polygon as IPolygon, expectedPolygon); }
public void ReadShapeAtIndex_ReadFirstUnifiedCheckMaterialShape_ShouldReturnRectangle() { // Arrange. m_TmpFile = new TempFileWriter("shape.shp", ShpFiles.Read("UnifiedChecksMaterial")); m_Reader = new IO.ShapeFile.Extended.ShapeReader(m_TmpFile.Path); IGeometryFactory factory = new GeometryFactory(); Polygon expectedPolygon = new Polygon(new LinearRing(new Coordinate[] { new Coordinate(-0.815656565656566, -0.439393939393939), new Coordinate(-0.353535353535354, -0.795454545454545), new Coordinate(-0.888888888888889,-0.929292929292929), new Coordinate(-1.151515151515152, -0.419191919191919), new Coordinate(-0.815656565656566,-0.439393939393939), })); // Act. IGeometry polygon = m_Reader.ReadShapeAtIndex(0, factory); Assert.IsNotNull(polygon); Assert.IsInstanceOf<IPolygon>(polygon); HelperMethods.AssertPolygonsEqual(polygon as IPolygon, expectedPolygon); }
public void Buffer() { var geom = new Polygon( new LinearRing(new Coordinate[] { new Coordinate(0, 0), new Coordinate(0, 10), new Coordinate(10, 10), new Coordinate(10, 0), new Coordinate(0, 0) })); Console.WriteLine(geom.AsText()); var geom2 = geom.Buffer(2d); Console.WriteLine(geom2); var geom3 = geom2.Buffer(-2); geom3.Normalize(); Console.WriteLine(geom3); }