/// <summary> /// Creates a points shapefile /// </summary> /// <param name="FileName"></param> private static void TestCreatePointsShapeFile(string FileName) { var points = new List <string>() { "P1", "P2", "P3", "P4" }; OSGeo.OGR.Driver drv = Ogr.GetDriverByName("ESRI Shapefile"); using (var ds = drv.CreateDataSource(FileName, new string[] {})) { var src = new OSGeo.OSR.SpatialReference(""); src.ImportFromEPSG(23030); using (var layer = ds.CreateLayer("SENSORS", src, wkbGeometryType.wkbPoint, new string[] {})) { FieldDefn fdefn = new FieldDefn("ID", FieldType.OFTString); fdefn.SetWidth(32); layer.CreateField(fdefn, 1); fdefn = new FieldDefn("FIELD_2", FieldType.OFTReal); layer.CreateField(fdefn, 1); foreach (var s in points) { Feature feature = new Feature(layer.GetLayerDefn()); feature.SetField("ID", s); feature.SetField("FIELD_2", 123.4d); var geom = new Geometry(wkbGeometryType.wkbPoint); double X = 123.4; double Y = 123.4; geom.AddPointZM(X, Y, 123.4d, 0d); feature.SetGeometry(geom); layer.CreateFeature(feature); } } ds.FlushCache(); } }
private static void SetShp(Layer PointLayer, Fornix fornix) { if (-1 == PointLayer.FindFieldIndex("trend", 0)) { FieldDefn oFieldName0 = new FieldDefn("trend", FieldType.OFTReal); oFieldName0.SetWidth(50); oFieldName0.SetPrecision(7); PointLayer.CreateField(oFieldName0, 1); } if (-1 == PointLayer.FindFieldIndex("incli", 0)) { FieldDefn oFieldName1 = new FieldDefn("incli", FieldType.OFTReal); oFieldName1.SetWidth(50); oFieldName1.SetPrecision(7); PointLayer.CreateField(oFieldName1, 1); } if (-1 == PointLayer.FindFieldIndex("dip", 0)) { FieldDefn oFieldName2 = new FieldDefn("dip", FieldType.OFTReal); oFieldName2.SetWidth(50); oFieldName2.SetPrecision(7); PointLayer.CreateField(oFieldName2, 1); } for (int i = 0; i < (int)PointLayer.GetFeatureCount(0); ++i) { Vertex vertex = fornix.outSide.upvers.getVer(i); Feature pointFeature = PointLayer.GetFeature(i); pointFeature.SetField("trend", vertex.occurrence.trend); pointFeature.SetField("incli", vertex.occurrence.inclination); pointFeature.SetField("dip", vertex.occurrence.dip); PointLayer.SetFeature(pointFeature); //更改其值 pointFeature.Dispose(); //释放对象 } }
public static FieldDefn ToFieldDefn(MG_Field field) { FieldType type = ToFieldType(field.Type); FieldDefn def = new FieldDefn(field.Name, type); def.SetWidth(field.Width); def.SetPrecision(field.Precision); return(def); }
private void button1_Click(object sender, EventArgs e) { da.InitinalGdal(); da.GetShpLayer(av); FieldDefn oFieldI = new FieldDefn(textBox1.Text, FieldType.OFTInteger); oFieldI.SetWidth(Convert.ToInt32(textBox2.Text)); da.oLayer.CreateField(oFieldI, 1); SX(); }
public void AddFieldInteger(string name, int width) { FieldDefn fdefn = new FieldDefn(name, FieldType.OFTInteger); fdefn.SetWidth(width); if (_layer.CreateField(fdefn, 1) != 0) { throw new Exception("Nie można utworzyć pola " + name); } }
public void AddFieldReal(string name, int width, int precision) { FieldDefn fdefn = new FieldDefn(name, FieldType.OFTReal); fdefn.SetWidth(width); fdefn.SetPrecision(precision); if (_layer.CreateField(fdefn, 1) != 0) { throw new Exception("Nie można utworzyć pola " + name); } }
public void defineAtrybutTekstowy(string fieldName, int fieldSize) { FieldDefn fdefn = new FieldDefn(fieldName, FieldType.OFTString); fdefn.SetWidth(fieldSize); Console.WriteLine(" Dodawanie atrybutu " + fieldName); if (this.layer.CreateField(fdefn, 1) != 0) { throw new Exception("-FAILED-"); } }
public void AddField(string FieldName, FieldType fieldType, int FieldLength) { if (oLayer == null) { Console.WriteLine("目标图层为null,无法添加字段!"); return; } FieldDefn oFieldDef = new FieldDefn(FieldName, fieldType); if (FieldLength > 0) { oFieldDef.SetWidth(FieldLength); } oLayer.CreateField(oFieldDef, 1); }
public bool CreateField(string name, FieldType fieldType, int length) { // Creating and adding attribute fields to layer FieldDefn fieldDefn = new FieldDefn(name, fieldType); fieldDefn.SetWidth(length); if (_ogrLayer.CreateField(fieldDefn, 1) != 0) { Console.WriteLine("Creating field failed"); return(false); } return(true); }
/// <summary> /// 创建坐标红线图层(生成shp文件) /// </summary> /// <returns></returns> public static Layer CreateRedLineLayer(DataSource dataSource, int wkid, string shpFilePath) { //创建图层 var spatialRef = new SpatialReference(""); spatialRef.ImportFromEPSG(wkid); Layer layer = dataSource.CreateLayer(Path.GetFileNameWithoutExtension(shpFilePath), spatialRef, wkbGeometryType.wkbPolygon, null); //定义字段 foreach (TField baseField in CfgRedlineTxt.BlockFields) { FieldDefn fieldDefn = new FieldDefn(baseField.FieldName, FieldType.OFTString); fieldDefn.SetWidth(1000); layer.CreateField(fieldDefn, 1); } return(layer); }
public void CreateShp(string layerName, List <Geometry> GeomList) { string strDriverName = "ESRI Shapefile"; using (Driver oDriver = Ogr.GetDriverByName(strDriverName)) { //用此Driver创建Shape文件 OSGeo.OGR.DataSource poDS; poDS = oDriver.CreateDataSource(_outputFileName, null); if (poDS == null) { MessageBox.Show("DataSource Creation Error"); } using (DataSource oDS = oDriver.CreateDataSource(_outputFileName, null)) { //步骤2、创建空间坐标系 OSGeo.OSR.SpatialReference oSRS = new OSGeo.OSR.SpatialReference(""); oSRS.SetWellKnownGeogCS("WGS84"); //步骤3、创建图层,并添加坐标系,创建一个多边形图层(wkbGeometryType.wkbUnknown,存放任意几何特征) Layer oLayer = oDS.CreateLayer(layerName, oSRS, wkbGeometryType.wkbUnknown, null); // 步骤4、下面创建属性表 FieldDefn oFieldPlotArea = new FieldDefn("Name", FieldType.OFTString); // 先创建一个叫PlotArea的属性 oFieldPlotArea.SetWidth(100); // 步骤5、将创建的属性表添加到图层中 oLayer.CreateField(oFieldPlotArea, 1); foreach (var geom in GeomList) { //步骤6、定义一个特征要素oFeature(特征要素包含两个方面1.属性特征2.几何特征) FeatureDefn oDefn = oLayer.GetLayerDefn(); Feature oFeature = new Feature(oDefn); //建立了一个特征要素并将指向图层oLayer的属性表 oFeature.SetField(0, -1); //步骤7、设置属性特征的值 oFeature.SetGeometry(geom); //步骤8、设置几何特征 oLayer.CreateFeature(oFeature); //步骤9、将特征要素添加到图层中 } } } MessageBox.Show("成功导出文件到" + _outputFileName); }
public static void Main(string[] args) { if (args.Length != 2) { usage(); } // Using early initialization of System.Console Console.WriteLine(""); /* -------------------------------------------------------------------- */ /* Register format(s). */ /* -------------------------------------------------------------------- */ Ogr.RegisterAll(); /* -------------------------------------------------------------------- */ /* Get driver */ /* -------------------------------------------------------------------- */ Driver drv = Ogr.GetDriverByName("ESRI Shapefile"); if (drv == null) { Console.WriteLine("Can't get driver."); System.Environment.Exit(-1); } // TODO: drv.name is still unsafe with lazy initialization (Bug 1339) //string DriverName = drv.name; //Console.WriteLine("Using driver " + DriverName); /* -------------------------------------------------------------------- */ /* Creating the datasource */ /* -------------------------------------------------------------------- */ DataSource ds = drv.CreateDataSource(args[0], new string[] {}); if (drv == null) { Console.WriteLine("Can't create the datasource."); System.Environment.Exit(-1); } /* -------------------------------------------------------------------- */ /* Creating the layer */ /* -------------------------------------------------------------------- */ Layer layer; int i; for (i = 0; i < ds.GetLayerCount(); i++) { layer = ds.GetLayerByIndex(i); if (layer != null && layer.GetLayerDefn().GetName() == args[1]) { Console.WriteLine("Layer already existed. Recreating it.\n"); ds.DeleteLayer(i); break; } } layer = ds.CreateLayer(args[1], null, wkbGeometryType.wkbPoint, new string[] {}); if (layer == null) { Console.WriteLine("Layer creation failed."); System.Environment.Exit(-1); } /* -------------------------------------------------------------------- */ /* Adding attribute fields */ /* -------------------------------------------------------------------- */ FieldDefn fdefn = new FieldDefn("Name", FieldType.OFTString); fdefn.SetWidth(32); if (layer.CreateField(fdefn, 1) != 0) { Console.WriteLine("Creating Name field failed."); System.Environment.Exit(-1); } fdefn = new FieldDefn("IntField", FieldType.OFTInteger); if (layer.CreateField(fdefn, 1) != 0) { Console.WriteLine("Creating IntField field failed."); System.Environment.Exit(-1); } fdefn = new FieldDefn("DbleField", FieldType.OFTReal); if (layer.CreateField(fdefn, 1) != 0) { Console.WriteLine("Creating DbleField field failed."); System.Environment.Exit(-1); } fdefn = new FieldDefn("DateField", FieldType.OFTDate); if (layer.CreateField(fdefn, 1) != 0) { Console.WriteLine("Creating DateField field failed."); System.Environment.Exit(-1); } /* -------------------------------------------------------------------- */ /* Adding features */ /* -------------------------------------------------------------------- */ Feature feature = new Feature(layer.GetLayerDefn()); feature.SetField("Name", "value"); feature.SetField("IntField", (int)123); feature.SetField("DbleField", (double)12.345); feature.SetField("DateField", 2007, 3, 15, 18, 24, 30, 0); Geometry geom = Geometry.CreateFromWkt("POINT(47.0 19.2)"); if (feature.SetGeometry(geom) != 0) { Console.WriteLine("Failed add geometry to the feature"); System.Environment.Exit(-1); } if (layer.CreateFeature(feature) != 0) { Console.WriteLine("Failed to create feature in shapefile"); System.Environment.Exit(-1); } ReportLayer(layer); }
public static void WriteVectorFile(string strVectorFile) { Gdal.AllRegister(); // 为了支持中文路径,请添加下面这句代码 OSGeo.GDAL.Gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "NO"); // 为了使属性表字段支持中文,请添加下面这句 OSGeo.GDAL.Gdal.SetConfigOption("SHAPE_ENCODING", ""); //string strVectorFile = @"C:\Users\Administrator\Desktop\shptest\TestPolygon.shp"; // 注册所有的驱动 Ogr.RegisterAll(); //创建数据,这里以创建ESRI的shp文件为例 string strDriverName = "ESRI Shapefile"; OSGeo.OGR.Driver oDriver = Ogr.GetDriverByName(strDriverName); if (oDriver == null) { MessageBox.Show("%s 驱动不可用!\n", strVectorFile); return; } // 创建数据源 DataSource oDS = oDriver.CreateDataSource(strVectorFile, null); if (oDS == null) { MessageBox.Show("创建矢量文件【%s】失败!\n", strVectorFile); return; } // 创建图层,创建一个多边形图层,这里没有指定空间参考,如果需要的话,需要在这里进行指定 Layer oLayer = oDS.CreateLayer("TestPolygon", null, wkbGeometryType.wkbPolygon, null); if (oLayer == null) { MessageBox.Show("图层创建失败!\n"); return; } // 下面创建属性表 // 先创建一个叫FieldID的整型属性 FieldDefn oFieldID = new FieldDefn("FieldID", FieldType.OFTInteger); oLayer.CreateField(oFieldID, 1); // 再创建一个叫FeatureName的字符型属性,字符长度为50 FieldDefn oFieldName = new FieldDefn("FieldName", FieldType.OFTString); oFieldName.SetWidth(100); oLayer.CreateField(oFieldName, 1); FeatureDefn oDefn = oLayer.GetLayerDefn(); // 创建三角形要素 Feature oFeatureTriangle = new Feature(oDefn); oFeatureTriangle.SetField(0, 0); oFeatureTriangle.SetField(1, "三角形"); Geometry geomTriangle = Geometry.CreateFromWkt("POLYGON ((0 0,20 0,10 15,0 0))"); oFeatureTriangle.SetGeometry(geomTriangle); oLayer.CreateFeature(oFeatureTriangle); // 创建矩形要素 Feature oFeatureRectangle = new Feature(oDefn); oFeatureRectangle.SetField(0, 1); oFeatureRectangle.SetField(1, "矩形"); Geometry geomRectangle = Geometry.CreateFromWkt("POLYGON ((30 0,60 0,60 30,30 30,30 0))"); oFeatureRectangle.SetGeometry(geomRectangle); oLayer.CreateFeature(oFeatureRectangle); // 创建岛要素 Feature oFeatureHole = new Feature(oDefn); oFeatureHole.SetField(0, 1); oFeatureHole.SetField(1, "环岛测试"); //Geometry geomWYX = Geometry.CreateFromWkt("POLYGON ((30 0,60 0,60 30,30 30,30 0))"); OSGeo.OGR.Geometry outGeo = new OSGeo.OGR.Geometry(OSGeo.OGR.wkbGeometryType.wkbLinearRing); outGeo.AddPoint(40, -30, 0); outGeo.AddPoint(60, -30, 0); outGeo.AddPoint(60, -10, 0); outGeo.AddPoint(40, -10, 0); OSGeo.OGR.Geometry inGeo = new OSGeo.OGR.Geometry(OSGeo.OGR.wkbGeometryType.wkbLinearRing); inGeo.AddPoint(45, -25, 0); inGeo.AddPoint(55, -25, 0); inGeo.AddPoint(55, -15, 0); inGeo.AddPoint(45, -15, 0); OSGeo.OGR.Geometry geo = new OSGeo.OGR.Geometry(OSGeo.OGR.wkbGeometryType.wkbPolygon); geo.AddGeometryDirectly(outGeo); geo.AddGeometryDirectly(inGeo); oFeatureHole.SetGeometry(geo); oLayer.CreateFeature(oFeatureHole); // 创建Multi要素 Feature oFeatureMulty = new Feature(oDefn); oFeatureMulty.SetField(0, 1); oFeatureMulty.SetField(1, "MultyPart测试"); OSGeo.OGR.Geometry geo1 = new OSGeo.OGR.Geometry(OSGeo.OGR.wkbGeometryType.wkbLinearRing); geo1.AddPoint(25, -10, 0); geo1.AddPoint(5, -10, 0); geo1.AddPoint(5, -30, 0); geo1.AddPoint(25, -30, 0); OSGeo.OGR.Geometry poly1 = new Geometry(wkbGeometryType.wkbPolygon); poly1.AddGeometryDirectly(geo1); OSGeo.OGR.Geometry geo2 = new OSGeo.OGR.Geometry(OSGeo.OGR.wkbGeometryType.wkbLinearRing); geo2.AddPoint(0, -15, 0); geo2.AddPoint(-5, -15, 0); geo2.AddPoint(-5, -20, 0); geo2.AddPoint(0, -20, 0); OSGeo.OGR.Geometry poly2 = new Geometry(wkbGeometryType.wkbPolygon); poly2.AddGeometryDirectly(geo2); OSGeo.OGR.Geometry geoMulty = new OSGeo.OGR.Geometry(OSGeo.OGR.wkbGeometryType.wkbMultiPolygon); geoMulty.AddGeometryDirectly(poly1); geoMulty.AddGeometryDirectly(poly2); oFeatureMulty.SetGeometry(geoMulty); oLayer.CreateFeature(oFeatureMulty); MessageBox.Show("\n数据集创建完成!\n"); }
/// <summary> /// Outputs the specified DotSpatial IFeatureLayer to an OGR layer /// </summary> /// <param name="pDrvNm">A name like KML, ESRI SHapefile or FileGDB etc.</param> /// <param name="pFLyr">A layer that implements the IFeatureLayer interface</param> /// <param name="pOPFn">The outputShapefileName of the output file</param> /// <param name="pSrcProj">The SRS of the source dataset</param> /// <param name="pTgtProj">The SRS of the output dataset</param> /// <param name="pHasTitle">A boolean flag that determines whether to create fieldAttributes special title field</param> /// <param name="pTitleFieldNames">A comma separated list of field names to be used in the special title field</param> /// <param name="pTitleFormat">The C# String.Format format of the special title field</param> /// <param name="pLCOpts">A string array of layer creation options in the form of OPTION=VALUE entries</param> /// <param name="pDSCOpts">A string of data source creation options in the form of OPTION=VALUE entries</param> /// <param name="pFieldMap">A dictionary of source and target field names to be translated on the source /// the title format field names and the special title field name all observe this field mapping.</param> /// <param name="pOnlyInFieldMap">If true, only writes fields that are included in the field-map</param> /// <returns>True on success, false on error</returns> /// <remarks> /// Presently implements special functions for KML that perhaps should be kept separate. /// </remarks> public static ReturnValue ExportFeatureLayerToOGR( string pDrvNm, IFeatureLayer pFLyr, string pOPFn, ProjectionInfo pSrcProj, ProjectionInfo pTgtProj, bool pHasTitle = false, string pTitleFieldNames = "", string pTitleFormat = "", List <string> pLCOpts = null, List <string> pDSCOpts = null, Dictionary <string, string> pFieldMap = null, bool pOnlyInFieldMap = false, bool pAppend = false) { var mReturnValue = new ReturnValue(true); //Check if data source and layer creation options are null and if so, create an empty list object for them pDSCOpts = (pDSCOpts != null) ? pDSCOpts : new List <string>(); pLCOpts = (pLCOpts != null) ? pLCOpts : new List <string>(); // May or may not be used, declared in any case; Dictionary <string, string> mTitleFieldValues = null; // Determine whether transformation is required bool mTransformRequired = (pSrcProj != pTgtProj) ? true : false; // Read the target SRS SpatialReference mTgtSRS = ExtFunctions.GetSpatialReferenceByEPSG(pTgtProj.AuthorityCode); // If transformation is needed, create fieldAttributes shared transformation object for the export if (mTransformRequired) { pFLyr.Projection = pSrcProj; pFLyr.Reproject(pTgtProj); } // Setup driver OSGeo.OGR.Driver drv = Ogr.GetDriverByName(pDrvNm); if (drv == null) { mReturnValue.AddMessage("Could not load driver", true); return(mReturnValue); } // Special handling of KML mFiles // Add special title name as datasource creation option if (pHasTitle && pDrvNm == "KML") { pDSCOpts.Add("NameField=" + ExtFunctions.TitleFieldName); } // Create fieldAttributes datasource DataSource ds = null; try { if (pAppend && (Directory.Exists(pOPFn) || File.Exists(pOPFn))) { ds = drv.Open(pOPFn, 1); } else { ds = drv.CreateDataSource(pOPFn, pDSCOpts.ToArray()); } if (ds == null) { mReturnValue.AddMessage("Could not create/open datasource"); return(mReturnValue); } } catch (Exception ex) { mReturnValue.AddMessage(ex.Message); return(mReturnValue); } // Find the geometry type of the source layer to determine output type wkbGeometryType mGeomType = DSGeomTypeToOgrGeomType(pFLyr.DataSet.FeatureType); if (mGeomType == wkbGeometryType.wkbNone) { mReturnValue.AddMessage("Could not parse geometry type of input layer"); return(mReturnValue); } // Create the new layer OSGeo.OGR.Layer l; if (pAppend && ds.HasLayer(pFLyr.LegendText.Replace(" ", "_"))) { l = ds.GetLayerByName(pFLyr.LegendText.Replace(" ", "_")); } else { l = ds.CreateLayer(pFLyr.LegendText, mTgtSRS, mGeomType, pLCOpts.ToArray()); } if (l == null) { mReturnValue.AddMessage("Failed to create file: "); return(mReturnValue); } // Create fieldAttributes list to hold the names of fields var mDataSourceFieldNames = new List <string>(); // Loop through all the fields foreach (DataColumn mDataColumn in pFLyr.DataSet.DataTable.Columns) { var mColType = DataTypeToOgrFieldType(mDataColumn.DataType); var mNewField = new FieldDefn(MapFieldName(mDataColumn.ColumnName, pFieldMap), mColType); if (mColType == FieldType.OFTString) { mNewField.SetWidth(mDataColumn.MaxLength); } if (pOnlyInFieldMap == false || (pOnlyInFieldMap && pFieldMap.Keys.Contains(mDataColumn.ColumnName))) { if (!pAppend || !l.HasField(mNewField.GetName())) { if (Ogr.OGRERR_NONE != l.CreateField(mNewField, 1)) { mReturnValue.AddMessage("Failed to add field: " + mDataColumn.ColumnName + " => " + MapFieldName(mDataColumn.ColumnName, pFieldMap)); return(mReturnValue); } } } mDataSourceFieldNames.Add(mNewField.GetName()); } // Add special title field, if the necessary information is present if (pHasTitle == true && !string.IsNullOrEmpty(pTitleFieldNames) && !string.IsNullOrEmpty(pTitleFormat) && !mDataSourceFieldNames.Contains(ExtFunctions.TitleFieldName)) { mTitleFieldValues = new Dictionary <string, string>(); var mTitleField = new FieldDefn(MapFieldName(TitleFieldName, pFieldMap), FieldType.OFTString); mTitleField.SetWidth(254); foreach (var mTitleFieldName in pTitleFieldNames.Split(',')) { mTitleFieldValues.Add(mTitleFieldName, ""); } l.CreateField(mTitleField, 1); } int createdFeatures = 0; // For each row in the source featureset for (int i = 0; i < pFLyr.DataSet.NumRows(); i++) { // Read the source feature IFeature mSrcFeature = pFLyr.DataSet.GetFeature(i); // Read and set the geometry on the new feature byte[] mSrcGeom = mSrcFeature.ToBinary(); var mFeature = new OSGeo.OGR.Feature(l.GetLayerDefn()); var mGeom = OSGeo.OGR.Geometry.CreateFromWkb(mSrcGeom); mFeature.SetGeometry(mGeom); // Set feature id mFeature.SetFID(i); // Handle fieldAttributes for (int j = 0; j < mDataSourceFieldNames.Count(); j++) { var mCurrentValue = mSrcFeature.DataRow[j]; if (pOnlyInFieldMap == false || (pOnlyInFieldMap && pFieldMap.Values.Contains(mDataSourceFieldNames[j]))) { if (mCurrentValue.GetType() == typeof(string)) { mFeature.SetField(mDataSourceFieldNames[j], Utilities.GetANSI((string)mCurrentValue)); } else if (mCurrentValue.GetType() == typeof(int)) { mFeature.SetField(mDataSourceFieldNames[j], (int)mCurrentValue); } else if (mCurrentValue.GetType() == typeof(double)) { mFeature.SetField(mDataSourceFieldNames[j], (double)mCurrentValue); } } if (pHasTitle && mTitleFieldValues.Keys.Contains(mDataSourceFieldNames[j])) { mTitleFieldValues[mDataSourceFieldNames[j]] = mCurrentValue.ToString(); } } // If title field is to be created, use field values collected above to construct fieldAttributes new string format // to go into the title-field if (pHasTitle == true) { var mTitleValue = string.Format(pTitleFormat, mTitleFieldValues.Values.ToArray <string>()); mFeature.SetField(MapFieldName(TitleFieldName, pFieldMap), Utilities.GetANSI(mTitleValue)); } // Create the feature try { l.CreateFeature(mFeature); createdFeatures++; } catch (Exception ex) { mReturnValue.AddMessage(ex.Message); mReturnValue.AddMessage("Tip: A datasource may appear read-only if the file location is inside a dropbox folder and the dropbox application is running"); } } if (mTransformRequired) { pFLyr.Reproject(pSrcProj); } // Dispose and cleanup l.Dispose(); ds.Dispose(); drv.Dispose(); mReturnValue.AddMessage(String.Format("Added {0} features to layer {1}", createdFeatures, pFLyr.LegendText)); return(mReturnValue); }
/// <summary> /// 转换是否纠偏,只使用与火星坐标纠偏 /// </summary> /// <param name="dataTable">数据表,如果是点表中含X,Y字段,如果是线和面,表中含有PATH字段</param> /// <param name="filePath">存储路径</param> /// <param name="geoType">数据类型,暂时支持简单的点线面</param> /// <param name="jiupian">是否纠偏[火星坐标转84坐标]</param> public static void SaveShpFile(DataTable dataTable, string filePath, wkbGeometryType geoType, ProjectConvert jiupian) { if (geoType == wkbGeometryType.wkbLineString || geoType == wkbGeometryType.wkbPolygon) { if (!dataTable.Columns.Contains("PATH")) { return; } } else if (geoType == wkbGeometryType.wkbPoint) { if (!dataTable.Columns.Contains("X") || !dataTable.Columns.Contains("Y")) { return; } } else { return; } // 为了支持中文路径,请添加下面这句代码 OSGeo.GDAL.Gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "NO"); // 为了使属性表字段支持中文,请添加下面这句 OSGeo.GDAL.Gdal.SetConfigOption("SHAPE_ENCODING", ""); string strVectorFile = filePath; // 注册所有的驱动 Ogr.RegisterAll(); //创建数据,这里以创建ESRI的shp文件为例 string strDriverName = "ESRI Shapefile"; int count = Ogr.GetDriverCount(); Driver oDriver = Ogr.GetDriverByName(strDriverName); if (oDriver == null) { log.ErrorFormat("{0}驱动不可用!\n", strVectorFile); Console.WriteLine("{0}驱动不可用!\n", strVectorFile); return; } // 创建数据源 DataSource oDS = oDriver.CreateDataSource(strVectorFile, null); if (oDS == null) { log.ErrorFormat("创建矢量文件{0}失败!\n", strVectorFile); Console.WriteLine("创建矢量文件【%s】失败!\n", strVectorFile); return; } string strwkt = "GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS 84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],AUTHORITY[\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],UNIT[\"degree\",0.0174532925199433,AUTHORITY[\"EPSG\",\"9122\"]],AUTHORITY[\"EPSG\",\"4326\"]]"; OSGeo.OSR.SpatialReference srs = new OSGeo.OSR.SpatialReference(strwkt); // 创建图层,创建一个多边形图层,这里没有指定空间参考,如果需要的话,需要在这里进行指定 Layer oLayer = oDS.CreateLayer("test", null, geoType, null); if (oLayer == null) { Console.WriteLine("图层创建失败!\n"); return; } for (int i = 0; i < dataTable.Columns.Count; i++) { if (dataTable.Columns[i].ColumnName == "PATH") { continue; } string columnName = dataTable.Columns[i].ColumnName; FieldDefn oFieldName = new FieldDefn(columnName, FieldType.OFTString); oFieldName.SetWidth(255); oLayer.CreateField(oFieldName, 1); } FeatureDefn oDefn = oLayer.GetLayerDefn(); foreach (DataRow row in dataTable.Rows) { if ((geoType == wkbGeometryType.wkbPolygon || geoType == wkbGeometryType.wkbLineString) && string.IsNullOrEmpty(row["PATH"].ToString())) { continue; } // 创建Multi要素 Feature oFeatureMulty = new Feature(oDefn); for (int i = 0; i < dataTable.Columns.Count; i++) { if (geoType == wkbGeometryType.wkbPolygon || geoType == wkbGeometryType.wkbLineString) { if (dataTable.Columns[i].ColumnName == "PATH") { continue; } } string name = row[i] != null ? row[i].ToString() : ""; if (!string.IsNullOrEmpty(name)) { try { //oFeatureMulty.SetField(dataTable.Columns[i].ColumnName,name); var value = name.Trim().Replace("'", "").Replace(",", ""); if (value.Length > 255) { value = value.Substring(0, 250); } oFeatureMulty.SetField(i, value); } catch (Exception ex) { Console.WriteLine(ex); } } } if (geoType == wkbGeometryType.wkbPolygon || geoType == wkbGeometryType.wkbLineString) { string path = row["PATH"] != null ? row["PATH"].ToString() : ""; if (string.IsNullOrEmpty(path)) { continue; } var geoCount = path.Split('|').Length; wkbGeometryType newGeometryType = geoType; OSGeo.OGR.Geometry geo1 = new OSGeo.OGR.Geometry(geoType); if (geoType == wkbGeometryType.wkbPolygon) { if (geoCount > 1) { geo1 = new OSGeo.OGR.Geometry(wkbGeometryType.wkbMultiPolygon); for (int i = 0; i < geoCount; i++) { var temp = path.Split('|')[i]; var points = temp.Split(';'); OSGeo.OGR.Geometry innGeometry = new Geometry(wkbGeometryType.wkbLinearRing); for (int j = 0; j < points.Length; j++) { var c = ProjectChange(points[j], jiupian); innGeometry.AddPoint_2D(c.lon, c.lat); } var polygon = new Geometry(wkbGeometryType.wkbPolygon); polygon.AddGeometry(innGeometry); geo1.AddGeometry(polygon); } } else { geo1 = new OSGeo.OGR.Geometry(wkbGeometryType.wkbPolygon); for (int i = 0; i < geoCount; i++) { var temp = path.Split('|')[i]; var points = temp.Split(';'); OSGeo.OGR.Geometry innGeometry = new Geometry(wkbGeometryType.wkbLinearRing); for (int j = 0; j < points.Length; j++) { var c = ProjectChange(points[j], jiupian); innGeometry.AddPoint_2D(c.lon, c.lat); } geo1.AddGeometry(innGeometry); } } } else { if (geoCount > 1) { geo1 = new OSGeo.OGR.Geometry(wkbGeometryType.wkbMultiLineString); for (int i = 0; i < geoCount; i++) { var temp = path.Split('|')[i]; var points = temp.Split(';'); OSGeo.OGR.Geometry innGeometry = new Geometry(wkbGeometryType.wkbLinearRing); for (int j = 0; j < points.Length; j++) { var c = ProjectChange(points[j], jiupian); innGeometry.AddPoint_2D(c.lon, c.lat); } geo1.AddGeometry(innGeometry); } } else { for (int i = 0; i < geoCount; i++) { var temp = path.Split('|')[i]; var points = temp.Split(';'); geo1 = new OSGeo.OGR.Geometry(wkbGeometryType.wkbLinearRing); for (int j = 0; j < points.Length; j++) { var c = ProjectChange(points[j], jiupian); geo1.AddPoint_2D(c.lon, c.lat); } } } } //if (geoType == wkbGeometryType.wkbLineString) //{ // for (int i = 0; i < ps.Length; i++) // { // var c = ProjectChange(ps[i], jiupian); // geo1.AddPoint_2D(c.lon, c.lat); // } //} //else if (geoType == wkbGeometryType.wkbPolygon) //{ // List<int> indexs = new List<int>(); // indexs.Add(0); // for (int i = 0; i < ps.Length; i++) // { // if (ps[i].Split('|', ',').Length > 2) // { // indexs.Add(i); // } // } // indexs.Add(ps.Length - 1); // if (indexs.Count == 2) // { // OSGeo.OGR.Geometry outGeo = new OSGeo.OGR.Geometry(OSGeo.OGR.wkbGeometryType.wkbLinearRing); // for (int i = 0; i < ps.Length; i++) // { // var c = ProjectChange(ps[i], jiupian); // outGeo.AddPoint_2D(c.lon, c.lat); // } // var c1 = ProjectChange(ps[0], jiupian); // outGeo.AddPoint_2D(c1.lon, c1.lat); // geo1.AddGeometryDirectly(outGeo); // } // else // { // for (int j = 0; j < indexs.Count - 1; j++) // { // OSGeo.OGR.Geometry outGeo = new OSGeo.OGR.Geometry(OSGeo.OGR.wkbGeometryType.wkbLinearRing); // Coord sc = new Coord(); // int first = indexs[j]; // int end = indexs[j + 1]; // for (int i = first; i < end + 1; i++) // { // if (i == first && first != 0) // { // var c = ProjectChange(ps[i], jiupian); // outGeo.AddPoint(c.lon, c.lat,0); // } // else // { // if (jiupian != ProjectConvert.NONE) // { // var c = ProjectChange(ps[i], jiupian); // outGeo.AddPoint(c.lon, c.lat,0); // } // else // { // double x = double.Parse(ps[i].Split('|', ',')[0]); // double y = double.Parse(ps[i].Split('|', ',')[1]); // if (i == first) // { // sc.lon = x; // sc.lat = y; // } // outGeo.AddPoint(x, y, 0); // } // } // } // outGeo.AddPoint(sc.lon, sc.lat, 0); // geo1.AddGeometryDirectly(outGeo); // } // } //} oFeatureMulty.SetGeometry(geo1); } else if (geoType == wkbGeometryType.wkbPoint) { OSGeo.OGR.Geometry geo1 = new OSGeo.OGR.Geometry(wkbGeometryType.wkbPoint); string xstring = row["X"] != null ? row["X"].ToString() : ""; string ystring = row["Y"] != null ? row["Y"].ToString() : ""; double x = double.Parse(xstring); double y = double.Parse(ystring); Coord c = CoordHelper.Gcj2Wgs(x, y); geo1.AddPoint(c.lon, c.lat, 0); oFeatureMulty.SetGeometry(geo1); } oLayer.CreateFeature(oFeatureMulty); } oLayer.Dispose(); oDS.Dispose(); }
private void button4_Click(object sender, EventArgs e) { SaveFileDialog sfd = new SaveFileDialog(); sfd.Filter = "文本文件(*.txt)|*.shp|所有文件|*.*"; //设置文件类型 sfd.FileName = "po"; //设置默认文件名 sfd.DefaultExt = "shp"; //设置默认格式(可以不设) sfd.AddExtension = true; //设置自动在文件名中添加扩展名 string localFilePat = ""; if (sfd.ShowDialog() == DialogResult.OK) { //获得文件路径 string localFilePath = sfd.FileName.ToString(); localFilePat = localFilePath; } strVectorFile = localFilePat; MessageBox.Show(localFilePat); dabb.Add(localFilePat); pc.path.Add(localFilePat); pc.sdsad(localFilePat); //bb.pat = localFilePat; a = localFilePat; string strDriverName = "ESRI Shapefile"; int count = Ogr.GetDriverCount(); Driver oDriver = Ogr.GetDriverByName(strDriverName); if (oDriver == null) { Console.WriteLine("%s 驱动不可用!\n", strVectorFile); return; } // 创建数据源 DataSource oDS = oDriver.CreateDataSource(strVectorFile, null); if (oDS == null) { Console.WriteLine("创建矢量文件【%s】失败!\n", strVectorFile); return; } oLayer = oDS.CreateLayer(textBox3.Text, null, wkbGeometryType.wkbPoint, null); if (oLayer == null) { Console.WriteLine("图层创建失败!\n"); return; } // 下面创建属性表 // 先创建一个叫FieldID的整型属性 for (int i = 0; i < listView1.Items.Count; i++) { FieldDefn oFieldI = new FieldDefn(listView1.Items[i].SubItems[0].Text, FieldType.OFTInteger); oFieldI.SetWidth(Convert.ToInt32(listView1.Items[i].SubItems[1].Text)); oLayer.CreateField(oFieldI, 1); } //Feature poFeature = new Feature(oLayer.GetLayerDefn()); //Geometry pt = new Geometry(OSGeo.OGR.wkbGeometryType.wkbPoint); //for (int i = 100; i < 110; i++) //{ // //属性一"名称"赋值 // poFeature.SetField(0, i); // //属性二"高度"赋值 // poFeature.SetField(1, i); // //添加坐标点 // pt.AddPoint(i, i, i); // poFeature.SetGeometry(pt); // //将带有坐标及属性的Feature要素点写入Layer中 // oLayer.CreateFeature(poFeature); //} //关闭文件读写 //poFeature.Dispose(); oDS.Dispose(); oDriver.Dispose(); //string information = OGRReadFile.GetVectorInfo(strVectorFile); MessageBox.Show("创建成功!"); }
/// <summary> /// Transfers fieldAttributes from plot layer to address unit layer based on spatial intersection /// </summary> /// <param name="pFrm">The main application form</param> /// <param name="pTargetFileGDB">The outputShapefileName of fieldAttributes FileGDB with addressing data</param> /// <param name="pSrcShapefile">The outputShapefileName of fieldAttributes Shapefile with plot polygons</param> /// <param name="pFldsToCopy">A dictionary of source=>target field names</param> /// <param name="pMatchColPrefix">The prefix to assign to the match column</param> /// <param name="pBufSteps">An array of buffer steps</param> /// <param name="pFeatClassNm">The name of the feature class in the target FileGDB</param> /// <returns>True on success, false on error</returns> public static bool AddPlotIDsToAddressDB(frmMain pFrm, string pTargetFileGDB, string pSrcShapefile, Dictionary <string, string> pFldsToCopy, string pMatchColPrefix, double[] pBufSteps, string pFeatClassNm ) { string mMatchColNm = pMatchColPrefix + "_MATCH"; try { var mFileGDBDrv = OSGeo.OGR.Ogr.GetDriverByName("FileGDB"); var mTgtDSrc = mFileGDBDrv.Open(pTargetFileGDB, 1); var mTgtLyr = mTgtDSrc.GetLayerByName(pFeatClassNm); if (mTgtLyr != null) { pFrm.Log("Success opening target FileGDB"); DataSource mSrcDSrc = Ogr.Open(pSrcShapefile, 0); Layer mSrcLyr = mSrcDSrc.GetLayerByIndex(0); if (mSrcLyr != null) { pFrm.Log("Success opening source layer"); } foreach (string mSrcFieldName in pFldsToCopy.Keys) { if (!mTgtLyr.HasField(pFldsToCopy[mSrcFieldName]) && mSrcLyr.HasField(mSrcFieldName)) { //var mFieldDefn = mSrcLyr.GetNextFeature().GetFieldDefnRef(mSrcFieldName); var mFieldDefn = new FieldDefn(pFldsToCopy[mSrcFieldName], FieldType.OFTString); mFieldDefn.SetWidth(255); mTgtLyr.CreateField(mFieldDefn, 1); } } if (!mTgtLyr.HasField(mMatchColNm)) { var mFieldDefn = new FieldDefn(mMatchColNm, FieldType.OFTString); mFieldDefn.SetWidth(100); mTgtLyr.CreateField(mFieldDefn, 1); } mTgtLyr.ResetReading(); Feature mFeat = null; int idxAdr = 0; int idxHit = 0; int idxPass = 0; mTgtLyr.StartTransaction(); for (int idxStep = 0; idxStep < pBufSteps.Length; idxStep++) { double mBuf = pBufSteps[idxStep]; idxPass++; int idxAdrInner = 0; mTgtLyr.SetAttributeFilter(mMatchColNm + " ='' OR " + mMatchColNm + " IS null"); mTgtLyr.ResetReading(); int mAdrCount = mTgtLyr.GetFeatureCount(1); pFrm.Log("Pass #" + idxPass + " (" + mBuf + "m): " + mAdrCount + " features..."); while (null != (mFeat = mTgtLyr.GetNextFeature())) { Geometry mGeom; if (mBuf == 0) { mGeom = mFeat.GetGeometryRef(); } else { mGeom = mFeat.GetGeometryRef().Buffer(mBuf, 0); } mSrcLyr.ResetReading(); mSrcLyr.SetSpatialFilter(mGeom); Feature mHit = mSrcLyr.GetNextFeature(); int mPlotCount = mSrcLyr.GetFeatureCount(1); if (mHit != null && mPlotCount <= 2) { bool mUpd = false; if (mPlotCount < 2) { foreach (string mFieldName in pFldsToCopy.Keys) { var mFieldVal = mHit.GetFieldAsString(mFieldName); if (mFieldVal != null && mFieldVal.Length < 255) { mFeat.SetField(pFldsToCopy[mFieldName], mFieldVal); mUpd = true; } } } else { mUpd = true; } if (mUpd) { mFeat.SetField(pMatchColPrefix + "_MATCH", mPlotCount.ToString("00") + " hits within " + mBuf.ToString("00.00") + "m"); mTgtLyr.SetFeature(mFeat); mUpd = false; } idxHit++; } idxAdr++; idxAdrInner++; if (idxAdrInner % 500 == 0 || idxAdrInner == mAdrCount) { pFrm.Log(String.Format("Processed: {0} out of {1} features ({2} matches)", idxAdrInner, mAdrCount, idxHit)); Application.DoEvents(); } } } mSrcLyr.Dispose(); } mTgtLyr.CommitTransaction(); mTgtLyr.Dispose(); mTgtDSrc.Dispose(); mFileGDBDrv.Dispose(); } catch (Exception ex) { pFrm.Log(ex.Message); return(false); } return(true); }
/// <summary> /// 百度矢量要素下载(数据下载写入shp文件的时候可能出现问题,比如下载网络波动中断到时系统无法识别(解决办法先吧数据下载到数据在写入shp文件)) /// </summary> /// <param name="Result"></param> /// <returns></returns> public WebApiResult <string> BaiduDownload(BaiduMapFeatureDownloadResult Result) { this.countdown = new CountdownEvent(Result.TaskCount); this.Result_BFeature = Result; this.N = Result.TaskCount; UpdateLastLoc <BaiduMapFeatureDownloadResult>(Result.GUID); log = new TaskLogEntity() { GUID = Result.GUID, Name = Result.TName, Type = "矢量要素", Description = "BaiduDownload", Status = "进行中", Parameter = JsonHelper.ToJson(Result), SavePath = Result.SavePathText }; //操作日志 new Log <BaiduMapFeatureDownloadResult>(log); if (Result.LayerName == "道路") { xmlDoc.Load(MapFeatureConfig); /////////////////////////////////////////////////////////////////////////////// // GDAL创建shp文件 // 注册所有的驱动 Ogr.RegisterAll(); // GDAL中文路径支持 OSGeo.GDAL.Gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES"); // 属性表字段中文支持 OSGeo.GDAL.Gdal.SetConfigOption("SHAPE_ENCODING", "CP936"); // 设置坐标系存储文件夹gdal-data路径 OSGeo.GDAL.Gdal.SetConfigOption("GDAL_DATA", System.Windows.Forms.Application.StartupPath + "\\gdal-data"); Driver oDriver = Ogr.GetDriverByName("ESRI Shapefile"); if (oDriver == null) { return(new WebApiResult <string>() { success = 0, msg = "GDAL驱动不可用,请检查!" }); } // 创建数据源 DataSource oDS = oDriver.CreateDataSource(Result.SavePathText, null); if (oDS == null) { return(new WebApiResult <string>() { success = 0, msg = "创建数据源失败,请检查!" }); } oLayer = oDS.GetLayerByName(Result.TName); if (oLayer == null) { // 创建图层,创建一个多线图层,并指定空间参考 OSGeo.OSR.SpatialReference oSRS = new OSGeo.OSR.SpatialReference("PROJCS[\"WGS_1984_Pseudo_Mercator\",GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Mercator\"],PARAMETER[\"false_easting\",0.0],PARAMETER[\"false_northing\",0.0],PARAMETER[\"central_meridian\",0.0],PARAMETER[\"standard_parallel_1\",0.0],UNIT[\"Meter\",1.0]]"); //OSGeo.OSR.SpatialReference oSRS = new OSGeo.OSR.SpatialReference(""); //oSRS.SetWellKnownGeogCS("EPSG:4326"); oLayer = oDS.CreateLayer(Result.TName, oSRS, wkbGeometryType.wkbMultiLineString, null); if (oLayer == null) { return(new WebApiResult <string>() { success = 0, msg = "创建图层失败,请检查!" }); } // 创建属性表 // 先创建一个叫Name的字符型属性,字符长度为100 FieldDefn oFieldName = new FieldDefn("Name", FieldType.OFTString); oFieldName.SetWidth(100); oLayer.CreateField(oFieldName, 1); // 再创建一个叫Type的字符型属性,字符长度为50 FieldDefn oFieldType = new FieldDefn("Type", FieldType.OFTString); oFieldType.SetWidth(50); oLayer.CreateField(oFieldType, 1); // 再创建一个叫UID的字符型属性,字符长度为50 FieldDefn oFieldUID = new FieldDefn("UID", FieldType.OFTString); oFieldUID.SetWidth(50); oLayer.CreateField(oFieldUID, 1); } ///////////////////////////////////////////////////////////////////////////////// threadlog = new ThreadTaskLogEntity() { GUID = Result.GUID, TaskLog_GUID = Result.GUID, Status = "进行中", TStatus = 1, TName = Result.TName, IsPaused = false, URL = Result.URL, Parameter = JsonHelper.ToJson(Result) }; //计算Total并更新 threadlog.Total = GetList("SELECT KWName FROM mapbar_poi WHERE KWType = '道路'", "KWName").Count; new Log <BaiduMapFeatureDownloadResult>(threadlog); log.Count = threadlog.Total; new Log <BaiduMapFeatureDownloadResult>(log); Thread[] t = new Thread[Result.TaskCount]; for (int num = 0; num < Result.TaskCount; num++) { try { t[num] = new Thread(new ParameterizedThreadStart(run_BFeature)) { Name = "Thread " + num.ToString() }; t[num].Start(num); } catch (Exception ex) { threadlog.Status = "错误"; threadlog.ErrorMsg = ex.ToString(); threadlog.TStatus = 3; new Log <BaiduMapFeatureDownloadResult>(threadlog); log.Status = "错误"; log.ErrorMsg = ex.ToString(); log.ErrorDate = DateTime.Now.ToString(); //操作日志 new Log <BaiduMapFeatureDownloadResult>(log); return(new WebApiResult <string>() { success = 0, msg = ex.ToString() }); } } countdown.Wait(); oLayer.Dispose(); oDS.Dispose(); for (int num = 0; num < Result.TaskCount; num++) { t[num].Abort(); } lock (obj) { if (!Log <BaiduMapFeatureDownloadResult> .GetThreadLogEntity(this.Result_BFeature.GUID).IsPaused) { //配置文件参数信息更新 xmlDoc["MapFeature"]["bmap"]["dict_index"].InnerText = "0"; xmlDoc.Save(MapFeatureConfig); log.Status = "已完成"; log.CompleteTime = DateTime.Now.ToString(); log.Current = log.Count; threadlog.Status = "已完成"; threadlog.TStatus = 2; threadlog.Current = threadlog.Total; threadlog.Current_loc = List2Str(current_loc); //操作日志 new Log <BaiduMapFeatureDownloadResult>(threadlog); new Log <BaiduMapFeatureDownloadResult>(log); return(new WebApiResult <string>() { success = 1, msg = "百度地图要素下载完成!" }); } } } else { return(new WebApiResult <string>() { success = 2, msg = "图层类型不符合" }); } return(null); }
public static bool ExportSelectedDatabaseToGML(Action <string, bool> aLog, string pOutputFilename) { // Get database, return if no database selected if (frmMain.dbx == null) { aLog("Please select a database first...", true); return(false); } // Setup driver OSGeo.OGR.Driver drv = Ogr.GetDriverByName("GML"); if (drv == null) { aLog("Could not load driver", true); return(false); } // Create fieldAttributes datasource DataSource ds = drv.CreateDataSource(pOutputFilename, null); if (ds == null) { aLog("Could not create datasource", true); return(false); } // Create fieldAttributes layer OSGeo.OGR.Layer l = ds.CreateLayer("AddressUnits", null, wkbGeometryType.wkbPoint, null); if (l == null) { aLog("Failed to create GML file: AddressUnits", true); return(false); } // Create fieldAttributes class to hold address unit data AddressUnit mAddressUnits = new AddressUnit(); // Add fields to shapefile foreach (System.Reflection.FieldInfo mFld in mAddressUnits.GetType().GetFields()) { var val = (DatFld)mFld.GetValue(mAddressUnits); var mNewField = new FieldDefn(mFld.Name, val.type); if (val.type == FieldType.OFTString) { mNewField.SetWidth(val.length); } if (Ogr.OGRERR_NONE != l.CreateField(mNewField, 1)) { aLog("Failed to add field: " + mFld.Name, true); } } int ctr = 0; double mX, mY; var mAdmAdrFeature = new AddressUnitFeature(frmMain.dbx); DataTable mTable = mAdmAdrFeature.GetTable(sqlStatements.selectAddressUnitsSQL); // Add features foreach (DataRow mRow in mTable.Rows) { if (Double.TryParse(mRow["loc_x"].ToString(), out mX) && Double.TryParse(mRow["loc_y"].ToString(), out mY)) { var mFeature = new OSGeo.OGR.Feature(l.GetLayerDefn()); var mPoint = new OSGeo.OGR.Geometry(wkbGeometryType.wkbPoint); mPoint.SetPoint(0, mX, mY, 0); mFeature.SetFID(ctr); mFeature.SetGeometry(mPoint); mFeature.SetField("ADDRESSUNITID", int.Parse(mRow["id"].ToString())); mFeature.SetField("ROADID", int.Parse(mRow["road_id"].ToString())); mFeature.SetField("ADDRESSUNITNR", int.Parse(mRow["addressUnitNumber"].ToString())); mFeature.SetField("ROADNAME_EN", Utilities.GetANSI(mRow["NAMEENGLISH"].ToString())); mFeature.SetField("ROADNAME_AR", Utilities.GetANSI(mRow["NAMEARABIC"].ToString())); mFeature.SetField("DISTRICT_EN", Utilities.GetANSI(mRow["DISTRICT_EN"].ToString())); mFeature.SetField("DISTRICT_AR", Utilities.GetANSI(mRow["DISTRICT_AR"].ToString())); mFeature.SetField("MUNICIPALITY_EN", Utilities.GetANSI(Utilities.LABEL_ABUDHABI_EN)); mFeature.SetField("MUNICIPALITY_AR", Utilities.GetANSI(Utilities.LABEL_ABUDHABI_AR)); mFeature.SetField("QR_CODE", Utilities.GetANSI(mAdmAdrFeature.GetQRCode(mRow, mTable))); l.CreateFeature(mFeature); } else { Utilities.LogDebug("Error"); } ctr++; } l.Dispose(); ds.Dispose(); drv.Dispose(); return(true); }
/// <summary> /// 创建树木位置 /// </summary> public List <Tree> createTreePosition(DEMOperate dem, int i) { Console.WriteLine("Create trees of feature " + i); if (oLayer == null) { return(null); } string forestType = "人工林"; string distributeType = ""; double density = 0; double standArea = 0; double treeNum = 0; double D = 0, Dg = 0; List <Tree> trees = new List <Tree>(); Feature oFeature = oLayer.GetFeature(i); // 获得森林类型 for (int iField = 0; iField < m_FeildList.Count; iField++) { if (m_FeildList[iField].ToUpper() == "F_QIYUAN" || m_FeildList[iField].ToUpper() == "TYPE" || m_FeildList[iField].ToUpper() == "FOREST_TYPE" || m_FeildList[iField].ToUpper() == "STAND_TYPE") { forestType = GetFeildContent(iField, oFeature); } if (m_FeildList[iField].ToUpper() == "F_DWZS" || m_FeildList[iField].ToUpper() == "DENSITY" || m_FeildList[iField].ToUpper() == "FOREST_DENSITY" || m_FeildList[iField].ToUpper() == "STAND_DENSITY") { density = Convert.ToDouble(GetFeildContent(iField, oFeature)); } if (m_FeildList[iField].ToUpper() == "DISTRIBUTE" || m_FeildList[iField].ToUpper() == "F_FBLX") { distributeType = GetFeildContent(iField, oFeature); } if (m_FeildList[iField].ToUpper() == "MEAN_DBH")//算数平均胸径 { D = Convert.ToDouble(GetFeildContent(iField, oFeature)); } if (m_FeildList[iField].ToUpper() == "QUADRATIC_MEAN_DBH" || m_FeildList[iField].ToUpper() == "Q_MEAN_DBH")//平均胸径(二次平均胸径) { Dg = Convert.ToDouble(GetFeildContent(iField, oFeature)); } if (m_FeildList[iField].ToUpper() == "F_ZHUSHU" || m_FeildList[iField].ToUpper() == "TREE_NUMBER" || m_FeildList[iField].ToUpper() == "TREENUMBER")//林木数量 { treeNum = Convert.ToDouble(GetFeildContent(iField, oFeature)); } } if (density == 0) { if (treeNum != 0) { standArea = oFeature.GetGeometryRef().GetArea(); density = treeNum / standArea / 10000; } else { Console.WriteLine("DATA ERROR: The Stand density is lacked."); return(null); } } // 人工林 if (forestType == "人工林" || forestType == "Plantation") { Geometry geom = oFeature.GetGeometryRef(); Envelope env = new Envelope(); geom.GetEnvelope(env); //分布范围 double xMax, xMin, yMax, yMin, xCen, yCen; xMax = env.MaxX; xMin = env.MinX; yMax = env.MaxY; yMin = env.MinY; xCen = (xMax + xMin) / 2; yCen = (yMax + yMin) / 2; //将值放入泛型当中位置坐标 List <double> tempX = new List <double>(); List <double> tempY = new List <double>(); double sideLength = Math.Sqrt(density / 10000 * ((xMax - xMin) * (yMax - yMin)));//边长 double offsetX = (xMax - xMin) / sideLength; double offsetY = (yMax - yMin) / sideLength; double diagonal = Math.Sqrt((xMax - xMin) * (xMax - xMin) + (yMax - yMin) * (yMax - yMin)); //对角线 double xAdd = (diagonal - (xMax - xMin)) / 2; double yAdd = (diagonal - (yMax - yMin)) / 2; Random rand = new Random(); //菱形均匀分布 if (distributeType.Contains("Diamond") || distributeType.Contains("Interlaced")) { Console.WriteLine("Diamond distribution"); int row = 0; for (double j = xMin - xAdd; j < xMax + xAdd; j += offsetX) { if (row % 2 == 0) { for (double k = yMin - yAdd; k < yMax + yAdd; k += offsetY) { tempX.Add(j + rand.Next(10) / 10.0 * offsetX / 4); tempY.Add(k + rand.Next(10) / 10.0 * offsetY / 4); } } else { for (double k = yMin - yAdd + offsetY / 2; k < yMax + yAdd; k += offsetY) { tempX.Add(j + rand.Next(10) / 10.0 * offsetX / 4); tempY.Add(k + rand.Next(10) / 10.0 * offsetY / 4); } } row++; } } // 环形均匀分布 else if (distributeType.Contains("Circular")) { Console.WriteLine("Circular distribution"); //对角线做直径,计算面积,计算株数,计算环数,计算环距,计算极坐标,计算xy double r = diagonal / 2; double A = Math.PI * r * r; double N = density / 10000 * A; int roundNum = (int)((Math.Sqrt(1 + 4.0 / 3 * N) - 1) / 2); double roundDistance = Math.Sqrt(A / Math.PI) / roundNum; for (int j = 0; j < roundNum; j++) { double radius = j * roundDistance; //极矩 for (int k = 0; k < 6 * j; k++) { double angle = k * 2 * Math.PI / 6 / j; //极径 tempX.Add(radius * Math.Cos(angle) + rand.Next(10) / 10.0 * roundDistance / 4 + xCen + rand.Next(10) / 10.0 * roundDistance / 4); tempY.Add(radius * Math.Sin(angle) + rand.Next(10) / 10.0 * roundDistance / 4 + yCen + rand.Next(10) / 10.0 * roundDistance / 4); } } } // 井型均匀分布 else if (distributeType.Contains("Rectangular")) { Console.WriteLine("Rectangular distribution"); for (double j = xMin - xAdd; j < xMax + xAdd; j += offsetX) { for (double k = yMin - yAdd; k < yMax + yAdd; k += offsetY) { tempX.Add(j + rand.Next(10) / 10.0 * offsetX / 4); tempY.Add(k + rand.Next(10) / 10.0 * offsetY / 4); } } } else { Console.WriteLine("Rectangular distribution (default)"); // 默认井型 for (double j = xMin - xAdd; j < xMax + xAdd; j += offsetX) { for (double k = yMin - yAdd; k < yMax + yAdd; k += offsetY) { tempX.Add(j + rand.Next(10) / 10.0 * offsetX / 4); tempY.Add(k + rand.Next(10) / 10.0 * offsetY / 4); } } } //计算林分坡度 dem.getColRow(xCen, yCen); double aspect = dem.CalcuAspect(); //坐标系转换,林木沿山坡分布 for (int j = 0; j < tempX.Count; j++) { double x = (tempX[j] - xCen) * Math.Cos(aspect) + (tempY[j] - yCen) * Math.Sin(aspect); double y = (tempY[j] - yCen) * Math.Cos(aspect) - (tempX[j] - xCen) * Math.Sin(aspect); tempX[j] = x + xCen; tempY[j] = y + yCen; } //用此Driver创建Shape文件 //创建DataSource string temppath = "temp" + i + ".shp"; DataSource pDataSource = oDriver.CreateDataSource(temppath, null); if (pDataSource == null) { Console.WriteLine("DataSource Creation Error"); } //创建层Layer string outname = "point_out" + i; Layer tempLayer = pDataSource.CreateLayer(outname, null, wkbGeometryType.wkbPoint, null); if (tempLayer == null) { Console.WriteLine("Layer Creation Failed"); } //创建属性 FieldDefn oField1 = new FieldDefn("TREE_ID", FieldType.OFTInteger); oField1.SetWidth(16); tempLayer.CreateField(oField1, 1); //创建一个Feature Feature mFeature = new Feature(tempLayer.GetLayerDefn()); // 创建点 Geometry mPoint = new Geometry(wkbGeometryType.wkbPoint); for (int j = 0; j < tempX.Count; j++) { //树木编号 mFeature.SetField(0, j); //添加坐标点 mPoint.AddPoint(tempX[j], tempY[j], 0); mFeature.SetGeometry(mPoint); //将带有坐标及属性的Feature要素点写入Layer中 tempLayer.CreateFeature(mFeature); } //关闭文件读写 mFeature.Dispose(); mPoint.Dispose(); //创建裁切Layer string clipLyrname = "ClipLayer" + i; Layer clipLayer = pDataSource.CreateLayer(clipLyrname, null, wkbGeometryType.wkbPolygon, null); clipLayer.CreateFeature(oFeature); //裁剪 string treePosition = "treePosition" + i; Layer result = pDataSource.CreateLayer(treePosition, null, wkbGeometryType.wkbPoint, null); tempLayer.Clip(clipLayer, result, new string[] { "SKIP_FAILURES=YES" }, null, null); // 删除临时temp.shp tempLayer.Dispose(); pDataSource.DeleteLayer(0); //以下读取数据并对trees赋值 int rFeatureCount = (int)result.GetFeatureCount(0); Feature rFeature = null; for (int k = 0; k < rFeatureCount; k++) { Tree tree = new Tree(); tree.ForestID = i; //标注所属树林 tree.ID = k; //树木编号 rFeature = result.GetFeature(k); Geometry geometry = rFeature.GetGeometryRef(); tree.X = geometry.GetX(0); tree.Y = geometry.GetY(0); trees.Add(tree);//加入trees } Console.WriteLine("Get trees' locations"); //求算WVA,WVA表示采用加权Voronoi图得出每株数的多边形面积 List <double> boundX = new List <double>(); List <double> boundY = new List <double>(); boundX.Add(xMin - offsetX); boundX.Add(xMin - offsetX); boundX.Add(xMax + offsetX); boundX.Add(xMax + offsetX); boundY.Add(yMin - offsetY); boundY.Add(yMax + offsetY); boundY.Add(yMax + offsetY); boundY.Add(yMin - offsetY); Geometry oGeometry = new Geometry(wkbGeometryType.wkbPolygon); List <double> treeX = new List <double>(); List <double> treeY = new List <double>(); List <double> Area = new List <double>(); for (int t = 0; t < trees.Count; t++) { //只在本树林范围计算WVA,此时tree_count为除本树林已加入trees的棵数 treeX.Add(trees[t].X); treeY.Add(trees[t].Y); Area.Add(0); //初始化 } int t_num = trees.Count; //此树林树木棵数 double[] treex = treeX.ToArray(); double[] treey = treeY.ToArray(); double[] boundx = boundX.ToArray(); double[] boundy = boundY.ToArray(); double[] area = Area.ToArray(); CreateThiessen(treex, treey, t_num, boundx, boundy, 4, area); for (int t = 0; t < trees.Count; t++) { trees[t].WVA = area[t]; } //分配胸径 WeibullDistribute(trees, trees.Count, D, Dg); // 删除临时 clipLayer.Dispose(); result.Dispose(); pDataSource.DeleteLayer(0); pDataSource.DeleteLayer(0); } return(trees); }
//----------------------------------------------------------------------------------- public void readPoint(ref Layer oLayer) { // 对图层进行初始化,如果对图层进行了过滤操作,执行这句后,之前的过滤全部清空 oLayer.ResetReading(); Driver oDriver = null; DataSource oDS = null; Layer newLayer = null; initShp(ref oLayer, ref oDriver, ref oDS, ref newLayer, LAYER_TYPE.POINT); // 获取图层中的属性表表头并输出 string strInfo = "属性表结构信息:\n"; FeatureDefn oDefn = oLayer.GetLayerDefn(); int iFieldCount = oDefn.GetFieldCount(); for (int iAttr = 0; iAttr < iFieldCount; iAttr++) { FieldDefn oField = oDefn.GetFieldDefn(iAttr); FieldType type = oField.GetFieldType(); string fieldName = oField.GetName(); //为新图层创建属性 if (!fieldName.Equals("X坐标") && !fieldName.Equals("Y坐标")) { FieldDefn newField = new FieldDefn(fieldName, type); if (type == FieldType.OFTString) { newField.SetWidth(oField.GetWidth()); } newLayer.CreateField(newField, 1); } //获取图层属性信息 strInfo += string.Format("{0}:{1} ({2}.{3})\n", oField.GetNameRef(), oField.GetFieldTypeName(oField.GetFieldType()), oField.GetWidth(), oField.GetPrecision()); } FeatureDefn newDefn = newLayer.GetLayerDefn(); // 输出图层中的要素个数 strInfo += string.Format("要素个数 = {0}\n", oLayer.GetFeatureCount(0)); Feature oFeature = null; // 下面开始遍历图层中的要素 while ((oFeature = oLayer.GetNextFeature()) != null) { strInfo += string.Format("\n当前处理第{0}个: \n属性值:", oFeature.GetFID()); //为新图层创建要素 Feature oFeaturePoint = new Feature(newDefn); double pointX = 0.0; double pointY = 0.0; // 获取要素中的属性表内容 for (int iField = 0; iField < iFieldCount; iField++) { FieldDefn oFieldDefn = oDefn.GetFieldDefn(iField); FieldType type = oFieldDefn.GetFieldType(); string name = oFieldDefn.GetNameRef(); switch (type) { case FieldType.OFTString: IntPtr pchar = OGR_F_GetFieldAsString(Feature.getCPtr(oFeature), iField); string val = Marshal.PtrToStringAnsi(pchar); oFeaturePoint.SetField(name, val); break; case FieldType.OFTReal: if (!name.Equals("X坐标") && !name.Equals("Y坐标")) { oFeaturePoint.SetField(name, oFeature.GetFieldAsDouble(iField)); } switch (name) { case "X": pointX = oFeature.GetFieldAsDouble(iField); break; case "Y": pointY = oFeature.GetFieldAsDouble(iField); break; default: break; } break; case FieldType.OFTInteger: oFeaturePoint.SetField(iField, oFeature.GetFieldAsInteger(iField)); break; default: oFeaturePoint.SetField(iField, oFeature.GetFieldAsString(iField)); break; } } //填充要素几何信息 Geometry oGeometry = Geometry.CreateFromWkt(string.Format("POINT({0} {1})", pointX, pointY)); oFeaturePoint.SetGeometry(oGeometry); newLayer.CreateFeature(oFeaturePoint); } strInfo += "\n数据集关闭!"; oDS.Dispose(); }
public static void Write(string dataSourceName, string layerName) { try { Ogr.RegisterAll(); string driverName = "ESRI Shapefile"; Driver driver = Ogr.GetDriverByName(driverName); if (System.IO.File.Exists(dataSourceName)) { //System.IO.File.Delete(dataSourceName);// only remove xxx.shp driver.DeleteDataSource(dataSourceName);// reomve xxx.shp dbf shx } DataSource ds = driver.CreateDataSource(dataSourceName, new string[] { }); Layer layer; int i; for (i = 0; i < ds.GetLayerCount(); i++) { layer = ds.GetLayerByIndex(i); if (layer != null && layer.GetLayerDefn().GetName() == layerName) { MessageBox.Show("Layer already existed. Recreating it.\n"); ds.DeleteLayer(i); break; } } layer = ds.CreateLayer(layerName, null, wkbGeometryType.wkbPoint, new string[] { }); // create three files xxx.shp xxx.dbf xxx.shx // add layer attribute field (fieldName at most 10 chars) // StringField --->StringFiel // IntField--->IntField // DoubleField--->DoubleFiel // DateField--->DateField FieldDefn fdef = new FieldDefn("StringField", FieldType.OFTString); fdef.SetWidth(32); layer.CreateField(fdef, 1); fdef = new FieldDefn("IntField", FieldType.OFTInteger); layer.CreateField(fdef, 1); fdef = new FieldDefn("DoubleField", FieldType.OFTReal); layer.CreateField(fdef, 1); fdef = new FieldDefn("DateField", FieldType.OFTDate); layer.CreateField(fdef, 1); // add feature 1 Feature f = new Feature(layer.GetLayerDefn()); // attribute value f.SetField(0, "pkuHelloGIS"); f.SetField(1, (int)99); f.SetField(2, (float)3.14); f.SetField(3, 2012, 10, 17, 18, 24, 30, 0); // geometry value Geometry g = Geometry.CreateFromWkt("POINT(100 200)"); f.SetGeometry(g); layer.CreateFeature(f); f.Dispose(); // add feature 2 Feature f2 = new Feature(layer.GetLayerDefn()); // attribute value f2.SetField(0, "kezunlin"); f2.SetField(1, (int)100); f2.SetField(2, (float)100.0); f2.SetField(3, 2007, 3, 15, 18, 24, 30, 0); // geometry value Geometry g2 = Geometry.CreateFromWkt("POINT(100 100)"); f2.SetGeometry(g2); layer.CreateFeature(f2); // flush data to file f2.Dispose(); layer.Dispose(); ds.Dispose(); driver.Dispose(); MessageBox.Show("CreateShapefile Successfully."); } catch (System.Exception ex) { MessageBox.Show(ex.ToString()); } }
public void readLine(ref Layer oLayer, string pointTableName) { // 对图层进行初始化,如果对图层进行了过滤操作,执行这句后,之前的过滤全部清空 oLayer.ResetReading(); //打开数据 DataSource newDs = Ogr.Open(mSrcFile, 0); if (newDs == null) { Console.WriteLine(string.Format("打开文件【{0}】失败!\n", mSrcFile)); return; } //根据图层名称获取相应的图层 Layer matchLayer = newDs.GetLayerByName(pointTableName); Driver oDriver = null; DataSource oDS = null; Layer newLayer = null; initShp(ref oLayer, ref oDriver, ref oDS, ref newLayer, LAYER_TYPE.LINE); // 获取图层中的属性表表头并输出 string strInfo = "属性表结构信息:\n"; FeatureDefn oDefn = oLayer.GetLayerDefn(); int iFieldCount = oDefn.GetFieldCount(); for (int iAttr = 0; iAttr < iFieldCount; iAttr++) { FieldDefn oField = oDefn.GetFieldDefn(iAttr); FieldType type = oField.GetFieldType(); //为新图层创建属性 FieldDefn newField = new FieldDefn(oField.GetNameRef(), type); if (type == FieldType.OFTString) { newField.SetWidth(oField.GetWidth()); } newLayer.CreateField(newField, 1); strInfo += string.Format("{0}:{1} ({2}.{3})\n", oField.GetNameRef(), oField.GetFieldTypeName(oField.GetFieldType()), oField.GetWidth(), oField.GetPrecision()); } FeatureDefn newDefn = newLayer.GetLayerDefn(); // 输出图层中的要素个数 strInfo += string.Format("要素个数 = {0}\n", oLayer.GetFeatureCount(0)); Feature oFeature = null; // 下面开始遍历图层中的要素 double S_X = 0.0; double S_Y = 0.0; double E_X = 0.0; double E_Y = 0.0; while ((oFeature = oLayer.GetNextFeature()) != null) { strInfo += string.Format("\n当前处理第{0}个: \n属性值:", oFeature.GetFID()); //为新图层创建要素 Feature oFeatureLineString = new Feature(newDefn); string sql = string.Empty; // 获取要素中的属性表内容 for (int iField = 0; iField < iFieldCount; iField++) { FieldDefn oFieldDefn = oDefn.GetFieldDefn(iField); string name = oFieldDefn.GetNameRef(); FieldType type = oFieldDefn.GetFieldType(); switch (type) { case FieldType.OFTString: IntPtr pchar = OGR_F_GetFieldAsString(Feature.getCPtr(oFeature), iField); string val = Marshal.PtrToStringAnsi(pchar); oFeatureLineString.SetField(iField, val); switch (name) { case "S_Point": sql = oFeature.GetFieldAsString(iField); getCoordinate(ref matchLayer, ref sql, ref S_X, ref S_Y); break; case "E_Point": sql = oFeature.GetFieldAsString(iField); getCoordinate(ref matchLayer, ref sql, ref E_X, ref E_Y); break; default: break; } break; case FieldType.OFTReal: oFeatureLineString.SetField(name, oFeature.GetFieldAsDouble(iField)); break; case FieldType.OFTInteger: oFeatureLineString.SetField(iField, oFeature.GetFieldAsInteger(iField)); break; default: oFeatureLineString.SetField(iField, oFeature.GetFieldAsString(iField)); break; } } Geometry oGeometry = Geometry.CreateFromWkt(string.Format("LINESTRING({0} {1},{2} {3})", S_X, S_Y, E_X, E_Y)); oFeatureLineString.SetGeometryDirectly(oGeometry); newLayer.CreateFeature(oFeatureLineString); oGeometry.Dispose(); } strInfo += "\n数据集关闭!"; oDS.Dispose(); }
private void button1_Click(object sender, EventArgs e) { OSGeo.GDAL.Gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES"); // 为了使属性表字段支持中文,请添加下面这句 OSGeo.GDAL.Gdal.SetConfigOption("SHAPE_ENCODING", ""); Ogr.RegisterAll(); string strVectorFile = "H:\\GDAL\\po.shp"; //创建数据,这里以创建ESRI的shp文件为例 string strDriverName = "ESRI Shapefile"; int count = Ogr.GetDriverCount(); Driver oDriver = Ogr.GetDriverByName(strDriverName); if (oDriver == null) { Console.WriteLine("%s 驱动不可用!\n", strVectorFile); return; } // 创建数据源 DataSource oDS = oDriver.CreateDataSource(strVectorFile, null); if (oDS == null) { Console.WriteLine("创建矢量文件【%s】失败!\n", strVectorFile); return; } oLayer = oDS.CreateLayer("TestPolygon", null, wkbGeometryType.wkbPoint, null); if (oLayer == null) { Console.WriteLine("图层创建失败!\n"); return; } // 下面创建属性表 // 先创建一个叫FieldID的整型属性 for (int i = 0; i < listView1.Items.Count; i++) { FieldDefn oFieldI = new FieldDefn(listView1.Items[i].SubItems[0].Text, FieldType.OFTInteger); oFieldI.SetWidth(Convert.ToInt32(listView1.Items[i].SubItems[1].Text)); oLayer.CreateField(oFieldI, 1); } // FieldDefn oFieldID = new FieldDefn(textBox1.Text, FieldType.OFTInteger); // oFieldID.SetWidth(Convert.ToInt32(textBox2.Text)); // oLayer.CreateField(oFieldID, 1); //FieldDefn oFieldName = new FieldDefn("FieldName", FieldType.OFTString); // oFieldName.SetWidth(20); // oLayer.CreateField(oFieldName, 0); Feature poFeature = new Feature(oLayer.GetLayerDefn()); Geometry pt = new Geometry(OSGeo.OGR.wkbGeometryType.wkbPoint); for (int i = 100; i < 110; i++) { //属性一"名称"赋值 poFeature.SetField(0, i); //属性二"高度"赋值 poFeature.SetField(1, i); //添加坐标点 pt.AddPoint(i, i, i); poFeature.SetGeometry(pt); //将带有坐标及属性的Feature要素点写入Layer中 oLayer.CreateFeature(poFeature); } //poFeature.SetGeometry(pt); //oLayer.CreateFeature(poFeature); //关闭文件读写 poFeature.Dispose(); oDS.Dispose(); string information = OGRReadFile.GetVectorInfo(strVectorFile); MessageBox.Show(information); // string sShpFileName = @"H:\GDAL\po.shp"; // Shpread a = new Shpread(); // a.GetShpLayer(sShpFileName); // a.InitinalGdal(); // a.GetFeilds(); // List<string> m_FeildList = new List<string>(); // m_FeildList.Clear(); //// wkbGeometryType oTempGeometryType = oLayer.GetGeomType(); // List<string> TempstringList = new List<string>(); // // // FeatureDefn oDefn = oLayer.GetLayerDefn(); // int iFieldCount = oDefn.GetFieldCount(); // for (int iAttr = 0; iAttr < iFieldCount; iAttr++) // { // FieldDefn oField = oDefn.GetFieldDefn(iAttr); // if (null != oField) // { // m_FeildList.Add(oField.GetNameRef()); // } // } }
//生成的线shp函数 public void lines() { double x = 0; double y = 0; int z = 0; string pszDriverName = "ESRI Shapefile"; OSGeo.OGR.Ogr.RegisterAll(); OSGeo.OGR.Driver poDriver = OSGeo.OGR.Ogr.GetDriverByName(pszDriverName); if (poDriver == null) { MessageBox.Show("Driver Error"); } OSGeo.GDAL.Gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES"); //用此Driver创建Shape文件//数据源 OSGeo.OGR.DataSource poDS; poDS = poDriver.CreateDataSource("D:\\SHP_TRY", null);//指定存储文件 if (poDS == null) { MessageBox.Show("DataSource Creation Error"); } // 创建图层 Layer oLayer = poDS.CreateLayer("lines", null, wkbGeometryType.wkbLineString, null);//图层名字为【CreateLayer(名字,类型,null)】 if (oLayer == null) { Console.WriteLine("图层创建失败!\n"); return; } // 下面创建属性表 // 先创建一个叫FieldID的整型属性 FieldDefn oFieldID = new FieldDefn("FieldID", FieldType.OFTInteger); oLayer.CreateField(oFieldID, 0); // 再创建一个叫FeatureName的字符型属性,字符长度为50 FieldDefn oFieldName = new FieldDefn("FieldName", FieldType.OFTString); oFieldName.SetWidth(100); oLayer.CreateField(oFieldName, 1); FeatureDefn oDefn = oLayer.GetLayerDefn(); // 创建要素 Feature oFeatureTriangle = new Feature(oDefn); OSGeo.OGR.Geometry pt = new OSGeo.OGR.Geometry(OSGeo.OGR.wkbGeometryType.wkbLineString); oFeatureTriangle.SetField(0, 1); oFeatureTriangle.SetField(1, "line_try");//线要素名字 //写入属性!!!!!!这里是根据基站的TXT的做的实验以后可以改数据,文件地址根据实际情况可以修改 string path = "C:\\Users\\Tianh\\Desktop\\station.txt"; string l; StreamReader sr = new StreamReader(path, Encoding.Default); while ((l = sr.ReadLine()) != null) { string[] strArr = sr.ReadLine().Split('\t'); x = Convert.ToDouble(strArr[2]); //经度 y = Convert.ToDouble(strArr[1]); //纬度 pt.AddPoint(x, y, z); } oFeatureTriangle.SetGeometry(pt); oLayer.CreateFeature(oFeatureTriangle); oFeatureTriangle.Dispose(); poDS.Dispose(); MessageBox.Show("生成文件在:D:\\SHP_TRY!"); }
private void WriteVectorFile(string strVectorFile) { SharpMap.GdalConfiguration.ConfigureGdal(); SharpMap.GdalConfiguration.ConfigureOgr(); // 为了支持中文路径,请添加下面这句代码 OSGeo.GDAL.Gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "NO"); // 为了使属性表字段支持中文,请添加下面这句 OSGeo.GDAL.Gdal.SetConfigOption("SHAPE_ENCODING", ""); Ogr.RegisterAll(); string strDriverName = "ESRI Shapefile"; Driver oDriver = Ogr.GetDriverByName(strDriverName); if (oDriver == null) { MessageBox.Show("%s 驱动不可用!!\n", strVectorFile); return; } DataSource oDS = oDriver.CreateDataSource(strVectorFile, null); if (oDS == null) { MessageBox.Show("创建矢量文件【%s】失败!\n", strVectorFile); return; } Layer oLayer = oDS.CreateLayer("TestPolygon", null, wkbGeometryType.wkbPolygon, null); if (oLayer == null) { MessageBox.Show("图层创建失败!\n"); return; } //FID FieldDefn oFieldID = new FieldDefn("FID", FieldType.OFTInteger); oLayer.CreateField(oFieldID, 1); //批次 FieldDefn oPCMC = new FieldDefn("PCMC", FieldType.OFTString); oPCMC.SetWidth(100); oLayer.CreateField(oPCMC, 1); //地块号 FieldDefn oDKH = new FieldDefn("DKH", FieldType.OFTString); oDKH.SetWidth(100); oLayer.CreateField(oDKH, 1); //日期 FieldDefn oDate = new FieldDefn("Date", FieldType.OFTString); oDate.SetWidth(10); oLayer.CreateField(oDate, 1); //用地类型 FieldDefn oType = new FieldDefn("Type", FieldType.OFTString); oType.SetWidth(10); oLayer.CreateField(oType, 1); FeatureDefn oDefn = oLayer.GetLayerDefn(); int index = 0; foreach (Data data in DataList) { index++; Feature oFeature = new Feature(oDefn); oFeature.SetField(0, index); oFeature.SetField(1, data.PCMC); oFeature.SetField(2, data.Dkh); oFeature.SetField(3, data.Date); oFeature.SetField(4, data.Type); Geometry geomTriangle = Geometry.CreateFromWkt(GetGeometry(data)); oFeature.SetGeometry(geomTriangle); oLayer.CreateFeature(oFeature); } oDS.Dispose(); MessageBox.Show("生成完毕"); }
static void Main(string[] args) { var e = Encoding.Default; Gdal.AllRegister(); Ogr.RegisterAll(); //Gdal.SetConfigOption("GDAL_DATA", Gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES"); Gdal.SetConfigOption("SHAPE_ENCODING", ""); // 读 //const string shpFile = @"C:\Users\x\Documents\ArcGIS\镶嵌线.shp"; //var s = Ogr.Open(shpFile, 0); //var lr = s.GetLayerByIndex(0); //var fieldName = Encoding.GetEncoding("gb2312"). // GetString(Encoding.UTF8.GetBytes("景号")); //var index = lr.FindFieldIndex(fieldName, 1); //Console.WriteLine(index); //s.Dispose(); // 创建 const string createdShpFile = @"C:\Users\x\Documents\ArcGIS\黑白像素.shp"; const string tifFile = @"C:\Users\x\Documents\ArcGIS\dem.tif"; var tifDs = Gdal.Open(tifFile, Access.GA_ReadOnly); // 参数为小数,传入0.5取得像素中心点坐标 var ul = GDALInfoGetPosition(tifDs, 0.0, 0.0); Console.WriteLine(" Upper Left (" + ul.Item1 + "," + ul.Item2 + ")"); // 创建 shp var projection = tifDs.GetProjectionRef(); var srs = new SpatialReference(null); if (projection != null) { if (srs.ImportFromWkt(ref projection) == 0) { string wkt; srs.ExportToPrettyWkt(out wkt, 0); Console.WriteLine("Coordinate System is:"); Console.WriteLine(wkt); } else { Console.WriteLine("Coordinate System is:"); Console.WriteLine(projection); } } var drv = Ogr.GetDriverByName("ESRI Shapefile"); var ds = drv.CreateDataSource(createdShpFile, new string[] { }); var layer = ds.CreateLayer("黑白像素", srs, wkbGeometryType.wkbPolygon, new string[] { }); FieldDefn fdefn = new FieldDefn("中文字段", FieldType.OFTString); fdefn.SetWidth(128); if (layer.CreateField(fdefn, 1) != 0) { Console.WriteLine("Creating Name field failed."); } layer.Dispose(); tifDs.Dispose(); //const string mdbPath = @"C:\Users\x\Documents\ArcGIS\个人一.mdb"; //var mdb = Ogr.Open(mdbPath, 0); //var lr2 = mdb.GetLayerByName("面"); //var j = lr2.FindFieldIndex("描述", 1); //Feature f; //while ((f = lr2.GetNextFeature()) != null) //{ // 修改 // f.geo.Clone().TransformTo(sp); // lyr.SetFeature(f); // var value = f.GetFieldAsString(j); // Console.WriteLine(value); //} }
//生成面shp函数 public void surface() { string pszDriverName = "ESRI Shapefile"; OSGeo.OGR.Ogr.RegisterAll(); OSGeo.OGR.Driver poDriver = OSGeo.OGR.Ogr.GetDriverByName(pszDriverName); if (poDriver == null) { MessageBox.Show("Driver Error"); } OSGeo.GDAL.Gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES"); //用此Driver创建Shape文件//数据源 OSGeo.OGR.DataSource poDS; poDS = poDriver.CreateDataSource("D:\\SHP_TRY", null); if (poDS == null) { MessageBox.Show("DataSource Creation Error"); } // 创建图层,创建一个多边形图层,这里没有指定空间参考,如果需要的话,需要在这里进行指定 Layer oLayer = poDS.CreateLayer("TestPolygon", null, wkbGeometryType.wkbPolygon, null); if (oLayer == null) { MessageBox.Show("图层创建失败!\n"); return; } // 下面创建属性表 // 先创建一个叫FieldID的整型属性 FieldDefn oFieldID = new FieldDefn("FieldID", FieldType.OFTInteger); oLayer.CreateField(oFieldID, 1); // 再创建一个叫FeatureName的字符型属性,字符长度为50 FieldDefn oFieldName = new FieldDefn("FieldName", FieldType.OFTString); oFieldName.SetWidth(100); oLayer.CreateField(oFieldName, 1); FeatureDefn oDefn = oLayer.GetLayerDefn(); // 创建几何图形要素 string CS = ""; string zc = ""; string zj = ""; string start_PT = ""; double x; double y; Feature oFeatureRectangle = new Feature(oDefn); oFeatureRectangle.SetField(0, 1); oFeatureRectangle.SetField(1, "surface"); for (int i = 0; i < 5; i++) { x = i * i; //X,Y是假设的数据,以后可以更加实际坐标点进行填充 y = i + 4; zc = x + " " + y; if (i == 0) { start_PT = zc; //记录第一个坐标 } zj = zj + zc + ","; //坐标之间用“,”隔开 } zj = zj + start_PT; //形成闭合的环 //在POLYGON中添加坐标 CS = "POLYGON ((" + zj + "))"; Geometry geomRectangle = Geometry.CreateFromWkt(CS); oFeatureRectangle.SetGeometry(geomRectangle); oLayer.CreateFeature(oFeatureRectangle); oFeatureRectangle.Dispose(); poDS.Dispose(); MessageBox.Show("生成文件在:D:\\SHP_TRY!"); }
/// <summary> /// 输出shapefile 文件 /// </summary> /// <param name="trees"></param> /// <param name="path"></param> public void Createshp(List <Tree> trees, string path) { DataSource outds = oDriver.CreateDataSource(path, null); if (outds == null) { Console.WriteLine("创建矢量文件失败!"); return; } SpatialReference sr = oLayer.GetSpatialRef(); if (sr == null) { string wkt = ""; sr = new SpatialReference(wkt); } Layer outLayer = outds.CreateLayer("PointLayer", sr, wkbGeometryType.wkbPoint, null); //create fields FieldDefn oFieldID = new FieldDefn("ID", FieldType.OFTInteger); outLayer.CreateField(oFieldID, 1); FieldDefn oFieldX = new FieldDefn("X", FieldType.OFTReal);// float型 oFieldX.SetWidth(18); oFieldX.SetPrecision(8); outLayer.CreateField(oFieldX, 1); FieldDefn oFieldY = new FieldDefn("Y", FieldType.OFTReal); oFieldY.SetWidth(18); oFieldY.SetPrecision(8); outLayer.CreateField(oFieldY, 1); FieldDefn oDBH = new FieldDefn("DBH", FieldType.OFTReal); oDBH.SetWidth(18); oDBH.SetPrecision(8); outLayer.CreateField(oDBH, 1); FieldDefn oHeight = new FieldDefn("Height", FieldType.OFTReal); oHeight.SetWidth(18); oHeight.SetPrecision(8); outLayer.CreateField(oHeight, 1); FieldDefn oUBH = new FieldDefn("UBH", FieldType.OFTReal); oUBH.SetWidth(18); oUBH.SetPrecision(8); outLayer.CreateField(oUBH, 1); FieldDefn oCH = new FieldDefn("CH", FieldType.OFTReal); oCH.SetWidth(18); oCH.SetPrecision(8); outLayer.CreateField(oCH, 1); FieldDefn oCW = new FieldDefn("CW", FieldType.OFTReal); oCW.SetWidth(18); oCW.SetPrecision(8); outLayer.CreateField(oCW, 1); FieldDefn eUBH = new FieldDefn("eUBH", FieldType.OFTReal); eUBH.SetWidth(18); eUBH.SetPrecision(8); outLayer.CreateField(eUBH, 1); FieldDefn sUBH = new FieldDefn("sUBH", FieldType.OFTReal); sUBH.SetWidth(18); sUBH.SetPrecision(8); outLayer.CreateField(sUBH, 1); FieldDefn wUBH = new FieldDefn("wUBH", FieldType.OFTReal); wUBH.SetWidth(18); wUBH.SetPrecision(8); outLayer.CreateField(wUBH, 1); FieldDefn nUBH = new FieldDefn("nUBH", FieldType.OFTReal); nUBH.SetWidth(18); nUBH.SetPrecision(8); outLayer.CreateField(nUBH, 1); FieldDefn eCH = new FieldDefn("eCH", FieldType.OFTReal); eCH.SetWidth(18); eCH.SetPrecision(8); outLayer.CreateField(eCH, 1); FieldDefn sCH = new FieldDefn("sCH", FieldType.OFTReal); sCH.SetWidth(18); sCH.SetPrecision(8); outLayer.CreateField(sCH, 1); FieldDefn wCH = new FieldDefn("wCH", FieldType.OFTReal); wCH.SetWidth(18); wCH.SetPrecision(8); outLayer.CreateField(wCH, 1); FieldDefn nCH = new FieldDefn("nCH", FieldType.OFTReal); nCH.SetWidth(18); nCH.SetPrecision(8); outLayer.CreateField(nCH, 1); FieldDefn eCW = new FieldDefn("eCW", FieldType.OFTReal); eCW.SetWidth(18); eCW.SetPrecision(8); outLayer.CreateField(eCW, 1); FieldDefn sCW = new FieldDefn("sCW", FieldType.OFTReal); sCW.SetWidth(18); sCW.SetPrecision(8); outLayer.CreateField(sCW, 1); FieldDefn wCW = new FieldDefn("wCW", FieldType.OFTReal); wCW.SetWidth(18); wCW.SetPrecision(8); outLayer.CreateField(wCW, 1); FieldDefn nCW = new FieldDefn("nCW", FieldType.OFTReal); nCW.SetWidth(18); nCW.SetPrecision(8); outLayer.CreateField(nCW, 1); FieldDefn oBiomass = new FieldDefn("Biomass", FieldType.OFTReal); oBiomass.SetWidth(18); oBiomass.SetPrecision(8); outLayer.CreateField(oBiomass, 1); FieldDefn oMortality = new FieldDefn("Mortality", FieldType.OFTString); oMortality.SetWidth(50); outLayer.CreateField(oMortality, 1); FieldDefn oCutting = new FieldDefn("Cutting", FieldType.OFTString); oCutting.SetWidth(50); outLayer.CreateField(oCutting, 1); // create feature FeatureDefn oDefn = outLayer.GetLayerDefn(); for (int i = 0; i < trees.Count; i++) { Feature oFeature = new Feature(oDefn); oFeature.SetField(0, i); oFeature.SetField(1, double.Parse(trees[i].X.ToString("0.00"))); oFeature.SetField(2, double.Parse(trees[i].Y.ToString("0.00"))); oFeature.SetField(3, double.Parse(trees[i].DBH.ToString("0.00"))); oFeature.SetField(4, double.Parse(trees[i].Height.ToString("0.00"))); oFeature.SetField(5, double.Parse(trees[i].UnderBranchHeight.ToString("0.00"))); oFeature.SetField(6, double.Parse(trees[i].CrownHeight.ToString("0.00"))); oFeature.SetField(7, double.Parse(trees[i].CrownWidth.ToString("0.00"))); if (trees[i].eastUnderBranchHeight > 0) { oFeature.SetField(8, double.Parse(trees[i].eastUnderBranchHeight.ToString("0.00"))); oFeature.SetField(9, double.Parse(trees[i].southUnderBranchHeight.ToString("0.00"))); oFeature.SetField(10, double.Parse(trees[i].westUnderBranchHeight.ToString("0.00"))); oFeature.SetField(11, double.Parse(trees[i].northUnderBranchHeight.ToString("0.00"))); } if (trees[i].eastCrownHeight > 0) { oFeature.SetField(12, double.Parse(trees[i].eastCrownHeight.ToString("0.00"))); oFeature.SetField(13, double.Parse(trees[i].southCrownHeight.ToString("0.00"))); oFeature.SetField(14, double.Parse(trees[i].westCrownHeight.ToString("0.00"))); oFeature.SetField(15, double.Parse(trees[i].northCrownHeight.ToString("0.00"))); } if (trees[i].eastCrownWidth > 0) { oFeature.SetField(16, double.Parse(trees[i].eastCrownWidth.ToString("0.00"))); oFeature.SetField(17, double.Parse(trees[i].southCrownWidth.ToString("0.00"))); oFeature.SetField(18, double.Parse(trees[i].westCrownWidth.ToString("0.00"))); oFeature.SetField(19, double.Parse(trees[i].northCrownWidth.ToString("0.00"))); } oFeature.SetField(20, double.Parse(trees[i].Biomass.ToString("0.00"))); if (trees[i].isMortality) { oFeature.SetField(21, "Mortality"); } if (trees[i].isCutting) { oFeature.SetField(22, "Cutting"); } Geometry geoTree = new Geometry(wkbGeometryType.wkbPoint); geoTree.AddPoint(double.Parse(trees[i].X.ToString("0.00")), double.Parse(trees[i].Y.ToString("0.00")), 0); oFeature.SetGeometry(geoTree); outLayer.CreateFeature(oFeature); } }
static void Main(string[] args) { //Ausgabe abschalten Console.SetOut(new StringWriter()); GdalConfiguration.ConfigureGdal(); GdalConfiguration.ConfigureOgr(); //Ausgabe einschalten var stdOut = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = true }; Console.SetOut(stdOut); //check Arguments OSGeo.OSR.SpatialReference _sr = new OSGeo.OSR.SpatialReference(""); if (!Utils.ChkArgs(args, ref _in, ref _sr, ref _out)) { Console.WriteLine("**** mission2shp **** /co(2019) DI Rudolf Matzeder"); Console.WriteLine("Befehlszeilenargumente:"); Console.WriteLine(" -i: Input File, Mission Planner Polygon File (usually *.poly)"); Console.WriteLine(" -cs: EPSG code of coordinate system"); Console.WriteLine(" 4326 WGS84"); Console.WriteLine(" 31255 MGI central Austria"); Console.WriteLine(" -o: Output File, shp File to be generated"); Console.WriteLine(); } else { OSGeo.OGR.Driver driver = Ogr.GetDriverByName("ESRI Shapefile"); // _in = Path.Combine(Environment.CurrentDirectory, _in); //Konsole Console.WriteLine(" -i: " + _in); _sr.ExportToPrettyWkt(out string wkt, 0); Console.WriteLine("-cs: " + wkt); Console.WriteLine(" -o:" + _out); //Output DataSource ds = driver.CreateDataSource(_out, new string[] { }); Layer ly = ds.CreateLayer("Test", _sr, wkbGeometryType.wkbPolygon, new string[] { }); //Felder OSGeo.OGR.FieldDefn fDefn = new FieldDefn("Block", FieldType.OFTString); fDefn.SetWidth(12); ly.CreateField(fDefn, 1); //Feature OSGeo.OGR.FeatureDefn featureDefn = new FeatureDefn(""); featureDefn.AddFieldDefn(fDefn); try { string path = Path.GetDirectoryName(_in); if (path == String.Empty) { path = Directory.GetCurrentDirectory(); } string datei = Path.GetFileName(_in); string[] files = Directory.GetFiles(path, datei); int cntFeatures = 0; foreach (string file in files) { Geometry geoPL = new Geometry(wkbGeometryType.wkbCurvePolygon); string Block = Path.GetFileNameWithoutExtension(file); geoPL = ReadFile(file); if (!geoPL.IsEmpty()) { //Ausgabe shp File OSGeo.OGR.Feature feature = new Feature(featureDefn); feature.SetGeometryDirectly(geoPL); feature.SetField("Block", Block); ly.CreateFeature(feature); cntFeatures++; } } Console.WriteLine("generierte Features: " + cntFeatures); } catch { Console.WriteLine("no Input"); } ds.Dispose(); } Geometry ReadFile(string input) { Geometry geoPL = new Geometry(wkbGeometryType.wkbPolygon); string Text = String.Empty; try { StreamReader sr = new StreamReader(input); Text = sr.ReadToEnd(); sr.Close(); } catch { } if (Text != String.Empty) { string[] rows = Text.Split(new[] { Environment.NewLine }, StringSplitOptions.None); Geometry geoRing = new Geometry(wkbGeometryType.wkbLinearRing); foreach (string row in rows) { try { string[] pt = row.Split(new[] { ' ' }); double x = double.Parse(pt[1], CultureInfo.InvariantCulture); double y = double.Parse(pt[0], CultureInfo.InvariantCulture); geoRing.AddPoint_2D(x, y); } catch { } } geoPL.AddGeometry(geoRing); } return(geoPL); } }