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 void DrawLine(object sender, EventArgs e) { double xmin = App.Map.Extent.MinX; double xmax = App.Map.Extent.MaxX; double ymin = App.Map.Extent.MinY; double ymax = App.Map.Extent.MaxY; Feature f = new Feature(); FeatureSet fs = new FeatureSet(f.FeatureType); // TODO change to List<Coordinate>... Coordinate[] coord = new Coordinate[2]; coord[0] = new Coordinate(xmin, ymin); coord[1] = new Coordinate(xmin, ymax); LineString ls = new LineString(coord); f = new Feature(ls); fs.Features.Add(f); coord[0] = new Coordinate(xmin / 2, ymin); coord[1] = new Coordinate(xmin / 2, ymax); ls = new LineString(coord); f = new Feature(ls); fs.Features.Add(f); coord[0] = new Coordinate(xmin, ymax); coord[1] = new Coordinate(xmax, ymax); ls = new LineString(coord); f = new Feature(ls); fs.Features.Add(f); coord[0] = new Coordinate(xmin, ymax / 2); coord[1] = new Coordinate(xmax, ymax / 2); ls = new LineString(coord); f = new Feature(ls); fs.Features.Add(f); //App.Map.AddFeatureLayer fs.SaveAs("C:\\Temp\\LineTest.shp", true); }
private void MultilsFSCS(object sender, EventArgs e) { Random rnd = new Random(); Feature f = new Feature(); FeatureSet fs = new FeatureSet(f.FeatureType); for (int ii = 0; ii < 40; ii++) { Coordinate[] coord = new Coordinate[36]; for (int i = 0; i < 36; i++) { coord[i] = new Coordinate((rnd.NextDouble() * 360) - 180, (rnd.NextDouble() * 180) - 90); } LineString ls = new LineString(coord); f = new Feature(ls); fs.Features.Add(f); } fs.SaveAs("C:\\Temp\\test.shp", true); }
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"; } }
private void MpsCS(object sender, EventArgs e) { Feature f = new Feature(); FeatureSet fs = new FeatureSet(f.FeatureType); Coordinate[] c = new Coordinate[36]; Random rnd = new Random(); for (int i = 0; i < 36; i++) { c[i] = new Coordinate((rnd.NextDouble() + 360) - 180, (rnd.NextDouble() * 180) - 90); } MultiPoint Mps = new MultiPoint(c); f = new Feature(Mps); fs.Features.Add(f); fs.SaveAs("C:\\Temp\\mps.shp", true); }
private void MultypgFSCS(object sender, EventArgs e) { Random rnd = new Random(); Polygon[] pg = new Polygon[100]; Feature f = new Feature(); FeatureSet fs = new FeatureSet(f.FeatureType); for (int i = 0; i < 100; i++) { Coordinate center = new Coordinate((rnd.Next(50) * 360) - 180, (rnd.Next(60) * 180) - 90); Coordinate[] coord = new Coordinate[50]; for (int ii = 0; ii < 50; ii++) { coord[ii] = new Coordinate(center.X + Math.Cos((ii * 10) * Math.PI / 10), center.Y + (ii * 10) * Math.PI / 10); } coord[49] = new Coordinate(coord[0].X, coord[0].Y); pg[i] = new Polygon(coord); fs.Features.Add(pg[i]); } fs.SaveAs("C:\\Temp\\test.shp", true); }
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; }
public void UnionFeatureSetTest() { IFeatureSet fs = FeatureSet.Open(_shapefiles + @"Topology_Test.shp"); FeatureSet fsunion = new FeatureSet(); // This is needed or else the table won't have the columns for copying attributes. fsunion.CopyTableSchema(fs); // Create a list of all the original shapes so if we union A->B we don't also union B->A var freeFeatures = fs.Features.Select((t, i) => i).ToList(); while (freeFeatures.Count > 0) { var fOriginal = fs.Features[freeFeatures[0]]; // Whether this gets unioned or not, it has been handled and should not be re-done. // We also don't want to waste time unioning shapes to themselves. freeFeatures.RemoveAt(0); // This is the unioned result. Remember, we may just add the original feature if no // shapes present themselves for unioning. IFeature fResult = null; // This is the list of any shapes that get unioned with our shape. List<int> mergedList = new List<int>(); bool shapeChanged; do { shapeChanged = false; // reset this each time. foreach (int index in freeFeatures) { if (fResult == null) { if (fOriginal.Intersects(fs.Features[index])) { // If FieldJoinType is set to all, and large numbers of shapes are combined, // the attribute table will have a huge number of extra columns, since // every column will be replicated for each instance. fResult = fOriginal.Union(fs.Features[index], fsunion, FieldJoinType.LocalOnly); // if the shape changed for an index greater than 0, then the newly unioned // shape might now union with an earlier shape that we skipped before. shapeChanged = true; } } else { if (fResult.Intersects(fs.Features[index])) { // snowball unioned features. Keep adding features to the same unioned shape. fResult = fResult.Union(fs.Features[index], fsunion, FieldJoinType.LocalOnly); shapeChanged = true; } } if (shapeChanged) { // Don't modify the "freefeatures" list during a loop. Keep track until later. mergedList.Add(index); // Less double-checking happens if we break rather than finishing the loop // and then retest the whole loop because of a change early in the list. break; } } foreach (int index in mergedList) { // We don't want to add the same shape twice. freeFeatures.Remove(index); } } while (shapeChanged); // Add fResult, unless it is null, in which case add fOriginal. fsunion.Features.Add(fResult ?? fOriginal); // Union doesn't actually add to the output featureset. The featureset is only // provided to the union method to handle column manipulation if necessary. fsunion.Features.Add(fResult); } // fsunion is in-memory until this is called. Once this is called, the extension will // be parsed to determine that a shapefile is required. The attributes and features will // be moved to variables in an appropriate shapefile class internally, and // then that class will save the features to the disk. fsunion.SaveAs(_shapefiles + @"Union_Test.shp", true); try { // cleanup File.Delete(_shapefiles + @"Union_Test.shp"); File.Delete(_shapefiles + @"Union_Test.dbf"); File.Delete(_shapefiles + @"Union_Test.shx"); } catch (IOException) { } }
private void NewButton_Click(object sender, EventArgs e) { FeatureTypeDialog dlg = new FeatureTypeDialog(); if (dlg.ShowDialog() != DialogResult.OK) { return; } FeatureSet fs = new FeatureSet(dlg.FeatureType); if (_geoMap.Projection != null) { fs.Projection = _geoMap.Projection; } fs.CoordinateType = dlg.CoordinateType; fs.IndexMode = false; IMapFeatureLayer layer; if (!String.IsNullOrWhiteSpace(dlg.Filename)) { fs.SaveAs(dlg.Filename, true); layer = (IMapFeatureLayer)_geoMap.Layers.Add(dlg.Filename); } else { layer = _geoMap.Layers.Add(fs); } layer.EditMode = true; _geoMap.Layers.SelectedLayer = layer; layer.LegendText = !String.IsNullOrEmpty(layer.DataSet.Name) ? layer.DataSet.Name : _geoMap.Layers.UnusedName("New Layer"); }
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(); }
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 static string SaveShapefileString(string name, FeatureSet feaS) { DialogResult result = MessageBox.Show("Do you want to save " + name + " as shapefile?", "Save option", MessageBoxButtons.YesNo); if (result == DialogResult.Yes) { SaveFileDialog dialog = new SaveFileDialog(); dialog.Filter = "Shapefile files (*.shp)|*.shp"; dialog.InitialDirectory = @"C:\"; dialog.Title = "Save shapefile"; string strFileName = ""; if (dialog.ShowDialog() == DialogResult.OK) { strFileName = dialog.FileName; feaS.SaveAs(@strFileName, true); return @strFileName; } } return string.Empty; }
/// <summary> /// Show the dialog for exporting data from a feature layer. /// </summary> /// <param name="e"></param> public void ExportData(IFeatureLayer e) { using (var frmExport = new ExportFeature()) { frmExport.Filename = e.DataSet.Filename; if (ShowDialog(frmExport) != DialogResult.OK) return; // Create a FeatureSet of features that the client wants exported FeatureSet fs = null; switch (frmExport.FeaturesIndex) { case 0: fs = (FeatureSet) e.DataSet; break; case 1: fs = e.Selection.ToFeatureSet(); break; case 2: var features = e.DataSet.Select(e.MapFrame.ViewExtents); fs = new FeatureSet(features) {Projection = e.Projection}; break; } if (fs.Features.Count == 0) { fs.CopyTableSchema(e.DataSet); fs.FeatureType = e.DataSet.FeatureType; } fs.SaveAs(frmExport.Filename, true); if (MessageBox.Show(Owner, "Do you want to load the shapefile?", "The layer was exported.", MessageBoxButtons.YesNo) == DialogResult.Yes) { LoadFeatureSetAsLayer(e, fs, Path.GetFileNameWithoutExtension(frmExport.Filename)); } } }
private void SaveKrigingGridData() { StringBuilder sb = new StringBuilder(); var fs = new FeatureSet(FeatureType.Point); var dataTable = new DataTable(); dataTable.Columns.Add(new DataColumn("X", typeof(double))); dataTable.Columns.Add(new DataColumn("Y", typeof(double))); dataTable.Columns.Add(new DataColumn("Z", typeof(double))); // Loop through grid to get each cell's Z value for (int r = 0; r < GlnRowCount; r++) { for (int c = 0; c < GlnColumnCount; c++) { int cellNdx = (r * GlnColumnCount) + c; // cell index is Row:Cell ratio if (GlarnT[cellNdx] != 0) { double cellZ = GlardV[cellNdx]; var x = GldColumnCoord[c]; var y = GldRowCoord[r]; sb.AppendLine(string.Format("{0},{1},{2}", x, y, cellZ)); fs.Features.Add(new Coordinate(x, y, cellZ)); dataTable.Rows.Add(x,y,cellZ); } } } dataTable.TableName = _krigingField.Field; fs.DataTable = dataTable; fs.Name = "grid-" + _krigingField.ID; var tempGridPath = Path.Combine(_krigingField.Folder, "grid_points.txt"); if (File.Exists(tempGridPath)) File.Delete(tempGridPath); System.IO.File.WriteAllText(tempGridPath, sb.ToString()); fs.DataTable = dataTable; fs.SaveAs(Path.Combine(_krigingField.Folder, "grid_points.shp"), true); }
private void CreatesLineFeature(object sender, EventArgs e) { //http://dotspatial.codeplex.com/wikipage?title=LFCS&referringTitle=Desktop_SampleCode //Creates a random number generator Random rnd = new Random(); //creates a new coordiante array Coordinate[] c = new Coordinate[36]; //for loop that will generate 36 random numbers for (int i = 0; i < 36; i++) { c[i] = new Coordinate((rnd.NextDouble() * 360) - 180, (rnd.NextDouble() * 180) - 90); } //creates a linestring from the coordinate array LineString ls = new LineString(c); //creates a feature from the linestring Feature f = new Feature(ls); FeatureSet fs = new FeatureSet(f.FeatureType); fs.Features.Add(f); fs.SaveAs("C:\\Temp\\Lines.shp", true); }
private void MpgCS(object sender, EventArgs e) { Random rnd = new Random(); Polygon[] pg = new Polygon[50]; for (int i = 0; i < 50; i++) { Coordinate center = new Coordinate((rnd.NextDouble() * 360) - 180, (rnd.NextDouble() * 180) - 90); Coordinate[] coord = new Coordinate[36]; for (int ii = 0; ii < 36; ii++) { coord[ii] = new Coordinate(center.X + Math.Cos((ii * 10) * Math.PI / 10), center.Y + (ii * 10) * Math.PI / 10); } coord[35] = new Coordinate(coord[0].X, coord[0].Y); pg[i] = new Polygon(coord); } MultiPolygon mpg = new MultiPolygon(pg); FeatureSet fs = new FeatureSet(mpg.FeatureType); fs.Features.Add(mpg); fs.SaveAs("C:\\Temp\\mpg.shp", true); }
private void MultiptFSCS(object sender, EventArgs e) { Coordinate[] c = new Coordinate[50]; Random rnd = new Random(); Feature f = new Feature(); FeatureSet fs = new FeatureSet(f.FeatureType); for (int i = 0; i < 50; i++) { c[i] = new Coordinate((rnd.Next(0, 50) + 360) - 90, (rnd.NextDouble() * 360) - 180); fs.Features.Add(c[i]); } fs.SaveAs("C:\\Temp\\MultiptFSCS.shp", true); }
private void MlsCS(object sender, EventArgs e) { Random rnd = new Random(); MultiLineString Mls = new MultiLineString(); LineString[] ls = new LineString[40]; for (int ii = 0; ii < 40; ii++) { Coordinate[] coord = new Coordinate[36]; for (int i = 0; i < 36; i++) { coord[i] = new Coordinate((rnd.NextDouble() * 360) - 180, (rnd.NextDouble() * 180) - 90); } ls[ii] = new LineString(coord); } Mls = new MultiLineString(ls); FeatureSet fs = new FeatureSet(Mls.FeatureType); fs.Features.Add(Mls); fs.SaveAs("C:\\Temp\\Mls.shp", true); }
/// <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; }
private void HolesCS(object sender, EventArgs e) { //Defines a new coordinate array Coordinate[] coords = new Coordinate[20]; //Defines a new random number generator Random rnd = new Random(); //defines a randomly generated center for teh polygon Coordinate center = new Coordinate((rnd.NextDouble() * 360) - 180, (rnd.NextDouble() * 180) - 90); for (int i = 0; i < 19; i++) { //generates random coordinates and adds those coordinates to the array coords[i] = new Coordinate(center.X + Math.Cos((i * 10) * Math.PI / 10), center.Y + (i * 10) * Math.PI / 10); } //sets the last coordinate equal to the first, this 'closes' the polygon coords[19] = new Coordinate(coords[0].X, coords[0].Y); //defines a new LingRing from the coordinates LinearRing Ring = new LinearRing(coords); //Repeates the process, but generates a LinearRing with a smaller area, this will be the hole in the polgyon Coordinate[] coordshole = new Coordinate[20]; for (int i = 0; i < 20; i++) { coordshole[i] = new Coordinate(center.X + Math.Cos((i * 10) * Math.PI / 20), center.Y + (i * 10) * Math.PI / 20); } coordshole[19] = new Coordinate(coordshole[0].X, coordshole[0].Y); LinearRing Hole = new LinearRing(coordshole); //This steps addes the hole LinerRing to a ILinearRing Array //A Polgyon can contain multiple holes, thus a Array of Hole is required ILinearRing[] Holes = new ILinearRing[1]; Holes[0] = Hole; //This passes the Ring, the polygon shell, and the Holes Array, the holes Polygon pg = new Polygon(Ring, Holes); //Feature f = new Feature(); FeatureSet fs = new FeatureSet(pg.FeatureType); //f = new Feature(pg); fs.Features.Add(pg); fs.SaveAs("C:\\Temp\\hole.shp", 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; } }