public static IGeometry Project(IGeometry geometry, ProjectionInfo pStart, ProjectionInfo pEnd) { var featureSet = new FeatureSet(); featureSet.AddFeature(geometry.ToDotSpatial()); featureSet.Projection = pStart; featureSet.Reproject(pEnd); return GeometryConverter.ToGeoAPI( ((featureSet.Features[0].BasicGeometry as DotSpatial.Topology.IGeometry))); }
private void createBaseGrid(object sender, EventArgs e) { Coordinate[] coord = new Coordinate[4]; double startx = 11252200; double starty = 1418500; const int width = 100; FeatureSet fs = new FeatureSet(); IFeature feature; // Add Some Columns fs.DataTable.Columns.Add(new DataColumn("ID", typeof(int))); fs.DataTable.Columns.Add(new DataColumn("Text", typeof(string))); fs.DataTable.Columns.Add(new DataColumn("Value", typeof(double))); Random rnd = new Random(); for (int i = 0; i < 110; i++) { for (int j = 0; j < 110; j++) { coord[0] = new Coordinate((i * width) + startx, (j * width) + starty); coord[1] = new Coordinate((i * width) + startx, (j * width) + starty + width); coord[2] = new Coordinate((i * width) + startx + width, (j * width) + starty + width); coord[3] = new Coordinate((i * width) + startx + width, (j * width) + starty + 0); Polygon pg = new Polygon(coord); feature = fs.AddFeature(pg); feature.DataRow.BeginEdit(); feature.DataRow["ID"] = j + i * 50; feature.DataRow["Text"] = "Hello World" + (j + i * 50).ToString(); feature.DataRow["Value"] = (rnd.NextDouble() * 360) ; feature.DataRow.EndEdit(); } } // Add a layer to the map, and we know it is a point layer so cast it specifically. IMapPolygonLayer polygonLayer = App.Map.Layers.Add(fs) as IMapPolygonLayer; // Control what the points look like through a symbolizer (or pointLayer.Symbology for categories) if (polygonLayer != null) { polygonLayer.LegendText = "grid point"; //polygonLayer.Symbolizer = new PointSymbolizer(Color.Blue, DotSpatial. ); } }
public void GetAttributes_WithFieldNames() { var fs = new FeatureSet(FeatureType.Point); fs.DataTable.Columns.Add("Column1"); fs.DataTable.Columns.Add("Column2"); fs.AddFeature(new Point(0, 0)); var fl = new PointLayer(fs); var target = new IndexSelection(fl); var attributesTable = target.GetAttributes(0, 1, new[] {"Column1"}); Assert.AreEqual(1, attributesTable.Columns.Count); Assert.AreEqual("Column1", attributesTable.Columns[0].ColumnName); }
/// <summary> /// The Voronoi Graph calculation creates a delaunay tesselation where /// each point is effectively converted into triangles. /// </summary> /// <param name="points">The points to use for creating the tesselation.</param> /// <returns>The generated line featureset.</returns> public static IFeatureSet DelaunayLines(IFeatureSet points) { double[] vertices = points.Vertex; VoronoiGraph gp = Fortune.ComputeVoronoiGraph(vertices); FeatureSet result = new FeatureSet(); foreach (VoronoiEdge edge in gp.Edges) { Coordinate c1 = edge.RightData.ToCoordinate(); Coordinate c2 = edge.LeftData.ToCoordinate(); LineString ls = new LineString(new List<Coordinate> { c1, c2 }); Feature f = new Feature(ls); result.AddFeature(f); } return result; }
/// <summary> /// The Voronoi Graph calculation creates the lines that form a voronoi diagram. /// </summary> /// <param name="points">The points to use for creating the tesselation.</param> /// <returns>An IFeatureSet that is the resulting set of lines in the diagram.</returns> public static IFeatureSet VoronoiLines(IFeatureSet points) { double[] vertices = points.Vertex; VoronoiGraph gp = Fortune.ComputeVoronoiGraph(vertices); HandleBoundaries(gp, points.Extent.ToEnvelope()); FeatureSet result = new FeatureSet(); foreach (VoronoiEdge edge in gp.Edges) { Coordinate c1 = edge.VVertexA.ToCoordinate(); Coordinate c2 = edge.VVertexB.ToCoordinate(); LineString ls = new LineString(new List<Coordinate> { c1, c2 }); Feature f = new Feature(ls); result.AddFeature(f); } return result; }
/// <summary> /// Erase features from one feature set where they are intersected by another feature set. /// </summary> /// <param name="TargetFeatures">Features which will be erased in part or whole.</param> /// <param name="SourceFeatures">Features which represent areas to erase.</param> /// <param name="cancelProgressHandler">Optional parameter to report progress and cancel entire process if needed.</param> /// <returns>A point feature set with the randomly created features.</returns> public static FeatureSet EraseFeatures(IFeatureSet TargetFeatures, IFeatureSet SourceFeatures, ICancelProgressHandler cancelProgressHandler = null) { if (TargetFeatures == null || SourceFeatures == null) { return null; } //Erase features from one feature set where they are intersected by another feature set //Note: we use the ShapeIndices here rather than for each feature in featureset.features as a memory management technique. //The current version does not preserve any attribute info. //Dan Ames 2/27/2013 FeatureSet ResultFeatures = new FeatureSet(); //the resulting featureset IFeature TF, SF; //a single output feature ResultFeatures.CopyTableSchema(TargetFeatures); //set up the data table in the new feature set for (Int16 i = 0; i <= TargetFeatures.ShapeIndices.Count - 1; i++) { TF = TargetFeatures.GetFeature(i); //get the full undifferenced feature for (Int16 j = 0; j <= SourceFeatures.ShapeIndices.Count - 1; j++) { SF = SourceFeatures.GetFeature(j); if (SF.Envelope.Intersects(TF.Envelope)) { TF = TF.Difference(SF); //clip off any pieces of SF that overlap FR } if (TF == null) { //sometimes difference leaves nothing left of a feature break; } } if (TF != null) { ResultFeatures.AddFeature(TF).CopyAttributes(TargetFeatures.GetFeature(i)); //add the fully clipped feature to the results } if (cancelProgressHandler != null) { if (cancelProgressHandler.Cancel) { return null; } int progress = Convert.ToInt32(i * 100 / TargetFeatures.ShapeIndices.Count); cancelProgressHandler.Progress(String.Empty, progress, String.Empty); } } return ResultFeatures; }
private IFeatureSet CreatefilterFeatureSet() { IFeatureSet data1 = new FeatureSet(FeatureType.Point); data1.Projection = _originalData.Projection; data1.DataTable.Columns.Add(new System.Data.DataColumn(this.Field, typeof(double))); data1.DataTable.Columns.Add(new System.Data.DataColumn("Repeat", typeof(string))); List<int> listt = _originalData.SelectIndexByAttribute(Filterfields); foreach (int index in listt) { IFeature fea1 = _originalData.GetFeature(index); IFeature d=data1.AddFeature((IBasicGeometry)fea1); d.DataRow[this.Field] = fea1.DataRow[this.Field]; } return data1; }
internal FeatureSet CreateFeatureSet() { FeatureSet featureSet = new FeatureSet(FeatureType.Line); featureSet.Projection = KnownCoordinateSystems.Geographic.World.WGS1984; foreach (ReferentielMultiLineString mls in this.MultiLineStrings) { List<LineString> lineStrings = new List<LineString>(); foreach (ReferentielLineString ls in mls.LineStrings) { List<Coordinate> coordinates = new List<Coordinate>(); for (int i = 0; i < (ls.Segements.Count - 1); i++) { coordinates.Add(ls.Segements[i].CoordDeb); } coordinates.Add(ls.Segements.Last().CoordDeb); coordinates.Add(ls.Segements.Last().CoordFin); LineString fsLs = new LineString(coordinates); lineStrings.Add(fsLs); } MultiLineString fsMls = new MultiLineString(lineStrings); featureSet.AddFeature(fsMls); } return featureSet; }
/// <summary> /// Reads the complete feature set from the database /// </summary> /// <param name="connString">sqlite db connection string</param> /// <param name="featureSetInfo">information about the table</param> /// <param name="sql">the sql query</param> /// <returns>the resulting feature set</returns> public IFeatureSet ReadFeatureSet(string connString, GeometryColumnInfo featureSetInfo, string sql) { DataTable tab = new DataTable(); FeatureType fType = GetGeometryType(featureSetInfo.GeometryType); FeatureSet fs = new FeatureSet(fType); fs.IndexMode = false; //setting the initial index mode.. using (SQLiteCommand cmd = CreateCommand(connString, sql)) { cmd.Connection.Open(); RunInitialCommands(cmd.Connection); //DotSpatial.Topology.Utilities.WkbReader wkbr = new DotSpatial.Topology.Utilities.WkbReader(); SpatiaLiteWkbReader wkbr = new SpatiaLiteWkbReader(); SQLiteDataReader rdr = cmd.ExecuteReader(); string[] columnNames = PopulateTableSchema(fs, featureSetInfo.GeometryColumnName, rdr); int numColumns = fs.DataTable.Columns.Count; while (rdr.Read()) { byte[] wkb = rdr[featureSetInfo.GeometryColumnName] as byte[]; IGeometry geom = wkbr.Read(wkb); IFeature newFeature = fs.AddFeature(geom); //populate the attributes foreach (string colName in columnNames) { newFeature.DataRow[colName] = rdr[colName]; } } cmd.Connection.Close(); fs.Name = featureSetInfo.TableName; //HACK required for selection to work properly fs.IndexMode = true; //assign projection ProjectionInfo proj = ProjectionInfo.FromEpsgCode(featureSetInfo.SRID); fs.Projection = proj; return fs; } }
private void MapRasterToTriangulation() { Console.WriteLine("Mapping elevation raster pixels to triangulation...\n"); List<River> rivers = model.Rivers.Values.ToList(); List<WaterSurfacePolygon> waterSurfacePolygons = new List<WaterSurfacePolygon>(); //Create triangulation for each river for (int k = 0; k < rivers.Count; k++) { River river = rivers[k]; foreach (Reach reach in river.Reaches.Values) { reach.CreateGISFeatures(); reach.CreateTriangulationForWaterSurface(); foreach (WaterSurfacePolygon polygon in reach.WaterSurfaces) { waterSurfacePolygons.Add(polygon); } } } float[] mapping = new float[xSize * ySize]; rasterWaterSurfaceMapping = new int[xSize][]; rasterTriangleMapping = new int[xSize][]; for (int i = 0; i < xSize; i++) { rasterWaterSurfaceMapping[i] = new int[ySize]; rasterTriangleMapping[i] = new int[ySize]; for (int j = 0; j < ySize; j++) { rasterWaterSurfaceMapping[i][j] = -1; rasterTriangleMapping[i][j] = -1; mapping[j * xSize + i] = noData; } } int count = 0; int foundCount = 0; int stepSize = (int)Math.Floor(xSize * ySize * 0.01); List<List<Coordinate>> coordinates = new List<List<Coordinate>>(); //Parallel.For(0, waterSurfacePolygons.Count, k => for (int k = 0; k < waterSurfacePolygons.Count; k++) { WaterSurfacePolygon watersurfacePolygon = waterSurfacePolygons[k]; Interlocked.Increment(ref count); double progress = count * 100.0 / (waterSurfacePolygons.Count * 1.0); lock (Console.Out) { Console.SetCursorPosition(0, Console.CursorTop); Console.Write("Progress => " + progress.ToString("###") + " %"); } lock (watersurfacePolygon) { Point pltc = getCoordIndexes(watersurfacePolygon.MinX, watersurfacePolygon.MaxY); Point prbc = getCoordIndexes(watersurfacePolygon.MaxX, watersurfacePolygon.MinY); List<Coordinate> coordinate = new List<Coordinate>(); Point ptt1 = getCoords((int)pltc.X, (int)pltc.Y); Point ptt2 = getCoords((int)prbc.X, (int)prbc.Y); coordinate.Add(new Coordinate(ptt1.X, ptt1.Y)); coordinate.Add(new Coordinate(ptt1.X, ptt2.Y)); coordinate.Add(new Coordinate(ptt2.X, ptt1.Y)); coordinate.Add(new Coordinate(ptt2.X, ptt2.Y)); for (int i = (int)pltc.X; i < prbc.X; i++) { for (int j = (int)pltc.Y; j < prbc.Y; j++) { Point p2 = getCoords(i, j); lock (watersurfacePolygon) { if (watersurfacePolygon.Contains(p2.X, p2.Y)) { int m = watersurfacePolygon.FindTriangleThatContains(p2.X, p2.Y); if (m > -1) { rasterWaterSurfaceMapping[i][j] = k; mapping[j * xSize + i] = k; rasterTriangleMapping[i][j] = m; } } } } } coordinates.Add(coordinate); } } using(IFeatureSet set = new FeatureSet(FeatureType.MultiPoint)) { foreach(var p in coordinates) set.AddFeature(new MultiPoint(p)); set.SaveAs(localWorkspace + "\\" + name + "_point.shp", true); } //); OSGeo.GDAL.Driver driver = Gdal.GetDriverByName(rasterDriver); Dataset newRaster = driver.Create(localWorkspace + "\\" + name + "_mapping.tif", xSize, ySize, 1, dataType, new string[] { "TFW=YES", "COMPRESS=LZW" }); newRaster.GetRasterBand(1).SetNoDataValue(noData); newRaster.SetGeoTransform(geoTransformation); newRaster.SetProjection(projection); Band newRasterBand = newRaster.GetRasterBand(1); newRasterBand.WriteRaster(0, 0, xSize, ySize, mapping, xSize, ySize, 0, 0); double min, max, mean, stdev; newRasterBand.GetStatistics(0, 1, out min, out max, out mean, out stdev); newRasterBand.FlushCache(); newRaster.FlushCache(); newRaster.Dispose(); newRaster = null; driver.Dispose(); driver = null; using (IFeatureSet fs = new FeatureSet(DotSpatial.Topology.FeatureType.Polygon)) { fs.DataTable.Columns.AddRange(new DataColumn[] { new DataColumn("Identifier" , typeof(int)), }); int tcount = 0; for (int k = 0; k < waterSurfacePolygons.Count; k++) { WaterSurfacePolygon surface = waterSurfacePolygons[k]; foreach (TriangleNet.Data.Triangle pgon in surface.Triangles) { TriangleNet.Data.Triangle ts = pgon; List<Coordinate> vertices = new List<Coordinate>(); Point p0 = surface.Points[ts.P0]; Point p1 = surface.Points[ts.P1]; Point p2 = surface.Points[ts.P2]; Coordinate c1 = new Coordinate(p0.X, p0.Y, p0.Z); Coordinate c2 = new Coordinate(p1.X, p1.Y, p1.Z); Coordinate c3 = new Coordinate(p2.X, p2.Y, p2.Z); vertices.Add(c1); vertices.Add(c2); vertices.Add(c3); Polygon polygon = new Polygon(vertices); IFeature fset = fs.AddFeature(polygon); fset.DataRow.BeginEdit(); fset.DataRow["Identifier"] = k; fset.DataRow.EndEdit(); tcount++; } } fs.SaveAs(localWorkspace + "\\" + name + "_polygon.shp", true); fs.Close(); fs.Dispose(); } double temp = 100; Console.SetCursorPosition(0, Console.CursorTop); Console.WriteLine("Progress => " + temp.ToString("###") + " % \n"); temp = foundCount * 100.0 / (xSize * ySize * 1.0); Console.WriteLine(temp.ToString("###.0") + " % of pixels were found in triangulation \n"); Console.WriteLine("Finished mapping elevation raster pixels to triangulation !\n"); }
public PointClassification ClassifyPoint(double latitude, double longitude) { FeatureSet pFeatureSet = new FeatureSet(); pFeatureSet.Projection = KnownCoordinateSystems.Geographic.World.WGS1984; DotSpatial.Topology.Point pPoint = new DotSpatial.Topology.Point(longitude, latitude); FeatureSet pPointFeatureSet = new FeatureSet(DotSpatial.Topology.FeatureType.Point); pPointFeatureSet.Projection = KnownCoordinateSystems.Geographic.World.WGS1984; pPointFeatureSet.AddFeature(pPoint); Extent pAffectedExtent = null; var result = fsWorldCountries.Select(pPointFeatureSet.Extent, out pAffectedExtent); foreach (IFeature feature in result) { PointClassification classification = new PointClassification(); classification.CountryCode = feature.DataRow["ADM0_A3"].ToString(); if (classification.CountryCode.Length == 3) classification.CountryCode = ConvertISOCountryCode(classification.CountryCode); classification.CountrySubdivision = feature.DataRow["NAME"].ToString(); classification.CountryName = feature.DataRow["ADMIN"].ToString(); return classification; } return null; // System.Diagnostics.Debug.WriteLine(featureL); }
public void SaveProfilesToShapeFile(FileInfo shapefile) { //clear existing profiles ClearProfiles(); //read the rivers ReadRivers(); List<Reach> reachesFixed = new List<Reach>(); List<Reach> reaches = (from n in rivers.Values from p in n.Reaches.Values select p).ToList(); for (int i = 0; i < reaches.Count; i++) { Reach r1 = reaches[i]; for (int j = 0; j < reaches.Count; j++) { if (j != i) { Reach r2 = reaches[j]; Point p1 = r1.CenterLine[r1.CenterLine.Count - 1]; Point p2 = r2.CenterLine[0]; if (Math.Abs((p1 - p2).Length()) < 200) { XSection x = r2.XSections.Values.First<XSection>(); r1.XSections.Add(x.StationName, x); r1.CreateGISFeatures(); reachesFixed.Add(r1); break; } } } } //Create Shapefile using .dospatial library using (IFeatureSet fsp = new FeatureSet(FeatureType.Polygon)) { using (IFeatureSet trip = new FeatureSet(FeatureType.Polygon)) { using (IFeatureSet fsxs = new FeatureSet(FeatureType.Line)) { using (IFeatureSet fspo = new FeatureSet(FeatureType.Point)) { //add attribute fields to attribute table trip.DataTable.Columns.AddRange(new DataColumn[] { new DataColumn("RiverName" , typeof(string)), new DataColumn("ReachName" , typeof(string)), }); //add attribute fields to attribute table fsp.DataTable.Columns.AddRange(new DataColumn[] { new DataColumn("RiverName" , typeof(string)), new DataColumn("ReachName" , typeof(string)), }); fsxs.DataTable.Columns.AddRange(new DataColumn[] { new DataColumn("RiverName" , typeof(string)), new DataColumn("ReachName" , typeof(string)), new DataColumn("StationName" , typeof(string)), }); List<River> tempRivers = rivers.Values.ToList(); //select river for (int j = 0; j < rivers.Count; j++) { River river = tempRivers[j]; foreach (Reach reach in river.Reaches.Values) { foreach (WaterSurfacePolygon wsurface in reach.WaterSurfaces) { List<Polygon> polygons = wsurface.GetPolygons(); foreach (Polygon polygon in polygons) { IFeature tri = trip.AddFeature(polygon); tri.DataRow.BeginEdit(); tri.DataRow["RiverName"] = river.Name; tri.DataRow["ReachName"] = reach.Name; tri.DataRow.EndEdit(); } } IFeature fp = fsp.AddFeature(reach.BoundingPolygon); fp.DataRow.BeginEdit(); fp.DataRow["RiverName"] = river.Name; fp.DataRow["ReachName"] = reach.Name; fp.DataRow.EndEdit(); List<XSection> xsections = reach.XSections.Values.ToList(); for (int ip = 0; ip < reach.XSectionsCutLines.Count; ip++) { IFeature fxs = fsxs.AddFeature(reach.XSectionsCutLines[ip]); fxs.DataRow.BeginEdit(); fxs.DataRow["RiverName"] = river.Name; fxs.DataRow["ReachName"] = reach.Name; fxs.DataRow["StationName"] = xsections[ip].StationName; fxs.DataRow.EndEdit(); } IFeature fpo = fspo.AddFeature(new MultiPoint(from n in reach.CenterLine select new Coordinate(n.X, n.Y))); } } fspo.SaveAs(shapefile.FullName.Replace(shapefile.Extension, "_point" + shapefile.Extension), true); } fsxs.SaveAs(shapefile.FullName.Replace(shapefile.Extension, "_xsection" + shapefile.Extension), true); } trip.SaveAs(shapefile.FullName.Replace(shapefile.Extension, "_triangulation" + shapefile.Extension), true); } fsp.SaveAs(shapefile.FullName.Replace(shapefile.Extension, "_boundary" + shapefile.Extension), true); } for (int i = 0; i < reachesFixed.Count; i++) { Reach r = reachesFixed[i]; r.XSections.Remove(r.XSections.Values.Last<XSection>().StationName); } controller.Project_Save(); }
internal void CreateLayers() { Envelope env = new Envelope(); if (this.Model.SigLayer != null) { if (this.Model.SigLayer.SigCodeLayer.Code == "Geocodage") { FeatureSet featureSetPoint = new FeatureSet(FeatureType.Point); featureSetPoint.Projection = DotSpatial.Projections.KnownCoordinateSystems.Geographic.World.WGS1984; PointSymbolizer featureSetPointSymbolizer = new PointSymbolizer(System.Drawing.Color.Red, DotSpatial.Symbology.PointShape.Ellipse, 10); FeatureSet featureSetLine = new FeatureSet(FeatureType.Line); featureSetLine.Projection = DotSpatial.Projections.KnownCoordinateSystems.Geographic.World.WGS1984; IDataService dataService = ServiceLocator.Current.GetInstance<IDataService>(); ICartoService cartoService = ServiceLocator.Current.GetInstance<ICartoService>(); EntityTableInfo tableInfo = dataService.GetEntityTableInfo(this.Model.SigLayer.EntityName); IQueryable queryable = dataService.GetDbSet(tableInfo.EntityType).AsQueryable(); EntityColumnInfo columnGeom = (from c in tableInfo.ColumnInfos where c.IsLocalisationReferenceGeom select c).FirstOrDefault(); EntityColumnInfo columnRef = (from c in tableInfo.ColumnInfos where c.IsLocalisationReferenceId select c).FirstOrDefault(); EntityColumnInfo columnDeb = (from c in tableInfo.ColumnInfos where c.IsLocalisationDeb select c).FirstOrDefault(); EntityColumnInfo columnFin = (from c in tableInfo.ColumnInfos where c.IsLocalisationFin select c).FirstOrDefault(); foreach (Object item in queryable) { Geometry geometry = null; if (columnGeom != null) { Object dataGeom = columnGeom.Property.GetValue(item); if (dataGeom != null) {geometry = WktHelper.CreateGeometryFromWkt(dataGeom.ToString());} } if (geometry == null && columnRef != null && columnDeb != null) { Object objRef = columnRef.Property.GetValue(item); Object objDeb = columnDeb.Property.GetValue(item); if (columnFin == null) { if (objRef != null && objRef is Int64 && objDeb != null && objDeb is Int64) { geometry = cartoService.Geocode((Int64)objRef, (Int64)objDeb ); } } else { Object objFin = columnFin.Property.GetValue(item); if (objRef != null && objRef is Int64 && objDeb != null && objDeb is Int64) { if (objFin != null && objFin is Int64) { geometry = cartoService.Geocode((Int64)objRef, (Int64)objDeb, (Int64)objFin); } else { geometry = cartoService.Geocode((Int64)objRef, (Int64)objDeb); } } } } if (geometry != null) { if (geometry is Point) { featureSetPoint.AddFeature(geometry); env.ExpandToInclude((geometry as Point).Coordinate); } else if (geometry is LineString) { featureSetLine.AddFeature(geometry); env.ExpandToInclude(geometry.Envelope); } else if (geometry is MultiLineString ) { featureSetLine.AddFeature(geometry); env.ExpandToInclude(geometry.Envelope); } } } this.Layers.Add(new MapLineLayer(featureSetLine)); this.Layers.Add(new MapPointLayer(featureSetPoint)); } } this.Envelope = env; }
/// <summary> /// Creates a specified number of random point features inside a single polygon feature. /// </summary> /// <param name="ConstrainingFeature">Random points will be generated inside this polygon feature.</param> /// <param name="NumberOfPoints">The number of points to be randomly generated.</param> /// <returns>A point feature set with the randomly created features.</returns> public static FeatureSet RandomPoints(Feature ConstrainingFeature, int NumberOfPoints) { //This function generates random points within the boundaries of one polygon feature FeatureSet fsOut = new FeatureSet(); fsOut.FeatureType = FeatureType.Point; Coordinate c = new Coordinate(); Random r = new Random(); int i = 0; while (i < NumberOfPoints) { c = new Coordinate(); //make a random point somewhere in the rectangular extents of the feature double rndx = r.Next(0, 100000) / 100000.0; double rndy = r.Next(0, 100000) / 100000.0; c.X = rndx * (ConstrainingFeature.Envelope.Right() - ConstrainingFeature.Envelope.Left()) + ConstrainingFeature.Envelope.Left(); c.Y = rndy * (ConstrainingFeature.Envelope.Top() - ConstrainingFeature.Envelope.Bottom()) + ConstrainingFeature.Envelope.Bottom(); //check if the point falls within the polygon featureset if (ConstrainingFeature.Intersects(c)) { fsOut.AddFeature(new Feature(c)); i++; } } return fsOut; }
private bool AddKrigingLayer(List<Polygon> polygonsList) { var field = this._krigingFields[krigingProcess]; string datasetName = field.ID; // field.ProductResult = Math.Round(CalculateProductSum(datasetName), 2); var zList = new List<double>(); FeatureSet fs = new FeatureSet(FeatureType.Polygon); fs.Projection = _config.TargetPolygonLayer.Projection; fs.DataTable.Columns.Add(new DataColumn("ID", typeof(int))); fs.DataTable.Columns.Add(new DataColumn("Z", typeof(double))); fs.DataTable.Columns.Add(new DataColumn("Product", typeof(double))); for (int i = 0; i < polygonsList.Count; i++) { var feature = fs.AddFeature(polygonsList[i]); feature.DataRow["ID"] = i; feature.DataRow["Z"] = polygonsList[i].Coordinate.Z; feature.DataRow["Product"] = field.ProductResult; zList.Add(polygonsList[i].Coordinate.Z); } fs.Name = field.Field; var shapeFile = Path.Combine(field.Folder, "kriging.shp"); fs.SaveAs(shapeFile, true); var input = fs as IFeatureSet; var input2 = _config.TargetPolygonLayer.DataSet as IFeatureSet; input.FillAttributes(); input2.FillAttributes(); FeatureSet output = new FeatureSet(input.FeatureType); output.Projection = input2.Projection; IFeatureSet tempOutput = input.Intersection(input2, FieldJoinType.LocalOnly, null); foreach (DataColumn inputColumn in tempOutput.DataTable.Columns) { output.DataTable.Columns.Add(new DataColumn(inputColumn.ColumnName, inputColumn.DataType)); } foreach (var fe in tempOutput.Features) { output.Features.Add(fe); } output.Name = datasetName; output.Filename = datasetName + ".shp"; field.OutputShapeFile = datasetName + ".shp"; field.OutputZ = string.Join(",", zList); var layer = PluginExtension.MyAppManager.Map.Layers.Add(output); layer.LegendText = field.Field; layer.Symbology.ClearCategories(); var pieChartData = new List<TempPIEChartData>(); _colorsList = _legendRepository.GetFieldLegend(field.Field); if (_colorsList.Where(c => c.Value == null).Count() > 0) { CreateRandomColorCategories(zList, ref pieChartData).ForEach(c => layer.Symbology.AddCategory(c)); } else { _colorsList.Reverse(); CreatePredefinedColorCategories(zList, ref pieChartData).ForEach(c => layer.Symbology.AddCategory(c)); } field.PieChartData = pieChartData; layer.ContextMenuItems.Add(new DotSpatial.Symbology.SymbologyMenuItem("View Input Data", new EventHandler((s, e) => ViewInputDataClick(s, e, field.ID)))); layer.ContextMenuItems.Add( new DotSpatial.Symbology.SymbologyMenuItem("Load Grid File", new EventHandler((s, ev) => LoadGridFileClick(s, ev, field)))); layer.ContextMenuItems.Add(new DotSpatial.Symbology.SymbologyMenuItem("Calculate Product", new EventHandler((s, e) => CalculateProductClick(s, e, field)))); layer.ContextMenuItems.Add( new DotSpatial.Symbology.SymbologyMenuItem("Load Product File", new EventHandler((s, ev) => LoadProductFileClick(s, ev, field)))); new DotSpatial.Symbology.Forms.FeatureCategoryControl(layer).ApplyChanges(); ColorsList = new List<LegendPattern>(); foreach (var item in layer.Symbology.GetCategories()) { var pattern = new Repository.Utils.LegendPattern(); pattern.Color = item.GetColor(); pattern.Value = item.LegendText != null ? item.LegendText : zList.Max().ToString(); ColorsList.Add(pattern); } field.Image = getMapImage(field); return true; }
private void CreateAttributes(object sender, EventArgs e) { //http://dotspatial.codeplex.com/wikipage?title=CreateAttributes&referringTitle=Desktop_SampleCode // define the feature type for this file FeatureSet fs = new FeatureSet(FeatureType.Polygon); // Add Some Columns fs.DataTable.Columns.Add(new DataColumn("ID", typeof(int))); fs.DataTable.Columns.Add(new DataColumn("Text", typeof(string))); // create a geometry (square polygon) List<Coordinate> vertices = new List<Coordinate>(); vertices.Add(new Coordinate(11219035, 1542354)); vertices.Add(new Coordinate(11219035, 1542354 + 100)); vertices.Add(new Coordinate(11219035 + 100, 1542354 + 100)); vertices.Add(new Coordinate(11219035 + 100, 1542354 + 0)); Polygon geom = new Polygon(vertices); fs.AddFeature(geom); // add 16.01.18 // add the geometry to the featureset. IFeature feature = fs.AddFeature(geom); // now the resulting features knows what columns it has // add values for the columns feature.DataRow.BeginEdit(); feature.DataRow["ID"] = 1; feature.DataRow["Text"] = "Hello World"; feature.DataRow.EndEdit(); vertices.Clear(); vertices.Add(new Coordinate(11219035 + 100, 1542354)); vertices.Add(new Coordinate(11219035 + 100, 1542354 + 100)); vertices.Add(new Coordinate(11219035 + 200, 1542354 + 100)); vertices.Add(new Coordinate(11219035 + 200, 1542354 + 0)); geom = new Polygon(vertices); feature = fs.AddFeature(geom); // now the resulting features knows what columns it has // add values for the columns feature.DataRow.BeginEdit(); feature.DataRow["ID"] = 2; feature.DataRow["Text"] = "Hello World"; feature.DataRow.EndEdit(); // save the feature set fs.SaveAs("d:\\test.shp", true); }
private IFeatureSet ConvertToPoints(IFeatureSet originalData) { string field = Field; IFeatureSet fea = new FeatureSet(FeatureType.Point); fea.Projection = originalData.Projection; DataColumn col = originalData.GetColumn(field); DataColumn coln = new DataColumn(col.ColumnName, col.DataType); fea.DataTable.Columns.Add(coln); foreach (Feature feature in originalData.Features) { foreach (Coordinate c in feature.BasicGeometry.Coordinates) { IFeature nfeature = fea.AddFeature(new DotSpatial.Topology.Point(c.X, c.Y)); nfeature.DataRow[field] = feature.DataRow[field]; } } return fea; }
private void CalculateProductForm_Shown(object sender, EventArgs e) { if (_field != null) { label1.Text = "Reading Polygon.."; var polygonFile = Path.Combine(_field.Folder, "input_polygon.shp"); var polygonFeatures = FeatureSet.Open(polygonFile).Features; label1.Text = "Reading Grid.."; var gridFile = Path.Combine(_field.Folder, "grid_points.shp"); var featuresDataset = FeatureSet.Open(gridFile); progressBar1.Maximum = polygonFeatures.Count; progressBar1.Value = 0; var newPolygonLayer = new FeatureSet(FeatureType.Polygon); var tbl = new DataTable(); tbl.Columns.Add("Z"); tbl.Columns.Add("AreaM2"); tbl.Columns.Add("Hectare"); int pCount = 1; foreach (Feature poly in polygonFeatures) { label1.Text = "Caculating Product Value for plot:" + pCount; var extent = poly.Envelope.ToExtent(); var fe = featuresDataset.CopySubset(featuresDataset.SelectIndices(extent)); double zTotalCount = 0; for (int i = 0; i < fe.Features.Count; i++) { if (poly.Contains(fe.Features[i])) { var z = double.Parse(Convert.ToString(fe.DataTable.Rows[i]["Z"])); zTotalCount += z; } } tbl.Rows.Add(Math.Round(zTotalCount / 25, 2), Math.Round(poly.Area(), 2), Math.Round(poly.Area() / 10000, 0)); newPolygonLayer.AddFeature(poly); progressBar1.Value = progressBar1.Value + 1; pCount++; } newPolygonLayer.DataTable = tbl; newPolygonLayer.Projection = _map.Projection; newPolygonLayer.Reproject(_map.Projection); var newPolyFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TempFiles", "Temp-Product" + DateTime.Now.Ticks + ".shp"); newPolygonLayer.SaveAs(newPolyFile, true); var layer = _map.Layers.Add(newPolyFile); layer.ContextMenuItems.Add( new DotSpatial.Symbology.SymbologyMenuItem("Save Product File", new EventHandler((s, ev) => SaveProductFileClick(s, ev, (IMapPolygonLayer)layer)))); label1.Text = "Completed"; } }
void p() { FeatureSet fs = new FeatureSet(FeatureType.Polygon); fs.DataTable.Columns.Add(new DataColumn("ID", typeof(int))); fs.DataTable.Columns.Add(new DataColumn("Text", typeof(string))); List<Coordinate> vertices = new List<Coordinate>(); // vertices.Add(new Coordinate(0, 0)); // vertices.Add(new Coordinate(0, 100)); // vertices.Add(new Coordinate(100, 100)); // vertices.Add(new Coordinate(100, 0)); vertices.Add(new Coordinate(242846.81386332, 7528087.29373347)); vertices.Add(new Coordinate(242854.625931002, 7528087.29373347)); vertices.Add(new Coordinate(242854.625931002, 7528094.1633412)); vertices.Add(new Coordinate(242846.81386332, 7528094.1633412)); Polygon geom = new Polygon(vertices); IFeature feature = fs.AddFeature(geom); appManager1.Map.Layers.Add(fs); }
void p2() { var sel = appManager1.Map.GetPointLayers()[0].Selection.ToFeatureList(); FeatureSet fs = new FeatureSet(FeatureType.Polygon); List<Coordinate> vertices = new List<Coordinate>(); vertices.Add(new Coordinate(sel[0].Coordinates[0])); vertices.Add(new Coordinate(sel[1].Coordinates[0])); vertices.Add(new Coordinate(sel[3].Coordinates[0])); vertices.Add(new Coordinate(sel[2].Coordinates[0])); Polygon geom = new Polygon(vertices); IFeature feature = fs.AddFeature(geom); appManager1.Map.Layers.Add(fs); MessageBox.Show(geom.Area.ToString()); }
private static IFeatureSet UnionAll(IFeatureSet fs) { FeatureSet fsunion = new FeatureSet(); fsunion.CopyTableSchema(fs); fsunion.Projection = fs.Projection; IFeature f = fs.Features[0]; for (int i = 1; i < fs.Features.Count; i++) { f = f.Union(fs.Features[i], fsunion, FieldJoinType.LocalOnly); } fsunion.AddFeature(f); return fsunion; }
/// <summary> /// Call EPAWebServiceHelper Method to get delineated watershed, and also return the start point. /// </summary> /// <param name="param">Arguments for backgroundworkers</param> /// <returns>Return a list of featureset including both point and polygon</returns> private IList<IFeatureSet> GetShapes(Coordinate watershedOutletLocation) { var projCor = watershedOutletLocation; // declare a new EPAWebServiceHelper Client var trigger = new EPAWebServiceHelper(projCor); // get Start Point Information object[] startpt = trigger.GetStartPoint(); // check if start point successful if (startpt == null) { //progress.closeForm(); return null; } // get delineated watershed object[] WshedObj = trigger.GetWsheds(startpt); if (WshedObj == null) { return null; } IFeatureSet fsWshed = new FeatureSet(); // delete small marginal polygons if any try { var fsCatchment = (IFeatureSet)WshedObj[0]; int count = fsCatchment.Features.Count; if (count > 1) { // the last one is the main watershed for (int i = 0; i < count - 1; i++) { fsCatchment.Features.RemoveAt(0); } // Object process could be dangerous to lose Projection info WshedObj[0] = fsCatchment; } fsWshed = SetAttribute(WshedObj); } catch (Exception ex) { // As a bare minimum we should probably log these errors logger.Fatal(ex.Message); System.Diagnostics.Trace.WriteLine(ex.Message); } // get Upstream flowlines var StreamObj = trigger.GetLines(startpt); var fsStream = SetAttribute(StreamObj); // create the start point shapefile var point = new Feature(projCor); IFeatureSet fsPoint = new FeatureSet(point.FeatureType); // PK: added this following one line fsPoint.Projection = WGS84; fsPoint.AddFeature(point); IList<IFeatureSet> EPAShapes = new List<IFeatureSet>(); EPAShapes.Add(fsWshed); EPAShapes.Add(fsStream); EPAShapes.Add(fsPoint); logger.Info("All shapes were generated."); return EPAShapes; }
/// <summary> /// Add the features from SourceFeatures to the TargetFeatures feature set. /// </summary> /// <param name="TargetFeatures">Feature set to which features will be added.</param> /// <param name="SourceFeatures">Source of features to add to the target feature set. </param> /// <returns>A point feature set with the randomly created features.</returns> public static FeatureSet AppendFeatures(FeatureSet TargetFeatures, FeatureSet SourceFeatures) { //Add the features from SourceFeatures to the TargetFeatures feature set //Note: we use the ShapeIndices here rather than for each feature in featureset.features as a memory management technique. //Dan Ames 2/27/2013 IFeature SF; for (Int16 j = 0; j <= SourceFeatures.ShapeIndices.Count - 1; j++) { SF = SourceFeatures.GetFeature(j); TargetFeatures.AddFeature(SF).CopyAttributes(SourceFeatures.GetFeature(j)); //by default this will try to copy attributes over that have the same name. } return TargetFeatures; }
/// <summary> /// Get delineated watershed polygon from EPA WebServices /// </summary> /// <param name="uri">Query string</param> /// <returns>Returns an IFeatureSet including the delineated polygon</returns> private object[] GetDelineation(string uri) { //Declare a WebClient instance to get the Watershed Delineation response string WebClient delineate = new WebClient(); try { string response = delineate.DownloadString(uri); int start = response.IndexOf("("); int end = response.LastIndexOf(")"); response = response.Substring(start + 1, end - 1 - start); //Declare Json Elements JObject mainObj = new JObject(); JToken outputObj = new JObject(); JToken shapeObj = new JObject(); JToken statusObj = new JObject(); mainObj = JObject.Parse(response); outputObj = mainObj["output"]; //check for error message in outputObj if (outputObj.Type == Newtonsoft.Json.Linq.JTokenType.Null) { statusObj = mainObj["status"]; string statusMessage = statusObj["status_message"].ToString(); throw new ArgumentException(statusMessage); } shapeObj = outputObj["shape"]; string stype = shapeObj["type"].ToString(); string area = outputObj["total_areasqkm"].ToString(); JArray coordArray = shapeObj["coordinates"] as JArray; //For coordinate information string lat; string lon; //Setup projection information _defaultProjection = KnownCoordinateSystems.Projected.World.WebMercator; //Initialize feature parameters Feature polyf = new Feature(); Feature multipolyf = new Feature(); IFeatureSet polyfs = new FeatureSet(FeatureType.Polygon); //For the case GeoJSON returns a MultiPolygon if (stype.Trim().ToLower() == "multipolygon") { foreach (JArray Polycoord in coordArray) //The third level branket { Polygon[] polys = new Polygon[Polycoord.Count]; if (Polycoord != null) { for (int i = 0; i < Polycoord.Count; i++)//The second level branket { JArray multiRingcoord = (JArray)Polycoord[i]; IList<Coordinate> multicoords = new List<Coordinate>(); if (multiRingcoord != null) { foreach (JArray latlongcoord in multiRingcoord) //The first level branket { Coordinate coord = new Coordinate(); lon = latlongcoord[0].ToString(); lat = latlongcoord[1].ToString(); coord.X = Convert.ToDouble(lon); coord.Y = Convert.ToDouble(lat); double[] xy = new double[2]; xy[0] = coord.X; xy[1] = coord.Y; double[] z = new double[1]; coord.X = xy[0]; coord.Y = xy[1]; multicoords.Add(coord); } polys[i] = new Polygon(multicoords); } } //Save polygon[] into a multipolygon if (polys.Length > 1) { IMultiPolygon multipolys = new MultiPolygon(polys); multipolyf = new Feature(multipolys); } else { // special case: A multipolygon with one part multipolyf = new Feature(polys[0]); } //Save features into a featureset if (polyfs.Features.Count == 0) { polyfs = new FeatureSet(multipolyf.FeatureType); polyfs.Projection = WGS84; polyfs.AddFeature(multipolyf); } else { polyfs.Projection = WGS84; polyfs.AddFeature(multipolyf); } } } } //For the case GeoJSON returns a Polygon if (stype.Trim().ToLower() == "polygon") { foreach (JArray Ringcoord in coordArray) //The second level branket { IList<Coordinate> coords = new List<Coordinate>(); if (Ringcoord != null) { foreach (JArray latlongcoord in Ringcoord) //The first level branket { Coordinate coord = new Coordinate(); lon = latlongcoord[0].ToString(); lat = latlongcoord[1].ToString(); coord.X = Convert.ToDouble(lon); coord.Y = Convert.ToDouble(lat); double[] xy = new double[2]; xy[0] = coord.X; xy[1] = coord.Y; double[] z = new double[1]; coord.X = xy[0]; coord.Y = xy[1]; coords.Add(coord); } polyfs.Projection = WGS84; // _defaultProjection; polyf = new Feature(FeatureType.Polygon, coords); } polyfs = new FeatureSet(polyf.FeatureType); if (polyfs.Features.Count == 0) { polyfs = new FeatureSet(polyf.FeatureType); polyfs.Projection = WGS84; polyfs.AddFeature(polyf); } else { polyfs.Projection = WGS84; polyfs.AddFeature(polyf); } } } object[] watersheds = new object[2]; watersheds[0] = polyfs; watersheds[1] = area; return watersheds; } catch (NullReferenceException ex) { var resp = new HttpResponseMessage(HttpStatusCode.NotFound) { Content = new StringContent(ex.Message), ReasonPhrase = "Watershed not found. Please try a different point." }; throw new HttpResponseException(resp); } catch (Exception ex) { var resp = new HttpResponseMessage(HttpStatusCode.NotFound) { Content = new StringContent(ex.Message), ReasonPhrase = "Error searching for watershed." }; throw new HttpResponseException(resp); } }
/// <summary> /// Get Upstream flowslines from EPA WebServices /// </summary> /// <param name="uri">Query string</param> /// <returns>Returns an IFeatureSet including the </returns> private object[] GetStreamline(string uri) { //Declare a WebClient instance to get the Watershed Delineation response string WebClient streamline = new WebClient(); try { string response = streamline.DownloadString(uri); int start = response.IndexOf("("); int end = response.IndexOf(")"); response = response.Substring(start + 1, end - 1 - start); //Declare Json Elements JObject mainObj = new JObject(); JToken outputObj; JArray lineObj = new JArray(); JToken shapeObj = new JObject(); mainObj = JObject.Parse(response); outputObj = mainObj["output"]; lineObj = outputObj["flowlines_traversed"] as JArray; List<string> comid = new List<string>(); List<string> reachcode = new List<string>(); List<string> totdist = new List<string>(); //Setup projection information _defaultProjection = KnownCoordinateSystems.Projected.World.WebMercator; //Initialize feature parameters Feature linef = new Feature(); IFeatureSet linefs = new FeatureSet(FeatureType.Line); //for (int i = 0; i < lineObj.Count; i++) foreach (JObject flowObj in lineObj) { shapeObj = flowObj["shape"] as JObject; string id = flowObj["comid"].ToString(); string code = flowObj["reachcode"].ToString(); string dist = flowObj["totaldist"].ToString(); string stype = shapeObj["type"].ToString(); JArray coordArray = shapeObj["coordinates"] as JArray; //For coordinate information string lat; string lon; //For the case GeoJSON returns a MultiLineString if (stype.Trim().ToLower() == "multilinestring") { if (coordArray != null) { LineString[] lines = new LineString[coordArray.Count]; for (int j = 0; j < coordArray.Count; j++)//The second level branket { JArray linecoord = (JArray)coordArray[j]; IList<Coordinate> multicoords = new List<Coordinate>(); if (linecoord != null) { foreach (JArray latlongcoord in linecoord) //The first level branket { Coordinate coord = new Coordinate(); lon = latlongcoord[0].ToString(); lat = latlongcoord[1].ToString(); coord.X = Convert.ToDouble(lon); coord.Y = Convert.ToDouble(lat); multicoords.Add(coord); } lines[j] = new LineString(multicoords); } } //Save lines[] into a multiline IMultiLineString multilines = new MultiLineString(lines); linef = new Feature(multilines); } } //For the case GeoJSON returns a LineString if (stype.Trim().ToLower() == "linestring") { IList<Coordinate> coords = new List<Coordinate>(); foreach (JArray latlongcoord in coordArray) //The second level branket { Coordinate coord = new Coordinate(); lon = latlongcoord[0].ToString(); lat = latlongcoord[1].ToString(); coord.X = Convert.ToDouble(lon, CultureInfo.InvariantCulture); coord.Y = Convert.ToDouble(lat, CultureInfo.InvariantCulture); coords.Add(coord); } linef = new Feature(FeatureType.Line, coords); } linefs.Projection = WGS84; //Save features into a featureset if (linefs.Features.Count == 0) { linefs.Projection = WGS84; linefs = new FeatureSet(linef.FeatureType); linefs.AddFeature(linef); } else { linefs.AddFeature(linef); } //Save streamlines' information comid.Add(id); reachcode.Add(code); totdist.Add(dist); } //TODO: PK- use a StreamLine object with 4 properties instead - create this class in the Models folder object[] streamlines = new object[4]; streamlines[0] = linefs as object; streamlines[1] = comid as object; streamlines[2] = reachcode as object; streamlines[3] = totdist as object; return streamlines; } catch (Exception ex) { var resp = new HttpResponseMessage(HttpStatusCode.NotFound) { Content = new StringContent(ex.Message), ReasonPhrase = "Error finding upstream flow lines with EPA web service." }; throw new HttpResponseException(resp); } }
/// <summary> /// Executes the ClipPolygonWithLine Operation tool programaticaly. /// Ping deleted static for external testing 01/2010 /// </summary> /// <param name="input1">The input Polygon FeatureSet.</param> /// <param name="input2">The input Polyline FeatureSet.</param> /// <param name="output">The output Polygon FeatureSet.</param> /// <param name="cancelProgressHandler">The progress handler.</param> /// <returns></returns> public bool Execute( IFeatureSet input1, IFeatureSet input2, IFeatureSet output, ICancelProgressHandler cancelProgressHandler) { // Validates the input and output data if (input1 == null || input2 == null || output == null) { return false; } if (cancelProgressHandler.Cancel) { return false; } IFeature polygon = input1.Features[0]; IFeature line = input2.Features[0]; IFeatureSet resultFs = new FeatureSet(FeatureType.Polygon); int previous = 0; if (DoClipPolygonWithLine(ref polygon, ref line, ref output) == false) { throw new SystemException(TextStrings.Exceptioninclipin); } int intFeature = output.Features.Count; for (int i = 0; i < intFeature; i++) { Polygon poly = new Polygon(output.Features[i].Coordinates); resultFs.AddFeature(poly); int current = Convert.ToInt32(Math.Round(i * 100D / intFeature)); // only update when increment in percentage if (current > previous) { cancelProgressHandler.Progress(string.Empty, current, current + TextStrings.progresscompleted); } previous = current; } cancelProgressHandler.Progress(string.Empty, 100, 100 + TextStrings.progresscompleted); resultFs.SaveAs(output.Filename, true); return true; }
/// <summary> /// Overload of BuildJoinedBasins that takes an outlets shape path used for Inlets resolution. If no outlets/inlets path given, it will treat all points as outlets /// </summary> // 2/11/09 rewritten by Chris George to dramatically improve speed: // (a) use utils.ClipPolygon instead of SpatialOperations.MergeShapes // (b) create a binary tree modeling the drainage pattern of the subbasins // (b) merge "upstream-first" using the drainage tree so that each merge combines abutting polygons public static bool BuildJoinedBasins(string subBasinShapePath, string outletsShapePath, string joinBasinShapeResultPath, IProgressHandler callback) { var shapeIdxList = new ArrayList(); BinTree drainage; IFeatureSet outlets = null; if (outletsShapePath != string.Empty) { outlets = FeatureSet.Open(outletsShapePath); } var shed = FeatureSet.Open(subBasinShapePath); var dsNodeFieldNum = -1; var dsShedFieldNum = -1; var us1FieldNum = -1; var us2FieldNum = -1; for (var i = 0; i < shed.DataTable.Columns.Count; i++) { switch (shed.DataTable.Columns[i].ColumnName.ToUpper()) { case "DSNODEID": dsNodeFieldNum = i; break; case "DSWSID": dsShedFieldNum = i; break; case "US1WSID": us1FieldNum = i; break; case "US2WSID": us2FieldNum = i; break; } } //DataManagement.DeleteShapefile(joinBasinShapeResultPath); var newShed = new FeatureSet(); newShed.FeatureType = FeatureType.Polygon; newShed.Filename = joinBasinShapeResultPath; var idfieldnum = AddField(newShed, "MWShapeID", typeof(int)); var linkfieldnum = AddField(newShed, "LinkIDs", typeof(string)); var outletfieldnum = AddField(newShed, "OutletID", typeof(int)); var dswsfieldnum = AddField(newShed, "DSWSID", typeof(int)); var uswsfieldnum1 = AddField(newShed, "USWSID1", typeof(int)); var uswsfieldnum2 = AddField(newShed, "USWSID2", typeof(int)); var reservoirfieldnum = AddField(newShed, "Reservoir", typeof(int)); var oldperc = 0; for (var sindx = 0; sindx < shed.NumRows(); sindx++) { if (shed.NumRows() > 1) { var newperc = Convert.ToInt32((Convert.ToDouble(sindx) / Convert.ToDouble(shed.NumRows())) * 100); if (newperc > oldperc) { if (callback != null) { callback.Progress("Status", newperc, "Merging Watersheds to Outlets/Inlets"); } oldperc = newperc; } } DSNode dsNodeType = DSNode.Outlet; var dsNodeVal = int.Parse(shed.get_CellValue(dsNodeFieldNum, sindx).ToString()); if (dsNodeVal > -1) { // an outlet, inlet, reservoir or point source if (outletsShapePath == string.Empty) { // assume this is an outlet drainage = getDrainageFromSubbasin(shed, outlets, false, true, sindx, dsNodeFieldNum, us1FieldNum, us2FieldNum); } else { dsNodeType = getDSNodeType(outlets, dsNodeVal); if ((dsNodeType == DSNode.Outlet) || (dsNodeType == DSNode.Reservoir)) { if (isUpstreamOfInlet(shed, outlets, sindx)) { drainage = null; } else { drainage = getDrainageFromSubbasin(shed, outlets, true, true, sindx, dsNodeFieldNum, us1FieldNum, us2FieldNum); } } else { // ignore inlets and point sources drainage = null; } } shapeIdxList.Clear(); if (drainage != null) { char[] sep = { ',' }; var idxs = drainage.ToString().Split(sep); for (var i = 0; i < idxs.Length; i++) { shapeIdxList.Add(idxs[i]); } } if (shapeIdxList.Count != 0) { IFeature mergeShape; string strLinks; if (shapeIdxList.Count == 1) { mergeShape = shed.get_Shape(int.Parse(shapeIdxList[0].ToString())); strLinks = shed.get_CellValue(0, int.Parse(shapeIdxList[0].ToString())).ToString(); } else { strLinks = shed.get_CellValue(0, int.Parse(shapeIdxList[0].ToString())).ToString(); for (int i = 1; i <= shapeIdxList.Count - 1; i++) { strLinks = strLinks + ", " + shed.get_CellValue(0, int.Parse(shapeIdxList[i].ToString())); } DateTime time = DateTime.Now; mergeShape = mergeBasinsByDrainage(shed, drainage); var elapsed = DateTime.Now.Subtract(time); Trace.WriteLine("Made merged watershed of " + shapeIdxList.Count + " subbasins in " + elapsed.TotalSeconds.ToString("F1") + " seconds"); } // Check merged shape for single part and clockwise if (mergeShape.NumGeometries > 1) { Trace.WriteLine("Merged polygon has " + mergeShape.NumGeometries + " parts"); } else { var area = SignedArea(mergeShape); if (area < 0) { Trace.WriteLine("Needed to reverse merged polygon"); mergeShape = ReverseShape(mergeShape); } } var currshpidx = newShed.NumRows(); newShed.AddFeature(mergeShape); newShed.EditCellValue(idfieldnum, currshpidx, currshpidx); newShed.EditCellValue(linkfieldnum, currshpidx, strLinks); newShed.EditCellValue(outletfieldnum, currshpidx, dsNodeVal); if (int.Parse(shed.get_CellValue(dsShedFieldNum, sindx).ToString()) != -1) { newShed.EditCellValue(dswsfieldnum, currshpidx, shed.get_CellValue(dsShedFieldNum, sindx)); } else { newShed.EditCellValue(dswsfieldnum, currshpidx, -1); } newShed.EditCellValue(uswsfieldnum1, currshpidx, -1); newShed.EditCellValue(uswsfieldnum2, currshpidx, -1); if (dsNodeType == DSNode.Reservoir) { newShed.EditCellValue(reservoirfieldnum, currshpidx, 1); } else { newShed.EditCellValue(reservoirfieldnum, currshpidx, 0); } } } } buildMergeDownstreamUpStream(newShed, idfieldnum, linkfieldnum, dswsfieldnum, uswsfieldnum1, uswsfieldnum2); newShed.Projection = shed.Projection; shed.Close(); newShed.Save(); newShed.Close(); if (outletsShapePath != string.Empty) { outlets.Close(); } if (callback != null) { callback.Progress(string.Empty, 0, string.Empty); } return true; }
public static void exportSDFtoShapeFile(string inputsdfFile, string outputShapefile) { using (TextReader reader = new StreamReader(inputsdfFile)) { string line; while ((line = reader.ReadLine()) != null) { if (line.Trim() == "BEGIN BOUNDS:") { FeatureSet fs = new FeatureSet(FeatureType.Polygon); fs.DataTable.Columns.AddRange(new DataColumn[] { new DataColumn("ProfileName" , typeof(string)), new DataColumn("ProfileDate" , typeof(string)), }); fs.AddFid(); while ((line = reader.ReadLine()) != null) { if (line.Trim() == "END BOUNDS:") { fs.SaveAs(outputShapefile, true); break; } else if (line.Trim() == "PROFILE LIMITS:") { string profileName = ""; bool isDate = false; DateTime dateTime = DateTime.Now; IList<Coordinate> coordinates = new List<Coordinate>(); while ((line = reader.ReadLine()) != null) { string[] cols; double x, y, z; if (line.Trim() == "END:") { Polygon p = new Polygon(coordinates); IFeature f = fs.AddFeature(p); f.DataRow.BeginEdit(); f.DataRow["ProfileName"] = profileName; if (isDate) { f.DataRow["ProfileDate"] = dateTime.ToString("yyyy/MM/dd HH:mm:ss"); } f.DataRow.EndEdit(); break; } else if (line.Trim() == "POLYGON:") { } else if ((cols = line.Trim().Split(new string[] { ":", "," }, StringSplitOptions.RemoveEmptyEntries)).Length > 1) { if (cols[0].Trim() == "PROFILE ID") { profileName = cols[1].Trim(); cols = profileName.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); int day, year; if (cols.Length == 2 && int.TryParse(cols[0].Substring(0, 2), out day) && int.TryParse(cols[0].Substring(5, 4), out year) && months.ContainsKey(cols[0].Substring(2, 3))) { isDate = true; dateTime = new DateTime(year, months[cols[0].Substring(2, 3)], day); dateTime = dateTime.AddHours(double.Parse(cols[1].Substring(0, 2))); dateTime = dateTime.AddMinutes(double.Parse(cols[1].Substring(2, 2))); } } else if ( double.TryParse(cols[0], out x) && double.TryParse(cols[1], out y) && double.TryParse(cols[2], out z) ) { coordinates.Add(new Coordinate(x, y, z) { Z = z }); } } } } } } } } }
private void ExcelDatasetToLayer() { try { if (_excelDataset != null) { var excelTable = _excelDataset.Tables[0]; if (excelTable.Columns.Contains("lat") & excelTable.Columns.Contains("long")) { FeatureSet fs = new FeatureSet(FeatureType.Point); fs.Projection = KnownCoordinateSystems.Geographic.World.WGS1984; // Set columns of attribute table fs.DataTable = excelTable.Clone(); foreach (DataRow excelRow in excelTable.Rows) { string lat = (excelRow["lat"].ToString()); string lon = (excelRow["long"].ToString()); if (!string.IsNullOrEmpty(lat) && !string.IsNullOrEmpty(lon)) { // Add the point to the FeatureSet Coordinate coord = new Coordinate(Double.Parse(lon), Double.Parse(lat)); DotSpatial.Topology.Point point = new DotSpatial.Topology.Point(coord); IFeature feature = fs.AddFeature(point); // Bring over all of the data as attribute data. for (int i = 0; i <= excelTable.Columns.Count - 1; i++) { feature.DataRow[i] = excelRow[i]; } } } foreach (var item in fieldsList.Where(c => c.isChecked == false)) { fs.DataTable.Columns.Remove(item.Field); } var shapePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TempFiles", Path.GetFileNameWithoutExtension(_filePath) + ".shp"); if (!Directory.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TempFiles"))) Directory.CreateDirectory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TempFiles")); fs.SaveAs(shapePath, true); PluginExtension.MyAppManager.Map.Layers.Add(shapePath); } else { MessageBox.Show("The excel file must have lat and long columns."); } } else { MessageBox.Show("Please provide file."); } } catch (Exception ex) { throw ex; } }