public void savaPolylineShape() { if (lineF == null) { MessageBox.Show("There is no line shape file."); } else { string filename = saveFile(); lineF.SaveAs(filename, true); MessageBox.Show("The line shapefile has been saved."); } map.Cursor = Cursors.Arrow; }
public void savePolygonShape() { if (polygonF == null) { MessageBox.Show("There is no polygon shape file."); } else { string filename = saveFile(); polygonF.SaveAs(filename, true); MessageBox.Show("The polygon shapefile has been saved."); } map.Cursor = Cursors.Arrow; }
public void SavePointToShapefileWithMandZ(CoordinateType c) { var fileName = FileTools.GetTempFileName(".shp"); try { var fs = new FeatureSet(FeatureType.Point) { Projection = KnownCoordinateSystems.Geographic.World.WGS1984, CoordinateType = c }; fs.AddFeature(new Point(new Coordinate(1, 2, 7, 4))); Assert.DoesNotThrow(() => fs.SaveAs(fileName, true)); var loaded = FeatureSet.Open(fileName); if (c == CoordinateType.Regular) //regular coordinates don't have m values { Assert.AreEqual(double.NaN, loaded.Features[0].Geometry.Coordinates[0].M); Assert.AreEqual(double.NaN, loaded.Features[0].Geometry.EnvelopeInternal.Minimum.M); Assert.AreEqual(double.NaN, loaded.Features[0].Geometry.EnvelopeInternal.Maximum.M); } else // m or z coordinates have m values { Assert.AreEqual(4, loaded.Features[0].Geometry.Coordinates[0].M); Assert.AreEqual(4, loaded.Features[0].Geometry.EnvelopeInternal.Minimum.M); Assert.AreEqual(4, loaded.Features[0].Geometry.EnvelopeInternal.Maximum.M); } if (c == CoordinateType.Z) // z coordinates have z values { Assert.AreEqual(7, loaded.Features[0].Geometry.Coordinates[0].Z); Assert.AreEqual(7, loaded.Features[0].Geometry.EnvelopeInternal.Minimum.Z); Assert.AreEqual(7, loaded.Features[0].Geometry.EnvelopeInternal.Maximum.Z); } else // regular and m coordinates don't have z values { Assert.AreEqual(double.NaN, loaded.Features[0].Geometry.Coordinates[0].Z); Assert.AreEqual(double.NaN, loaded.Features[0].Geometry.EnvelopeInternal.Minimum.Z); Assert.AreEqual(double.NaN, loaded.Features[0].Geometry.EnvelopeInternal.Maximum.Z); } } finally { FileTools.DeleteShapeFile(fileName); } }
/// <summary> /// Show the dialog for exporting data from a feature layer. /// </summary> /// <param name="layer">Layer whose data gets exported.</param> public void ExportData(IFeatureLayer layer) { using var frmExport = new ExportFeature(); frmExport.Filename = layer.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)layer.DataSet; break; case 1: fs = layer.Selection.ToFeatureSet(); break; case 2: var features = layer.DataSet.Select(layer.MapFrame.ViewExtents); fs = new FeatureSet(features) { Projection = layer.Projection }; break; } if (fs == null) { return; } if (fs.Features.Count == 0) { fs.CopyTableSchema(layer.DataSet); fs.FeatureType = layer.DataSet.FeatureType; } fs.SaveAs(frmExport.Filename, true); if (MessageBox.Show(Owner, SymbologyFormsMessageStrings.FeatureLayerActions_LoadFeatures, SymbologyFormsMessageStrings.FeatureLayerActions_FeaturesExported, MessageBoxButtons.YesNo) == DialogResult.Yes) { LoadFeatureSetAsLayer(layer, fs, Path.GetFileNameWithoutExtension(frmExport.Filename)); } }
private void btnStartEditNode_Click(object sender, RoutedEventArgs e) { //显示选中要素的结点列表,并提示用户选择需编辑结点 //if (btnStartEditNode.Content.ToString() == "Select editing node") //{ MessageBox.Show("Please select the nodes that you want to edit,left button to select,right button to move"); //注销事件 m_CurrentFeaLyr.SelectionChanged -= M_CurrentFeaLyr_SelectionChanged; MainWindow.m_AddFeaType = Enum.FeaType.MovePoint; MainWindow.m_DotMap.FunctionMode = FunctionMode.Select; MainWindow.m_DotMap.Cursor = System.Windows.Forms.Cursors.Cross; if (m_CurrentFeaLyr.Selection.Count > 0) { m_CurrentFeaLyr.ZoomToSelectedFeatures(); } //复制结点图层 AllPointLayer = MainWindow.m_DotMap.Layers.Where(t => t.LegendText == "AllNodes").FirstOrDefault() as FeatureLayer; if (AllPointLayer == null) { FeatureSet PointSet = new FeatureSet(FeatureType.Point); for (int i = 0; i < Points.Count; i++) { IFeature pFea = PointSet.AddFeature(Points[i]); PointList[i].Feature = pFea; } PointSet.Name = "AllNodes"; PointSet.Projection = MainWindow.m_DotMap.Projection; AllPointLayer = MainWindow.m_DotMap.Layers.Add(PointSet) as FeatureLayer; PointSymbolizer symbol = new PointSymbolizer(System.Drawing.Color.Red, DotSpatial.Symbology.PointShape.Ellipse, 5); AllPointLayer.Symbolizer = symbol; PointSet.SaveAs(TempPath, true); } btnStartEditNode.IsEnabled = false; //} //else//保存 //{ // (m_CurrentFeaLyr as FeatureLayer).FeatureSet.Save(); // MessageBox.Show("Save successfully!"); // btnStartEditNode.Content = "Select editing node"; // 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); // this.Close(); //} }
private void MultiFeatureSetExport() { foreach (var dataset in _ftProject.Datasets) { if (!ExportTag(dataset.TagId)) { continue; } FeatureSet fs = CreateFeatureSet(); foreach (var gpsPoint in dataset.GPSData.GpsSeries) { GpsDataPointToFeatureRow(dataset.TagId, fs, gpsPoint); } fs.SaveAs(CreateMultiexportFilename(dataset.TagId), true); } }
/// <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)); } } }
public void Execute() { RcIndex rc = Point_to_Raster(pointLayer, Accumulation); RasterPixel_2 rp1 = new RasterPixel_2(rc.Row, rc.Column, Accumulation.Value[rc.Row, rc.Column], Surface.Value[rc.Row, rc.Column]); Stack <RasterPixel_2> RpArr1 = new Stack <RasterPixel_2>(); Stack <RasterPixel_2> RpArr2 = new Stack <RasterPixel_2>(); RpArr1.Push(rp1); Label.Value[rp1.Row, rp1.Column] = rp1.Value2; do { RasterPixel_2 rp2 = RpArr1.Pop(); RpArr2.Push(rp2); is_Satisfy(rp2.Row, rp2.Column, rp2.Row, rp2.Column - 1, Radius, Accumulation, Surface, Label, RpArr1); //Left is_Satisfy(rp2.Row, rp2.Column, rp2.Row, rp2.Column + 1, Radius, Accumulation, Surface, Label, RpArr1); //Right is_Satisfy(rp2.Row, rp2.Column, rp2.Row - 1, rp2.Column, Radius, Accumulation, Surface, Label, RpArr1); //Top is_Satisfy(rp2.Row, rp2.Column, rp2.Row + 1, rp2.Column, Radius, Accumulation, Surface, Label, RpArr1); //Bottom is_Satisfy(rp2.Row, rp2.Column, rp2.Row - 1, rp2.Column - 1, Radius, Accumulation, Surface, Label, RpArr1); //TopLeft is_Satisfy(rp2.Row, rp2.Column, rp2.Row - 1, rp2.Column + 1, Radius, Accumulation, Surface, Label, RpArr1); //TopRight is_Satisfy(rp2.Row, rp2.Column, rp2.Row + 1, rp2.Column - 1, Radius, Accumulation, Surface, Label, RpArr1); //BottomLeft is_Satisfy(rp2.Row, rp2.Column, rp2.Row + 1, rp2.Column + 1, Radius, Accumulation, Surface, Label, RpArr1); //BottomRight } while (RpArr1.Count > 0); RasterPixel_2 rp3 = Search_pour_pixel(RpArr2); Coordinate ResultCoor = Rc_to_Coor(rp3.Row, rp3.Column, Accumulation); FeatureSet pointF = new FeatureSet(FeatureType.Point); pointF.Projection = Accumulation.Projection; DataColumn Column1 = new DataColumn("ID"); pointF.DataTable.Columns.Add(Column1); DataColumn Column2 = new DataColumn("Accumulation"); pointF.DataTable.Columns.Add(Column2); DataColumn Column3 = new DataColumn("Elevation"); pointF.DataTable.Columns.Add(Column3); Point point = new Point(ResultCoor); IFeature currentFeature = pointF.AddFeature(point); currentFeature.DataRow["ID"] = 0; currentFeature.DataRow["Accumulation"] = rp3.Value1; currentFeature.DataRow["Elevation"] = rp3.Value2; pointF.SaveAs(savePath, false); MainMap.Layers.Add(pointF); }
public void Build(string filename) { FeatureSet fs = new FeatureSet(FeatureType.Polygon); fs.Name = "Grid"; fs.Projection = this.Projection; fs.DataTable.Columns.Add(new DataColumn("HRU_ID", typeof(int))); fs.DataTable.Columns.Add(new DataColumn("CELL_ID", typeof(int))); fs.DataTable.Columns.Add(new DataColumn("ROW", typeof(int))); fs.DataTable.Columns.Add(new DataColumn("COLUMN", typeof(int))); fs.DataTable.Columns.Add(new DataColumn(ParaValueField, typeof(double))); if (Origin == null) { Origin = new Coordinate(0, 0); } int active = 1; for (int r = 0; r < RowCount; r++) { for (int c = 0; c < ColumnCount; c++) { if (IBound[0, r, c] != 0) { // create a geometry (square polygon) var vertices = LocateNodes(c, r); ILinearRing ring = new LinearRing(vertices); Polygon geom = new Polygon(ring); // 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["HRU_ID"] = active; feature.DataRow["CELL_ID"] = Topology.GetID(r, c); feature.DataRow["ROW"] = r + 1; feature.DataRow["COLUMN"] = c + 1; feature.DataRow[ParaValueField] = 0; feature.DataRow.EndEdit(); active++; } } } fs.SaveAs(filename, true); fs.Close(); }
public void BuildShape() { FeatureSet shp = new FeatureSet(FeatureType.Polygon); var columns = shp.DataTable.Columns; columns.Add(new DataColumn("SSBID", typeof(long))); columns.Add(new DataColumn("RSIZE", typeof(long))); columns.Add(new DataColumn("ROW", typeof(long))); columns.Add(new DataColumn("COL", typeof(long))); columns.Add(new DataColumn("XCOOR", typeof(long))); columns.Add(new DataColumn("YCOOR", typeof(long))); var gridSizeMeters = 500000; var ssbGrid = new SsbGrid(gridSizeMeters); var xMin = - -1000000.00; var yMin = 5500000.00; var xMax = 1120000; var yMax = 7940000; double x = xMin, y = yMin; for (int row = 0; y < yMax; row++) { for (int col = 0; x < xMax; col++) { var lowerLeftCoordinate = new Coordinate(x, y); Coordinate[] coords = ssbGrid.GetPolygon(lowerLeftCoordinate); var feature = new Feature(FeatureType.Polygon, coords); shp.Features.Add(feature); feature.DataRow.BeginEdit(); feature.DataRow["SSBID"] = ssbGrid.GetCellId(lowerLeftCoordinate); feature.DataRow["RSIZE"] = gridSizeMeters; feature.DataRow["ROW"] = row; feature.DataRow["COL"] = col; feature.DataRow["XCOOR"] = lowerLeftCoordinate.X; feature.DataRow["YCOOR"] = lowerLeftCoordinate.Y; feature.DataRow.EndEdit(); x += gridSizeMeters; } y += gridSizeMeters; x = xMin; } shp.SaveAs(@"c:\temp\test.shp", true); }
//Code for defining a geographic coordinate system for a feature set public static void AddingACoordinateSystemToFeatureSet(FeatureSet fs) { FeatureSet CopyFS = new FeatureSet(); ProjectionInfo dest = default(ProjectionInfo); //Copies the selected layer to a new feature set //Prevents the original file from being edited CopyFS.CopyFeatures(fs, true); dest = KnownCoordinateSystems.Geographic.World.WGS1984; //Adds the geographic coordinate system to the feature set CopyFS.Projection = dest; //Saves the feature set CopyFS.SaveAs("C:\\Temp\\US_Cities_GCS_WGS1984.shp", true); Console.WriteLine("The feature was successfully been projected."); }
private void mapMain_MouseDoubleClick(object sender, MouseEventArgs e) { if (polygonmouseClick == true) { //get polygonGeomety instance of existing polygonFeature IFeature polygonFeature = polygonF.GetFeature(0); //add first coordinate Coordinate coord = polygonFeature.Coordinates[0]; polygonFeature.Coordinates.Add(coord); polygonF.InitializeVertices(); mapMain.ResetBuffer(); //add first coordinate to the list xCoordinates.Add(coord.X); yCoordinates.Add(coord.Y); //we add new feature //Creat a list to contain the polygon coordinates List <Coordinate> polygonArray = new List <Coordinate>(); for (int i = 0; i < xCoordinates.Count; i++) { polygonArray.Add(new Coordinate(xCoordinates[i], yCoordinates[i])); } //Create an instance for LinearRing class. //We pass the polygon List to the constructor of this class LinearRing polygonGeometry = new LinearRing(polygonArray); DotSpatial.Topology.Polygon polygon = new Polygon(polygonGeometry); //add polygonGeomety instance to polygonFeature IFeature polygonFeatureNew = polygonFNew.AddFeature(polygon); FeatureType ft = polygonFNew.FeatureType; polygonFNew.SaveAs("polygonF.shp", true); polygonmouseClick = false; mapMain.Cursor = Cursors.Arrow; } }
/// <summary> /// 由点list新建shp文件 /// </summary> /// <param name="point_list"></param> /// <param name="file_path"></param> public static void outputMyPoint(List <MyPoint> point_list, string file_path) { Feature f = new Feature(); FeatureSet fs = new FeatureSet(f.FeatureType); //fs.DataTable.Columns.Add("azimuth", typeof(double)); //fs.DataTable.Columns.Add("speed", typeof(double)); DotSpatial.Topology.Coordinate[] coordinate = new DotSpatial.Topology.Coordinate[point_list.Count]; for (int i = 0; i < point_list.Count; i++) { coordinate[i] = new DotSpatial.Topology.Coordinate(point_list[i].x, point_list[i].y); fs.Features.Add(coordinate[i]); //fs.DataTable.Rows[i]["azimuth"] = point_list[i].azimuth; //fs.DataTable.Rows[i]["speed"] = point_list[i].speed; } fs.SaveAs(file_path, true); //fs.Projection.SaveAs(file_path.Substring(0, file_path.Length - 4) + ".prj"); }
private void SingleFeatureSetExport() { FeatureSet fs = CreateFeatureSet(); foreach (var dataset in _ftProject.Datasets) { if (!ExportTag(dataset.TagId)) { continue; } foreach (var gpsPoint in dataset.GPSData.GpsSeries) { GpsDataPointToFeatureRow(dataset.TagId, fs, gpsPoint); } } fs.SaveAs(ExportPath, true); }
static void Main(string[] args) { FeatureSet featureSet = new FeatureSet(DotSpatial.Topology.FeatureType.Polygon); //設定Shapefile幾何要素 featureSet.Projection = ProjectionInfo.FromEpsgCode(4326); //設定坐標投影系統 featureSet.DataTable.Columns.Add(new System.Data.DataColumn("序號", typeof(int))); //設定屬性表 featureSet.DataTable.Columns.Add(new System.Data.DataColumn("名稱", typeof(string))); //設定屬性表 //寫入Feature string wkt = "POLYGON((120.501320843584 23.643673036339,120.501491708153 23.6444211261058,120.501498926896 23.6444147291785,120.501524821969 23.6443917685627,120.501717159325 23.6442212029981,120.501677888785 23.644054697763,120.501579964979 23.6436249183856,120.501320843584 23.643673036339))"; Feature feature = WktToFeature(wkt); IFeature iFeature = featureSet.AddFeature(feature); iFeature.DataRow["序號"] = 1; iFeature.DataRow["名稱"] = "多邊形測試"; featureSet.SaveAs("newFile.shp", true); }
private void btnOK_Click(object sender, RoutedEventArgs e) { if (this.txtSavePath.Text == "") { MessageBox.Show("Please select a save path"); return; } if (this.cboX.Text == "" || this.cboY.Text == "") { MessageBox.Show("Please select x y field"); return; } string xField = this.cboX.Text; string yField = this.cboY.Text; IFeatureSet pFeaSet = new FeatureSet(FeatureType.Point); //使用当前视图的空间参考 pFeaSet.Projection = MainWindow.m_DotMap.Projection; pFeaSet.DataTable = m_DataTable.Clone(); pFeaSet.Name = this.txtName.Text; for (int i = 0; i < m_DataTable.Rows.Count; i++) { string xValue = m_DataTable.Rows[i][xField].ToString(); string yValue = m_DataTable.Rows[i][yField].ToString(); double x, y; //尝试转换成double类型 if (double.TryParse(xValue, out x) && double.TryParse(yValue, out y)) { Coordinate coor = new Coordinate(x, y); IPoint point = new NetTopologySuite.Geometries.Point(coor); IFeature feature = pFeaSet.AddFeature(point); feature.DataRow = m_DataTable.Rows[i]; } else { MessageBox.Show("第" + (i + 1) + "行中X或Y坐标不是数值"); return; } } pFeaSet.SaveAs(this.txtSavePath.Text, true); ResultFeaSet = pFeaSet; this.DialogResult = true; }
public static void CreatingALineInFeatureSet() { 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); }
/// <summary> /// 由线list新建shp /// </summary> /// <param name="point_list"></param> /// <param name="file_path"></param> public static void outputMyLine(List <MyLine> line_list, string file_path) { DotSpatial.Data.Feature f = new Feature(new Shape(FeatureType.Line)); DotSpatial.Data.FeatureSet fs = new FeatureSet(f.FeatureType); //fs.DataTable.Columns.Add("width", typeof(double)); //fs.DataTable.Columns.Add("distance", typeof(double)); for (int i = 0; i < line_list.Count; i++) { List <Coordinate> coor_list = new List <Coordinate>(); foreach (MyPoint point in line_list[i].points_mid) { coor_list.Add(new DotSpatial.Topology.Coordinate(point.x, point.y)); } fs.Features.Add(coor_list, FeatureType.Line); //fs.DataTable.Rows[i]["width"] = line_list[i].width; //fs.DataTable.Rows[i]["distance"] = line_list[i].distance_to_ori; } fs.SaveAs(file_path, true); //fs.Projection.SaveAs(file_path.Substring(0, file_path.Length - 4) + ".prj"); }
public void UtmProjectionSamePointsAfterSaveLoadShapeFile() { var fs = new FeatureSet(FeatureType.Point) { Projection = KnownCoordinateSystems.Projected.UtmWgs1984.WGS1984UTMZone33N // set any UTM projection }; const double OriginalX = 13.408056; const double OriginalY = 52.518611; var wgs = KnownCoordinateSystems.Geographic.World.WGS1984; var c = new[] { OriginalX, OriginalY }; var z = new[] { 0.0 }; Reproject.ReprojectPoints(c, z, wgs, fs.Projection, 0, 1); var pt = new Point(c[0], c[1]); fs.AddFeature(pt); var tmpFile = FileTools.GetTempFileName(".shp"); fs.SaveAs(tmpFile, true); try { // Now try to open saved shapefile // Points must have same location in WGS1984 var openFs = FeatureSet.Open(tmpFile); var fs0 = (Point)openFs.Features[0].Geometry; var c1 = new[] { fs0.X, fs0.Y }; Reproject.ReprojectPoints(c1, z, openFs.Projection, wgs, 0, 1); // reproject back to wgs1984 Assert.IsTrue(Math.Abs(OriginalX - c1[0]) < 1e-8); Assert.IsTrue(Math.Abs(OriginalY - c1[1]) < 1e-8); } finally { FileTools.DeleteShapeFile(tmpFile); } }
private static void GetODPoints() { OpenFileDialog ofd = new OpenFileDialog(); ofd.Filter = "文本文件|*.txt;*.csv"; ofd.RestoreDirectory = true; if (ofd.ShowDialog() == DialogResult.OK) { Console.WriteLine("Application thread ID: {0}", Thread.CurrentThread.ManagedThreadId); var gpsData = GPSIO.GPSTrajectoryReader.ReadAll(ofd.FileName); //保存成shapefile IFeatureSet oFS = new FeatureSet(FeatureType.Point); oFS.Name = "OriginalPoints"; oFS.DataTable.Columns.Add("UserID", typeof(int)); oFS.DataTable.Columns.Add("Time", typeof(int)); //D IFeatureSet dFS = new FeatureSet(FeatureType.Point); dFS.Name = "DesPoints"; dFS.DataTable.Columns.Add("UserID", typeof(int)); dFS.DataTable.Columns.Add("Time", typeof(int)); for (int i = 0; i < gpsData.GPSTrajectoriesData.Count; i++) { //起点shapefile var fe = oFS.AddFeature(new Point(gpsData.GPSTrajectoriesData[i].Start)); fe.DataRow.BeginEdit(); fe.DataRow["UserID"] = gpsData.GPSTrajectoriesData[i].UserID; fe.DataRow["Time"] = gpsData.GPSTrajectoriesData[i].Start.TimeStamp; fe.DataRow.EndEdit(); //终点shapefile var dfe = dFS.AddFeature(new Point(gpsData.GPSTrajectoriesData[i].End)); dfe.DataRow.BeginEdit(); dfe.DataRow["UserID"] = gpsData.GPSTrajectoriesData[i].UserID; dfe.DataRow["Time"] = gpsData.GPSTrajectoriesData[i].End.TimeStamp; dfe.DataRow.EndEdit(); } oFS.SaveAs("OriginalPoints.shp", true); dFS.SaveAs("DesPoints.shp", true); } }
public static void CreatingAPolygonInFeatureSet() { 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); }
/// <summary> /// 신규 레이어 생성하고, 편집레이어로 설정 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void NewButtonClick(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 MultiPointSaveAsWorking() { var vertices = new[] { new Coordinate(10.1, 20.2, 3.3, 4.4), new Coordinate(11.1, 22.2, 3.3, 4.4) }; var mp = new MultiPoint(vertices.CastToPointArray()); var f = new Feature(mp); var fs = new FeatureSet(f.FeatureType) { Projection = KnownCoordinateSystems.Geographic.World.WGS1984 }; fs.Features.Add(f); var fileName = FileTools.GetTempFileName(".shp"); try { Assert.DoesNotThrow(() => fs.SaveAs(fileName, true)); } catch (Exception) { FileTools.DeleteShapeFile(fileName); } }
public static void createSHPLineBulk(string fileName, string tableName, List <IndexedDictionary <string, string[]> > dataColl) { try { FeatureSet fs = new FeatureSet(FeatureType.Line); fs = SHPSchemaManager.createSchema(fs, dataColl[0]); foreach (var data in dataColl) { fs = SHPCRUD.SHPLineDataHandler(fs, data); } // save the feature set Debug.Write("\nSHP FILE::: " + fileName + "\n"); fs.SaveAs(fileName, true); } catch (SystemException ex) { Debug.Write("\n" + ex.ToString()); } }
public static void createSHP() { // See comments below this code for an updated version. // 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 <DotSpatial.Topology.Coordinate> vertices = new List <DotSpatial.Topology.Coordinate>(); vertices.Add(new DotSpatial.Topology.Coordinate(0, 0)); vertices.Add(new DotSpatial.Topology.Coordinate(0, 100)); vertices.Add(new DotSpatial.Topology.Coordinate(100, 100)); vertices.Add(new DotSpatial.Topology.Coordinate(100, 0)); Polygon geom = new Polygon(vertices); // add the geometry to the featureset. DotSpatial.Data.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(); // save the feature set fs.SaveAs(@"H:\temp\12Converter\SHPTEST\test.shp", true); }
public void CoordinateType_WriteOnSaveAs() { var outfile = FileTools.GetTempFileName(".shp"); IFeatureSet fs = new FeatureSet(); var c = new Coordinate(10.1, 20.2, 3.3, 4.4); IFeature f = new Feature(c); fs.CoordinateType = CoordinateType.Z; fs.Projection = KnownCoordinateSystems.Geographic.World.WGS1984; fs.DataTable.Columns.Add(new DataColumn(("ID"), typeof(int))); f = fs.AddFeature(f); f.ShapeType = ShapeType.PointZ; f.DataRow.BeginEdit(); f.DataRow["ID"] = 1; f.DataRow.EndEdit(); fs.SaveAs(outfile, true); var actual = FeatureSet.Open(outfile); try { Assert.AreEqual(fs.CoordinateType, actual.CoordinateType); } finally { FileTools.DeleteShapeFile(outfile); } }
public void SaveShapeFileCustomFieldMappings(bool customFieldMapper) { if (customFieldMapper) { FieldTypeCharacterMapperManager.Mapper = new CustomTestFieldMapper(); } var featureType = FeatureType.Line; var coordinateType = CoordinateType.Regular; var fileName = FileTools.GetTempFileName(".shp"); try { var coords = new List <Coordinate> { new Coordinate(1, 2), new Coordinate(3, 4), new Coordinate(5, 6), new Coordinate(7, 8), new Coordinate(1, 2) }; var fs = new FeatureSet(featureType) { Projection = KnownCoordinateSystems.Geographic.World.WGS1984, CoordinateType = coordinateType }; fs.DataTable.Columns.Add(new DataColumn("doublefield", typeof(double))); fs.DataTable.Columns.Add(new DataColumn("decimalfield", typeof(decimal))); fs.DataTable.Columns.Add(new DataColumn("floatfield", typeof(float))); fs.DataTable.Columns.Add(new DataColumn("stringfield", typeof(string))); var feature = fs.AddFeature(new LineString(coords.ToArray())); feature.DataRow.BeginEdit(); feature.DataRow["doublefield"] = 0.05d; feature.DataRow["decimalfield"] = 0.05m; feature.DataRow["floatfield"] = 0.05f; feature.DataRow["stringfield"] = "hello world"; feature.DataRow.EndEdit(); Assert.DoesNotThrow(() => fs.SaveAs(fileName, true)); var loaded = FeatureSet.Open(fileName); if (customFieldMapper) { Assert.True(new Field(loaded.DataTable.Columns[0]).TypeCharacter == FieldTypeCharacters.Double); Assert.True(new Field(loaded.DataTable.Columns[1]).TypeCharacter == FieldTypeCharacters.Double); Assert.True(new Field(loaded.DataTable.Columns[2]).TypeCharacter == FieldTypeCharacters.Double); } else { Assert.True(new Field(loaded.DataTable.Columns[0]).TypeCharacter == FieldTypeCharacters.Number); Assert.True(new Field(loaded.DataTable.Columns[1]).TypeCharacter == FieldTypeCharacters.Number); Assert.True(new Field(loaded.DataTable.Columns[2]).TypeCharacter == FieldTypeCharacters.Number); } Assert.True(((Field)loaded.DataTable.Columns[3]).TypeCharacter == FieldTypeCharacters.Text); } finally { FileTools.DeleteShapeFile(fileName); FieldTypeCharacterMapperManager.Mapper = new FieldTypeCharacterMapper(); } }
public void SaveFeatureToShapefileWithMandZ(CoordinateType c, FeatureType ft) { var fileName = FileTools.GetTempFileName(".shp"); try { List <Coordinate> coords = new List <Coordinate> { new Coordinate(1, 2, 7, 4), new Coordinate(3, 4, 5, 6), new Coordinate(5, 6, 3, 8), new Coordinate(7, 8, 9, 10), new Coordinate(1, 2, 7, 4) }; var fs = new FeatureSet(ft) { Projection = KnownCoordinateSystems.Geographic.World.WGS1984, CoordinateType = c }; switch (ft) { case FeatureType.Line: fs.AddFeature(new LineString(coords.ToArray())); break; case FeatureType.Polygon: fs.AddFeature(new Polygon(new LinearRing(coords.ToArray()))); break; case FeatureType.MultiPoint: coords.RemoveAt(4); fs.AddFeature(new MultiPoint(coords.CastToPointArray())); break; } Assert.DoesNotThrow(() => fs.SaveAs(fileName, true)); var loaded = FeatureSet.Open(fileName); if (c == CoordinateType.Regular) { // regular coordinates don't have m values Assert.AreEqual(double.NaN, loaded.Features[0].Geometry.Coordinates[0].M); Assert.AreEqual(double.NaN, loaded.Features[0].Geometry.EnvelopeInternal.Minimum.M); Assert.AreEqual(double.NaN, loaded.Features[0].Geometry.EnvelopeInternal.Maximum.M); } else { // m or z coordinates have m values Assert.AreEqual(4, loaded.Features[0].Geometry.Coordinates[0].M); Assert.AreEqual(4, loaded.Features[0].Geometry.EnvelopeInternal.Minimum.M); Assert.AreEqual(10, loaded.Features[0].Geometry.EnvelopeInternal.Maximum.M); } if (c == CoordinateType.Z) { // z coordinates have z values Assert.AreEqual(7, loaded.Features[0].Geometry.Coordinates[0].Z); Assert.AreEqual(3, loaded.Features[0].Geometry.EnvelopeInternal.Minimum.Z); Assert.AreEqual(9, loaded.Features[0].Geometry.EnvelopeInternal.Maximum.Z); } else { // regular and m coordinates don't have z values Assert.AreEqual(double.NaN, loaded.Features[0].Geometry.Coordinates[0].Z); Assert.AreEqual(double.NaN, loaded.Features[0].Geometry.EnvelopeInternal.Minimum.Z); Assert.AreEqual(double.NaN, loaded.Features[0].Geometry.EnvelopeInternal.Maximum.Z); } } finally { FileTools.DeleteShapeFile(fileName); } }
static void GetDataOfEachCentoid2() { Stopwatch sw = new Stopwatch(); sw.Start(); Console.WriteLine("开始读取数据"); IFeatureSet centroid = FeatureSet.Open(@"D:\OneDrive\2017研究生毕业设计\数据\项目用数据\newCentroidNoDup.shp"); IFeatureSet LargePoints = FeatureSet.Open(@"D:\OneDrive\2017研究生毕业设计\数据\项目用数据\OriginalGauss.shp"); string newColumnName = "Subject"; LargePoints.DataTable.Columns.Add(newColumnName, typeof(int)); sw.Stop(); Console.WriteLine("数据读取完成,耗费时间为{0}s", sw.Elapsed.TotalSeconds); sw.Restart(); Console.WriteLine("开始处理数据"); KdTree myTree = new KdTree(2); foreach (var item in centroid.Features) { var c = item.Coordinates[0]; myTree.Insert(new double[] { c.X, c.Y }, item); } Console.WriteLine("KD树构建完成"); int core = 8; IFeature[] newFeatures = LargePoints.Features.ToArray(); double eachTaskPointsCount = LargePoints.NumRows() / 8.0; Parallel.For(0, core, new Action <int>((index) => { //并行任务开始 int start = (int)Math.Ceiling(index * eachTaskPointsCount); int end = index != 7 ? (int)Math.Floor((index + 1) * eachTaskPointsCount) : LargePoints.NumRows() - 1; Console.WriteLine("开始为:{0},终点为:{1}", start, end); for (int i = start; i <= end; i++) { var currentFeature = newFeatures[i]; Coordinate c = currentFeature.Coordinates[0]; IFeature f = myTree.Nearest(new double[] { c.X, c.Y }) as IFeature; lock (currentFeature.DataRow.Table) { currentFeature.DataRow.BeginEdit(); if (f.Distance(currentFeature) <= 350) { currentFeature.DataRow[newColumnName] = f.Fid; } else { currentFeature.DataRow[newColumnName] = -1; } currentFeature.DataRow.EndEdit(); } } })); sw.Stop(); Console.WriteLine("计算结束!还需保存!耗时:{0}", sw.Elapsed.TotalSeconds); FeatureSet newFeatureSet = new FeatureSet(newFeatures); newFeatureSet.Name = "OriginalGaussWithSubject"; newFeatureSet.Projection = LargePoints.Projection; newFeatureSet.SaveAs(newFeatureSet.Name + ".shp", true); Console.WriteLine("保存完毕!"); Console.ReadKey(); }
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) { } }
/// <summary> /// This is the method that actually does the work. /// </summary> /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param> protected override void SolveInstance(IGH_DataAccess DA) { // First, we need to retrieve all data from the input parameters. List <string> fields = new List <string>(); GH_Structure <IGH_Goo> attributes = new GH_Structure <IGH_Goo>(); GH_Structure <GH_Point> inputPointTree = new GH_Structure <GH_Point>(); bool writeFile = false; string filePath = ""; string prj = null; if (!DA.GetData(5, ref writeFile)) { return; } if (!DA.GetData(4, ref filePath)) { return; } // access the input parameter by index. if (!DA.GetDataTree(0, out inputPointTree)) { return; } if (!DA.GetDataList(1, fields)) { return; } if (!DA.GetDataTree(2, out attributes)) { return; } if (!DA.GetData(3, ref prj)) { return; } //create new feature set to add data to //FeatureSet fs = new FeatureSet(FeatureType.Polygon); //FeatureSet fs = new FeatureSet(FeatureType.Point); FeatureSet fs = new FeatureSet(FeatureType.MultiPoint); if (prj != null) { //load projection file string cur_proj = System.IO.File.ReadAllText(@prj); ///create Projection system ProjectionInfo targetProjection = new ProjectionInfo(); targetProjection.ParseEsriString(cur_proj); fs.Projection = targetProjection; } if (writeFile) { // Add fields to the feature sets attribute table foreach (string field in fields) { //<<<dubble chack if this is properly declaring type>>>\\ fs.DataTable.Columns.Add(new DataColumn(field, typeof(string))); } // for every branch (ie feature) foreach (GH_Path path in inputPointTree.Paths) { //set branch IList branch = inputPointTree.get_Branch(path); // create a feature geometry List <Coordinate> vertices = new List <Coordinate>(); //add all pt coordinates to the vertices list foreach (GH_Point pt in branch) { Point3d rhinoPoint = new Point3d(); GH_Convert.ToPoint3d(pt, ref rhinoPoint, 0); vertices.Add(new Coordinate(rhinoPoint.X, rhinoPoint.Y)); } //Convert Coordinates to dot spatial point or multipoint geometry //DotSpatial.Topology.Point geom = new DotSpatial.Topology.Point(vertices); DotSpatial.Topology.MultiPoint geom = new DotSpatial.Topology.MultiPoint(vertices); //convert geom to a feature IFeature feature = fs.AddFeature(geom); //begin editing to add feature attributes feature.DataRow.BeginEdit(); //get this features attributes by its path IList <string> featrueAttributes = attributes.get_Branch(path) as IList <string>; int thisIndex = 0; //add each attribute for the pt's path foreach (var thisAttribute in attributes.get_Branch(path)) { //converting all fields to (((Proper Type...?))) feature.DataRow[fields[thisIndex]] = thisAttribute.ToString(); //currently everything is a string.... //<<<!!!!!!!!!! dubble chack if this is properly converting to the type declared above !!!!!!!!!!>>>\\ thisIndex++; } //finish attribute additions feature.DataRow.EndEdit(); }//end of itterating through branches of pt tree fs.SaveAs(filePath, true); } }
public void UnionFeatureSetTest() { var file = Path.Combine(_shapefiles, @"Topology_Test.shp"); IFeatureSet fs = FeatureSet.Open(file); 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) { } }
public void MultiPoint_SaveAsWorking() { var vertices = new[] { new Coordinate(10.1, 20.2, 3.3, 4.4), new Coordinate(11.1, 22.2, 3.3, 4.4) }; var mp = new MultiPoint(vertices); var f = new Feature(mp); var fs = new FeatureSet(f.FeatureType) { Projection = KnownCoordinateSystems.Geographic.World.WGS1984 }; fs.Features.Add(f); var fileName = FileTools.GetTempFileName(".shp"); try { Assert.DoesNotThrow(() => fs.SaveAs(fileName, true)); } catch (Exception) { FileTools.DeleteShapeFile(fileName); } }
public void UtmProjection_SamePoints_AfterSaveLoadShapeFile() { var fs = new FeatureSet(FeatureType.Point) { Projection = KnownCoordinateSystems.Projected.UtmWgs1984.WGS1984UTMZone33N // set any UTM projection }; const double originalX = 13.408056; const double originalY = 52.518611; var wgs = KnownCoordinateSystems.Geographic.World.WGS1984; var c = new[] { originalX, originalY }; var z = new[] { 0.0 }; Reproject.ReprojectPoints(c, z, wgs, fs.Projection, 0, 1); var pt = new Point(c[0], c[1]); fs.AddFeature(pt); var tmpFile = FileTools.GetTempFileName(".shp"); fs.SaveAs(tmpFile, true); try { // Now try to open saved shapefile // Points must have same location in WGS1984 var openFs = FeatureSet.Open(tmpFile); var fs0 = (Point) openFs.Features[0].BasicGeometry; var c1 = new[] {fs0.X, fs0.Y}; Reproject.ReprojectPoints(c1, z, openFs.Projection, wgs, 0, 1); // reproject back to wgs1984 Assert.IsTrue(Math.Abs(originalX - c1[0]) < 1e-8); Assert.IsTrue(Math.Abs(originalY - c1[1]) < 1e-8); } finally { FileTools.DeleteShapeFile(tmpFile); } }