private void cmbLayers_SelectedIndexChanged(object sender, EventArgs e) { cmbIdField.Items.Clear(); cmbNameField.Items.Clear(); if (cmbLayers.SelectedIndex > -1) { try { cmbNameField.Items.Add("<无>"); var layer = dataSourceSelector1.GetLayerByName(cmbLayers.SelectedItem.ToString()); FeatureDefn featureDefn = layer.GetLayerDefn(); for (int i = 0; i < featureDefn.GetFieldCount(); i++) { var fieldName = featureDefn.GetFieldDefn(i).GetName(); cmbNameField.Items.Add(fieldName); cmbIdField.Items.Add(fieldName); } if (cmbIdField.Items.Contains("XMID")) { cmbIdField.SelectedItem = "XMID"; if (cmbNameField.Items.Contains("XMMC")) { cmbNameField.SelectedItem = "XMMC"; } } } catch (Exception ex) { MessageBox.Show(ex.Message, Text, MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
public void opiszWarstwe() { FeatureDefn def = this.layer.GetLayerDefn(); Console.WriteLine("Nazwa warstwy: " + def.GetName()); Console.WriteLine("Liczba obiektów: " + this.layer.GetFeatureCount(1)); Envelope ext = new Envelope(); layer.GetExtent(ext, 1); Console.WriteLine("Zasiêg: " + ext.MinX + "," + ext.MaxX + "," + ext.MinY + "," + ext.MaxY); SpatialReference sr = this.layer.GetSpatialRef(); string srs_wkt = "(unknown)"; if (sr != null) { sr.ExportToPrettyWkt(out srs_wkt, 1); } Console.WriteLine("Uk³ad przestrzenny warstwy: " + srs_wkt); Console.WriteLine("Definicje atrybutów:"); for (int iAttr = 0; iAttr < def.GetFieldCount(); iAttr++) { FieldDefn fdef = def.GetFieldDefn(iAttr); Console.WriteLine(fdef.GetNameRef() + ": " + fdef.GetFieldTypeName(fdef.GetFieldType()) + " (" + fdef.GetWidth() + "." + fdef.GetPrecision() + ")"); } }
public bool getFields() { if (oLayer == null) { return(false); } mFiledList.Clear(); //获取图层的属性表结构 FeatureDefn oDefn = oLayer.GetLayerDefn(); int filedCount = oDefn.GetFieldCount(); for (int i = 0; i < filedCount; i++) { //获取指定序号的属性列 FieldDefn oField = oDefn.GetFieldDefn(i); if (oField != null) { //获取属性列名字 mFiledList.Add(oField.GetNameRef()); } } return(true); }
private Dictionary <string, Type> getShapeFields(out string errorMessage) { errorMessage = ""; Dictionary <string, Type> fields = new Dictionary <string, Type>(); try { DataSource ds = Ogr.Open(inputFile.FullName, 0); if (ds == null) { throw new Exception("Невозможно открыть файл"); } var layerCount = ds.GetLayerCount(); if (layerCount != 1) { throw new Exception("В файле должен быть ровно один слой"); } var layer = ds.GetLayerByIndex(0); FeatureDefn featDef = layer.GetLayerDefn(); var fc = featDef.GetFieldCount(); for (int i = 0; i < fc; i++) { var field = featDef.GetFieldDefn(i); fields.Add(field.GetNameRef(), convertType(field.GetFieldType())); } featDef.Dispose(); layer.Dispose(); ds.Dispose(); } catch (Exception ex) { errorMessage = ex.Message; } return(fields); }
public void test(ref Layer oLayer) { // 对图层进行初始化,如果对图层进行了过滤操作,执行这句后,之前的过滤全部清空 oLayer.ResetReading(); // 获取图层中的属性表表头并输出 string strInfo = "属性表结构信息:\n"; FeatureDefn oDefn = oLayer.GetLayerDefn(); int iFieldCount = oDefn.GetFieldCount(); for (int iAttr = 0; iAttr < iFieldCount; iAttr++) { FieldDefn oField = oDefn.GetFieldDefn(iAttr); strInfo += string.Format("{0}:{1} ({2}.{3})\n", oField.GetNameRef(), oField.GetFieldTypeName(oField.GetFieldType()), oField.GetWidth(), oField.GetPrecision()); } // 输出图层中的要素个数 strInfo += string.Format("要素个数 = {0}\n", oLayer.GetFeatureCount(0)); Feature oFeature = null; // 下面开始遍历图层中的要素 while ((oFeature = oLayer.GetNextFeature()) != null) { strInfo += string.Format("\n当前处理第{0}个: \n属性值:", oFeature.GetFID()); // 获取要素中的属性表内容 for (int iField = 0; iField < iFieldCount; iField++) { FieldDefn oFieldDefn = oDefn.GetFieldDefn(iField); FieldType type = oFieldDefn.GetFieldType(); switch (type) { case FieldType.OFTString: IntPtr pchar = OGR_F_GetFieldAsString(Feature.getCPtr(oFeature), iField); string val = Marshal.PtrToStringAnsi(pchar); strInfo += string.Format("{0}\t", val); break; case FieldType.OFTReal: strInfo += string.Format("{0}\t", oFeature.GetFieldAsDouble(iField)); break; case FieldType.OFTInteger: strInfo += string.Format("{0}\t", oFeature.GetFieldAsInteger(iField)); break; default: strInfo += string.Format("{0}\t", oFeature.GetFieldAsString(iField)); break; } } // 获取要素中的几何体 Geometry oGeometry = oFeature.GetGeometryRef(); // 为了演示,只输出一个要素信息 break; } strInfo += "\n数据集关闭!"; }
public static string ReportLayer(Layer layer) { string strInfomation = ""; FeatureDefn def = layer.GetLayerDefn(); strInfomation += ("Layer name: " + def.GetName()); strInfomation += ("Feature Count: " + layer.GetFeatureCount(1).ToString()); Envelope ext = new Envelope(); layer.GetExtent(ext, 1); strInfomation += ("Extent: " + ext.MinX.ToString() + "," + ext.MaxX.ToString() + "," + ext.MinY.ToString() + "," + ext.MaxY.ToString()); /* -------------------------------------------------------------------- */ /* Reading the spatial reference */ /* -------------------------------------------------------------------- */ OSGeo.OSR.SpatialReference sr = layer.GetSpatialRef(); string srs_wkt; if (sr != null) { sr.ExportToPrettyWkt(out srs_wkt, 1); } else { srs_wkt = "(unknown)"; } strInfomation += ("Layer SRS WKT: " + srs_wkt); /* -------------------------------------------------------------------- */ /* Reading the fields */ /* -------------------------------------------------------------------- */ strInfomation += ("Field definition:"); for (int iAttr = 0; iAttr < def.GetFieldCount(); iAttr++) { FieldDefn fdef = def.GetFieldDefn(iAttr); strInfomation += (fdef.GetNameRef() + ": " + fdef.GetFieldTypeName(fdef.GetFieldType()) + " (" + fdef.GetWidth().ToString() + "." + fdef.GetPrecision().ToString() + ")"); } /* -------------------------------------------------------------------- */ /* Reading the shapes */ /* -------------------------------------------------------------------- */ strInfomation += (""); Feature feat; while ((feat = layer.GetNextFeature()) != null) { strInfomation += ReportFeature(feat, def); feat.Dispose(); } return(strInfomation); }
public static IEnumerable <FieldDefn> FieldDefns(this FeatureDefn featureDefn) { var count = featureDefn.GetFieldCount(); for (int i = 0; i < count; i++) { yield return(featureDefn.GetFieldDefn(i)); } }
public override bool isExternalMetadataValid() { IDTSExternalMetadataColumnCollection100 exColumns = ComponentMetaData.InputCollection[0].ExternalMetadataColumnCollection; Layer OGRLayer = this.getLayer(); FeatureDefn OGRFeatureDef = OGRLayer.GetLayerDefn(); // Get Geometry column name string geomtryColumn = (OGRLayer.GetGeometryColumn() != "") ? OGRLayer.GetGeometryColumn() : "GEOMETRY"; //check for correct number of external metadata columns if (OGRFeatureDef.GetFieldCount() + 1 != exColumns.Count) { return(false); } //validate each external metadata column for (int i = 0; i < exColumns.Count; i++) { IDTSExternalMetadataColumn100 col = exColumns[i]; if (col.Name == geomtryColumn) { if (col.DataType != DataType.DT_IMAGE) { return(false); } // Check geometry column custom property against source if ((string)ComponentMetaData.CustomPropertyCollection["Geometry Column"].Value != geomtryColumn) { return(false); } } else { //check if ogr field exists by name int OGRFieldIndex = OGRFeatureDef.GetFieldIndex(col.Name); if (OGRFieldIndex == -1) { return(false); } //check if ogr column matches output column type FieldDefn OGRFieldDef = OGRFeatureDef.GetFieldDefn(OGRFieldIndex); FieldType OGRFieldType = OGRFieldDef.GetFieldType(); if (this.OGRTypeToBufferType(OGRFieldType) != col.DataType) { //check for case where OFTString -> DT_NTEXT if (!(OGRFieldType == FieldType.OFTString && col.DataType == DataType.DT_NTEXT)) { return(false); } } } } return(true); }
/// <summary> /// Initializes a new instance of the <see cref="OgrDataReader"/> class. /// </summary> /// <param name="sDataSource">The path of the data source file.</param> /// <param name="sLayer">Name of the layer.</param> public OgrDataReader(string sDataSource, string sLayer) { _ogrDataSource = Ogr.Open(sDataSource, 0); _ogrLayer = sLayer != null?_ogrDataSource.GetLayerByName(sLayer) : _ogrDataSource.GetLayerByIndex(0); _ogrFeatureDefinition = _ogrLayer.GetLayerDefn(); _iFieldCount = _ogrFeatureDefinition.GetFieldCount(); BuildSchemaTable(); _currentFeature = null; IsClosed = false; }
public static MG_FieldSet AsFieldSet(FeatureDefn f) { MG_FieldSet fieldSet = new MG_FieldSet(f.GetName());// name int count = f.GetFieldCount(); for (int i = 0; i < count; i++) { MG_Field field = AsField(f.GetFieldDefn(i)); fieldSet.Add(field); } return(fieldSet); }
private static IList <Column> BuildSchemaTable(FeatureDefn ogrFeatureDefinition) { IList <Column> schema = new List <Column>(); for (int i = 0; i < ogrFeatureDefinition.GetFieldCount(); i++) { FieldDefn f = ogrFeatureDefinition.GetFieldDefn(i); schema.Add(new Column(f.GetName(), f.GetFieldType())); } return(schema); }
/// <summary> /// 获取图层中的全部字段 /// </summary> /// <param name="layer"></param> /// <returns></returns> public static List <FieldDefn> GetFields(this Layer layer) { var fields = new List <FieldDefn>(); FeatureDefn featureDefn = layer.GetLayerDefn(); for (int i = 0; i < featureDefn.GetFieldCount(); i++) { fields.Add(featureDefn.GetFieldDefn(i)); } return(fields); }
/// <summary> /// Fetch the field names from a layer /// </summary> /// <param name="ogrLayer">the layer</param> /// <returns>Arraylist of strings</returns> private ArrayList GetFieldNames(Layer ogrLayer) { FeatureDefn featDef = ogrLayer.GetLayerDefn(); ArrayList fNames = new ArrayList(); for (int i = 0; i < featDef.GetFieldCount(); i++) { FieldDefn fieldDef = featDef.GetFieldDefn(i); fNames.Add(fieldDef.GetName()); } return(fNames); }
/// <summary> /// 获取所有列名 /// </summary> /// <param name="strVectorFile"></param> /// <returns></returns> public static List <string> getShapeFieldList(string strVectorFile) { List <string> list = new List <string>(); #region ReadShape { Gdal.AllRegister(); // 为了支持中文路径,请添加下面这句代码 OSGeo.GDAL.Gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "NO"); // 为了使属性表字段支持中文,请添加下面这句 OSGeo.GDAL.Gdal.SetConfigOption("SHAPE_ENCODING", ""); // 注册所有的驱动 Ogr.RegisterAll(); //打开数据 DataSource ds = Ogr.Open(strVectorFile, 0); if (ds == null) { MessageBox.Show("打开文件【{0}】失败!,文件名中不能包含中文!", strVectorFile); return(list); } //MessageBox.Show("打开文件【{0}】成功!", strVectorFile); // 获取该数据源中的图层个数,一般shp数据图层只有一个,如果是mdb、dxf等图层就会有多个 int iLayerCount = ds.GetLayerCount(); // 获取第一个图层 Layer oLayer = ds.GetLayerByIndex(0); if (oLayer == null) { MessageBox.Show("获取第{0}个图层失败!\n", "0"); return(list); } // 对图层进行初始化,如果对图层进行了过滤操作,执行这句后,之前的过滤全部清空 oLayer.ResetReading(); FeatureDefn oDefn = oLayer.GetLayerDefn(); // 输出图层中的要素个数 int iFieldCount = oDefn.GetFieldCount(); for (int iAttr = 0; iAttr < iFieldCount; iAttr++) { FieldDefn oField = oDefn.GetFieldDefn(iAttr); list.Add(oField.GetNameRef()); } } #endregion list.Sort(); return(list); }
public List <string> GetTileNameFromShapefile(string shpfilepath) { string fieldname = "TileName"; bool gotit = false; List <string> tilenames = new List <string>(); DataSource ds1 = Ogr.Open(shpfilepath, 0); if (ds1 == null) { Console.WriteLine(" [-] Could not open {0}", shpfilepath); return(tilenames); } Layer newlayer = ds1.GetLayerByIndex(0); if (newlayer == null) { Console.WriteLine(" [-] Could not fetch layer."); ds1.Dispose(); return(tilenames); } newlayer.ResetReading(); FeatureDefn newfeaturedfn = newlayer.GetLayerDefn(); for (int i = 0; i < newfeaturedfn.GetFieldCount(); i++) { //find TileName field in provided shapefile FieldDefn fielddefn = newfeaturedfn.GetFieldDefn(i); if (fielddefn.GetName() == fieldname) { gotit = true; break; } } if (gotit == false) { Console.WriteLine(" [-] Could not find tile name field. Please provide shapefile with the attribute field TileName"); ds1.Dispose(); return(tilenames); } for (int i = 0; i < newlayer.GetFeatureCount(1); i++) { //return each string for TileName field in shapefile Feature newfeature = newlayer.GetFeature(i); string result = newfeature.GetFieldAsString(fieldname); tilenames.Add(result); } ds1.Dispose(); return(tilenames); }
/// <summary> /// 获取某条数据的字段内容 /// </summary> /// <param name="iIndex"></param> /// <param name="FeildStringList"></param> /// <returns></returns> public bool GetFeildContent(int iIndex, out List <string> FeildStringList) { FeildStringList = new List <string>(); Feature oFeature = null; if ((oFeature = oLayer.GetFeature(iIndex)) != null) { FeatureDefn oDefn = oLayer.GetLayerDefn(); int iFieldCount = oDefn.GetFieldCount(); // 查找字段属性 for (int iAttr = 0; iAttr < iFieldCount; iAttr++) { FieldDefn oField = oDefn.GetFieldDefn(iAttr); string sFeildName = oField.GetNameRef(); #region 获取属性字段 FieldType Ftype = oFeature.GetFieldType(sFeildName); switch (Ftype) { case FieldType.OFTString: string sFValue = oFeature.GetFieldAsString(sFeildName); string sTempType = "string"; FeildStringList.Add(sFValue); break; case FieldType.OFTReal: double dFValue = oFeature.GetFieldAsDouble(sFeildName); sTempType = "float"; FeildStringList.Add(dFValue.ToString()); break; case FieldType.OFTInteger: int iFValue = oFeature.GetFieldAsInteger(sFeildName); sTempType = "int"; FeildStringList.Add(iFValue.ToString()); break; default: //sFValue = oFeature.GetFieldAsString(ChosenFeildIndex[iFeildIndex]); sTempType = "string"; break; } #endregion } } return(true); }
/// <summary>获取某条数据的字段内容 /// </summary> /// <param name="nIndex"></param> /// <param name="lstFeildString"></param> /// <param name="fileAttrEncoding">文件属性字段编码类型</param> /// <returns></returns> public virtual bool GetFeildContent(int nIndex, out Dictionary <string, string> dictFieldInfo, Encoding fileAttrEncoding) { _FileAttrEncoding = fileAttrEncoding; dictFieldInfo = new Dictionary <string, string>(); Feature oFeature = null; if ((oFeature = _Layer.GetFeature(nIndex)) != null) { FeatureDefn oDefn = _Layer.GetLayerDefn(); int iFieldCount = oDefn.GetFieldCount(); // 查找字段属性 for (int iAttr = 0; iAttr < iFieldCount; iAttr++) { FieldDefn oField = oDefn.GetFieldDefn(iAttr); string strFeildName = oField.GetNameRef(); string strValue = ""; #region 获取属性字段 FieldType Ftype = oFeature.GetFieldType(strFeildName); switch (Ftype) { case FieldType.OFTString: strValue = GetFieldAsStringNu(oFeature, strFeildName, _FileAttrEncoding); break; case FieldType.OFTReal: double dFValue = oFeature.GetFieldAsDouble(strFeildName); strValue = dFValue.ToString(); break; case FieldType.OFTInteger: int iFValue = oFeature.GetFieldAsInteger(strFeildName); strValue = iFValue.ToString(); break; default: break; } dictFieldInfo.Add(strFeildName, strValue); #endregion } } return(true); }
public OgrDataReader(string sDataSource, string sLayer) { //wkbReader = new DotSpatial.Data.WKBReader(); _ogrDataSource = Ogr.Open(sDataSource, 0); _ogrLayer = _ogrDataSource.GetLayerByName(sLayer); _iFeatureCount = _ogrLayer.GetFeatureCount(1); _ogrFeatureDefinition = _ogrLayer.GetLayerDefn(); _iFieldCount = _ogrFeatureDefinition.GetFieldCount(); BuildSchemaTable(); _currentFeature = null; bClosed = false; }
/// <summary> /// Reads the field types from the OgrFeatureDefinition -> OgrFieldDefinition /// </summary> /// <param name="fdt">FeatureDatatTable</param> /// <param name="oLayer">OgrLayer</param> private void readColumnDefinition(FeatureDataTable fdt, Layer oLayer) { using (FeatureDefn _OgrFeatureDefn = oLayer.GetLayerDefn()) { int iField; for (iField = 0; iField < _OgrFeatureDefn.GetFieldCount(); iField++) { using (FieldDefn _OgrFldDef = _OgrFeatureDefn.GetFieldDefn(iField)) { FieldType type; switch ((type = _OgrFldDef.GetFieldType())) { case FieldType.OFTInteger: fdt.Columns.Add(_OgrFldDef.GetName(), Type.GetType("System.Int32")); break; case FieldType.OFTReal: fdt.Columns.Add(_OgrFldDef.GetName(), Type.GetType("System.Double")); break; case FieldType.OFTString: fdt.Columns.Add(_OgrFldDef.GetName(), Type.GetType("System.String")); break; case FieldType.OFTWideString: fdt.Columns.Add(_OgrFldDef.GetName(), Type.GetType("System.String")); break; default: { //fdt.Columns.Add(_OgrFldDef.GetName(), System.Type.GetType("System.String")); Debug.WriteLine("Not supported type: " + type + " [" + _OgrFldDef.GetName() + "]"); break; } } } } } }
private static void Details(string dataSetPath) { Driver fileGdbDriver = Ogr.GetDriverByName("OpenFileGDB"); DataSource dataSource = fileGdbDriver.Open(dataSetPath, 0); Layer layer = dataSource.GetLayerByIndex(0); string shapeType = layer.GetGeomType().ToString("G").Substring(3); Console.WriteLine($"Shape Type: {shapeType}"); SpatialReference spatialReference = layer.GetSpatialRef(); string projectionName = spatialReference.GetName(); Console.WriteLine($"Projection: {projectionName}"); using Envelope extent = new Envelope(); layer.GetExtent(extent, 0); var dataSetExtent = new { XMin = extent.MinX, XMax = extent.MaxX, YMin = extent.MinY, YMax = extent.MaxY, }; Console.WriteLine($"Extent: {JsonSerializer.Serialize(dataSetExtent, new JsonSerializerOptions { WriteIndented = true })}"); int featureCount = (int)layer.GetFeatureCount(0); Console.WriteLine($"Feature Count: {featureCount}"); List <dynamic> columns = new List <dynamic>(); FeatureDefn layerDefinition = layer.GetLayerDefn(); for (int j = 0; j < layerDefinition.GetFieldCount(); j++) { FieldDefn field = layerDefinition.GetFieldDefn(j); columns.Add(new { Name = field.GetName(), DataType = field.GetFieldTypeName(field.GetFieldType()), }); } Console.WriteLine($"Columns: {JsonSerializer.Serialize(columns, new JsonSerializerOptions { WriteIndented = true })}"); }
private FeatureDataTable CreateFeatureDataTableStructure() { var featureDataTable = new FeatureDataTable(); //reads the column definition of the layer/feature using (FeatureDefn ogrFeatureDefn = ogrLayer.GetLayerDefn()) { int iField; var ogrTypesAndCSharpTypesMapping = new Dictionary <FieldType, Type>(); ogrTypesAndCSharpTypesMapping[FieldType.OFTInteger] = typeof(int); ogrTypesAndCSharpTypesMapping[FieldType.OFTReal] = typeof(double); ogrTypesAndCSharpTypesMapping[FieldType.OFTString] = typeof(string); ogrTypesAndCSharpTypesMapping[FieldType.OFTWideString] = typeof(string); ogrTypesAndCSharpTypesMapping[FieldType.OFTDateTime] = typeof(DateTime); for (iField = 0; iField < ogrFeatureDefn.GetFieldCount(); iField++) { using (FieldDefn ogrFldDef = ogrFeatureDefn.GetFieldDefn(iField)) { if (ogrTypesAndCSharpTypesMapping.ContainsKey(ogrFldDef.GetFieldType())) { featureDataTable.Columns.Add(ogrFldDef.GetName(), ogrTypesAndCSharpTypesMapping[ogrFldDef.GetFieldType()]); } else { //fdt.Columns.Add(_OgrFldDef.GetName(), System.Type.GetType("System.String")); Debug.WriteLine("Not supported type: " + ogrFldDef.GetFieldType() + " [" + ogrFldDef.GetName() + "]"); break; } } } } return(featureDataTable); }
/// <summary>获取所有的属性字段 /// </summary> /// <returns></returns> public virtual bool GetFeilds() { if (null == _Layer) { return(false); } _Feilds.Clear(); wkbGeometryType oTempGeometryType = _Layer.GetGeomType(); FeatureDefn oDefn = _Layer.GetLayerDefn(); int iFieldCount = oDefn.GetFieldCount(); for (int iAttr = 0; iAttr < iFieldCount; iAttr++) { FieldDefn oField = oDefn.GetFieldDefn(iAttr); if (null != oField) { _Feilds.Add(oField.GetNameRef(), oField.GetFieldType()); } } return(true); }
/// <summary> /// 获取所有的属性字段 /// </summary> /// <returns></returns> public void GetFeilds() { if (null == oLayer) { } 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()); } } string[] a = m_FeildList.ToArray(); }
/// <summary> /// Adds the features for the other file types. /// </summary> /// <param name="fs">The featureset the features get added to.</param> /// <param name="styles">The list the styles get added to.</param> /// <param name="layer">The layer to get the features from.</param> /// <param name="ogrFeatureDefinition">The feature definition that contains the field count.</param> /// <param name="schema">The list of columns used to fill the datarow.</param> private static void AddFeatures(IFeatureSet fs, IList <string> styles, Layer layer, FeatureDefn ogrFeatureDefinition, IList <Column> schema) { var wkbReader = new WKBReader(); OgrFeature ogrFeature = layer.GetNextFeature(); var fieldCount = ogrFeatureDefinition.GetFieldCount(); while (ogrFeature != null) { var wkbGeometry = GetGeometry(ogrFeature); var geometry = wkbReader.Read(wkbGeometry); if (geometry != null && geometry.IsValid && !geometry.IsEmpty) { IFeature feature = new Feature(geometry); if (fs.Features.Count == 0 || feature.FeatureType == fs.FeatureType) { fs.Features.Add(feature); for (int i = 0; i < fieldCount; i++) { feature.DataRow[i] = GetValue(i, schema, ogrFeature) ?? DBNull.Value; } var str = ogrFeature.GetStyleString(); feature.DataRow["style"] = str; if (!styles.Contains(str)) { // add the style to the layer styles.Add(str); } } } ogrFeature = layer.GetNextFeature(); } }
//Checks if output metadata columns match ogrlayer source columns public override bool isMetadataValid() { //get default output IDTSOutput100 output = null; for (int i = 0; i < ComponentMetaData.OutputCollection.Count; i++) { if (!ComponentMetaData.OutputCollection[i].IsErrorOut) { output = ComponentMetaData.OutputCollection[i]; } } //get ogrlayer and layer definition Layer OGRLayer; bool isSQLLayer = (!(ComponentMetaData.CustomPropertyCollection["SQL Statement"].Value == null || ComponentMetaData.CustomPropertyCollection["SQL Statement"].Value.ToString() == string.Empty)); if (isSQLLayer) { OGRLayer = getSQLLayer(); } else { OGRLayer = getLayer(); } FeatureDefn OGRFeatureDef = OGRLayer.GetLayerDefn(); // Get Geometry column name string geomtryColumn = (OGRLayer.GetGeometryColumn() != "") ? OGRLayer.GetGeometryColumn() : "GEOMETRY"; // Begin checks bool isValid = true; if (OGRFeatureDef.GetFieldCount() + 1 == output.OutputColumnCollection.Count) { int i = 0; do { //check if ogr field exists by name IDTSOutputColumn100 col = output.OutputColumnCollection[i]; int OGRFieldIndex = OGRFeatureDef.GetFieldIndex(col.Name); if (OGRFieldIndex == -1) { //set isValid false if not geom column if ((col.Name != geomtryColumn) || (col.DataType != DataType.DT_IMAGE) || ((string)ComponentMetaData.CustomPropertyCollection["Geometry Column"].Value != geomtryColumn)) { isValid = false; } } else { //is isVaild to false if field types don't match FieldDefn OGRFieldDef = OGRFeatureDef.GetFieldDefn(OGRFieldIndex); FieldType OGRFieldType = OGRFieldDef.GetFieldType(); if ((col.DataType != this.OGRTypeToBufferType(OGRFieldType)) && (!(OGRFieldType == FieldType.OFTString && col.DataType == DataType.DT_NTEXT))) // special case where lenth not provided by OFTString { isValid = false; } } i++; } while (isValid && i < output.OutputColumnCollection.Count); } else { isValid = false; } //Manualy call release on OGR layer sql result set if needed if (isSQLLayer) { this.OGRDataSource.ReleaseResultSet(OGRLayer); } return(isValid); }
public override void ReinitializeMetaData() { base.ReinitializeMetaData(); //get default output IDTSOutput100 defaultOutput = null; this.GetErrorOutputInfo(ref errorOutputID, ref errorOutputIndex); foreach (IDTSOutput100 output in ComponentMetaData.OutputCollection) { if (output.ID != errorOutputID) { defaultOutput = output; } } if (this.isConnected) { defaultOutput.OutputColumnCollection.RemoveAll(); defaultOutput.ExternalMetadataColumnCollection.RemoveAll(); //get ogrlayer and layer definition Layer OGRLayer; bool isSQLLayer = (!(ComponentMetaData.CustomPropertyCollection["SQL Statement"].Value == null || ComponentMetaData.CustomPropertyCollection["SQL Statement"].Value.ToString() == string.Empty)); if (isSQLLayer) { OGRLayer = getSQLLayer(); } else { OGRLayer = getLayer(); } FeatureDefn OGRFeatureDef = OGRLayer.GetLayerDefn(); //for each field in ogrlayer add output column and external metadata int i = 0; while (i < OGRFeatureDef.GetFieldCount()) { //map OGR field type to SSIS data type FieldDefn OGRFieldDef = OGRFeatureDef.GetFieldDefn(i); DataType BufferDataType = this.OGRTypeToBufferType(OGRFieldDef.GetFieldType()); int length = 0; int precision = OGRFieldDef.GetWidth(); int scale = OGRFieldDef.GetPrecision(); int codepage = 1252; switch (BufferDataType) { case DataType.DT_WSTR: length = precision; codepage = 0; precision = 0; scale = 0; //check for length == 0 if (length == 0) { //BufferDataType = DataType.DT_NTEXT; length = 4000; } break; default: length = 0; precision = 0; codepage = 0; scale = 0; break; } //create column metadata IDTSOutputColumn100 col = defaultOutput.OutputColumnCollection.New(); col.Name = OGRFieldDef.GetName(); col.ErrorRowDisposition = DTSRowDisposition.RD_FailComponent; col.TruncationRowDisposition = DTSRowDisposition.RD_FailComponent; col.SetDataTypeProperties(BufferDataType, length, precision, scale, codepage); //create external metadata IDTSExternalMetadataColumn100 ecol = defaultOutput.ExternalMetadataColumnCollection.New(); ecol.Name = col.Name; ecol.DataType = col.DataType; ecol.Precision = col.Precision; ecol.Length = col.Length; ecol.Scale = col.Scale; ecol.CodePage = col.CodePage; col.ExternalMetadataColumnID = ecol.ID; i++; } //get geometry column string geomtryColumn = (OGRLayer.GetGeometryColumn() != "") ? OGRLayer.GetGeometryColumn() : "GEOMETRY"; //add geom output column IDTSOutputColumn100 geomCol = defaultOutput.OutputColumnCollection.New(); geomCol.Name = geomtryColumn; geomCol.ErrorRowDisposition = DTSRowDisposition.RD_FailComponent; geomCol.TruncationRowDisposition = DTSRowDisposition.RD_FailComponent; geomCol.SetDataTypeProperties(DataType.DT_IMAGE, 0, 0, 0, 0); //add geom external metadata IDTSExternalMetadataColumn100 egeomCol = defaultOutput.ExternalMetadataColumnCollection.New(); egeomCol.Name = geomCol.Name; egeomCol.DataType = geomCol.DataType; egeomCol.Precision = geomCol.Precision; egeomCol.Length = geomCol.Length; egeomCol.Scale = geomCol.Scale; egeomCol.CodePage = geomCol.CodePage; //map column metadata to external column metadata geomCol.ExternalMetadataColumnID = egeomCol.ID; //set geometry column custom property ComponentMetaData.CustomPropertyCollection["Geometry Column"].Value = geomtryColumn; if (isSQLLayer) { this.OGRDataSource.ReleaseResultSet(OGRLayer); } } }
public static bool CovertRegion2Line(string path, string savePath) { try { OSGeo.OGR.Ogr.RegisterAll(); OSGeo.OGR.Driver dr = OSGeo.OGR.Ogr.GetDriverByName("ESRI shapefile"); if (dr == null) { Console.WriteLine("启动驱动失败!\n"); } OSGeo.OGR.DataSource ds = dr.Open(path, 0); int layerCount = ds.GetLayerCount(); OSGeo.OGR.Layer layer = ds.GetLayerByIndex(0); FeatureDefn fdf = layer.GetLayerDefn(); int fieldCount = fdf.GetFieldCount(); // 创建数据源 DataSource oDS = dr.CreateDataSource(savePath, null); if (oDS == null) { Console.WriteLine("创建矢量文件【%s】失败!\n", savePath); return(false); } OSGeo.OSR.SpatialReference srs = layer.GetSpatialRef(); // 创建图层,创建一个多边形图层,这里没有指定空间参考,如果需要的话,需要在这里进行指定 Layer oLayer = oDS.CreateLayer("line", srs, OSGeo.OGR.wkbGeometryType.wkbMultiLineString, null); if (oLayer == null) { Console.WriteLine("图层创建失败!\n"); return(false); } for (int i = 0; i < fieldCount; i++) { FieldDefn fieldDefn = fdf.GetFieldDefn(i); oLayer.CreateField(fieldDefn, 1); } FeatureDefn oDefn = oLayer.GetLayerDefn(); OSGeo.OGR.Feature feat; while ((feat = layer.GetNextFeature()) != null) { Feature oFeatureMulty = new Feature(oDefn); OSGeo.OGR.Geometry geometry = feat.GetGeometryRef(); for (int i = 0; i < fieldCount; i++) { string value = feat.GetFieldAsString(i); oFeatureMulty.SetField(i, value); } OSGeo.OGR.wkbGeometryType goetype = geometry.GetGeometryType(); if (goetype == OSGeo.OGR.wkbGeometryType.wkbPolygon) { Geometry tempGeo = new Geometry(wkbGeometryType.wkbMultiLineString); int count = geometry.GetGeometryCount(); for (int j = 0; j < count; j++) { Geometry line = new Geometry(wkbGeometryType.wkbLinearRing); Geometry geo = geometry.GetGeometryRef(j); for (int i = 0; i < geo.GetPointCount(); i++) { double x = geo.GetX(i); double y = geo.GetY(i); line.AddPoint(x, y, 0); } tempGeo.AddGeometryDirectly(line); } oFeatureMulty.SetGeometry(tempGeo); } oLayer.SetFeature(oFeatureMulty); } oLayer.Dispose(); layer.Dispose(); oDS.Dispose(); ds.Dispose(); dr.Dispose(); } catch { } return(false); }
/// <summary> /// 转换并纠偏,只使用与火星坐标纠偏 /// </summary> /// <param name="dataTable">数据表,如果是点表中含X,Y字段,如果是线和面,表中含有PATH字段</param> /// <param name="filePath">存储路径</param> /// <param name="geoType">数据类型,暂时支持简单的点线面</param> //public static void saveShpFile(DataTable dataTable,string filePath,wkbGeometryType geoType) //{ // saveShpFile(dataTable, filePath, geoType, ProjectConvert.GCJ_WGS); //} /// <summary> /// 导出shp数据到表格 /// </summary> /// <param name="path">文件路径</param> /// <returns>DataTable</returns> public static DataTable GetData(string path) { try { OSGeo.OGR.Ogr.RegisterAll(); OSGeo.OGR.Driver dr = OSGeo.OGR.Ogr.GetDriverByName("ESRI shapefile"); if (dr == null) { Console.WriteLine("启动驱动失败!\n"); } OSGeo.OGR.DataSource ds = dr.Open(path, 0); int layerCount = ds.GetLayerCount(); OSGeo.OGR.Layer layer = ds.GetLayerByIndex(0); DataTable dataTable = new DataTable(); FeatureDefn fdf = layer.GetLayerDefn(); int fieldCount = fdf.GetFieldCount(); for (int i = 0; i < fieldCount; i++) { dataTable.Columns.Add(fdf.GetFieldDefn(i).GetName(), Type.GetType("System.String")); } if (fdf.GetGeomType() == OSGeo.OGR.wkbGeometryType.wkbPoint) { if (!dataTable.Columns.Contains("X")) { dataTable.Columns.Add("X", Type.GetType("System.String")); } if (!dataTable.Columns.Contains("Y")) { dataTable.Columns.Add("Y", Type.GetType("System.String")); } } else if (fdf.GetGeomType() == OSGeo.OGR.wkbGeometryType.wkbPolygon || fdf.GetGeomType() == OSGeo.OGR.wkbGeometryType.wkbLineString) { if (!dataTable.Columns.Contains("PATH")) { dataTable.Columns.Add("PATH", Type.GetType("System.String")); } } OSGeo.OGR.Feature feat; while ((feat = layer.GetNextFeature()) != null) { DataRow row = dataTable.NewRow(); OSGeo.OGR.Geometry geometry = feat.GetGeometryRef(); for (int i = 0; i < fieldCount; i++) { string value = feat.GetFieldAsString(i); row[i] = value.Replace(",", ""); } OSGeo.OGR.wkbGeometryType goetype = geometry.GetGeometryType(); if (goetype == OSGeo.OGR.wkbGeometryType.wkbPoint) { double x = geometry.GetX(0); double y = geometry.GetY(0); row["X"] = x.ToString(); row["Y"] = y.ToString(); } else if (goetype == OSGeo.OGR.wkbGeometryType.wkbLineString) { string points = ""; for (int i = 0; i < geometry.GetPointCount(); i++) { double x = geometry.GetX(i); double y = geometry.GetY(i); points += x.ToString() + "|" + y.ToString() + ";"; } if (points != "") { points.Substring(0, points.Length - 1); } row["PATH"] = points; } else if (goetype == OSGeo.OGR.wkbGeometryType.wkbPolygon) { int count = geometry.GetGeometryCount(); string points = ""; for (int j = 0; j < count; j++) { Geometry geo = geometry.GetGeometryRef(j); for (int i = 0; i < geo.GetPointCount(); i++) { double x = geo.GetX(i); double y = geo.GetY(i); points += x.ToString() + "|" + y.ToString() + ";"; } if (points != "") { points.Substring(0, points.Length - 1); } points += "|"; } if (points != "") { points.Substring(0, points.Length - 1); } row["PATH"] = points; } } layer.Dispose(); ds.Dispose(); dr.Dispose(); return(dataTable); } catch { return(null); } }
public bool VectorFileCoordTransfrom(string fileName, string saveFileName, DelegateCoordsTransform deleCoordsTransfrom) { //注册所有驱动 Ogr.RegisterAll(); OSGeo.GDAL.Gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "NO"); //为支持属性表字段支持中文 OSGeo.GDAL.Gdal.SetConfigOption("SHAPE_ENCODING", ""); //开启日志 Gdal.SetConfigOption("CPL_DEBUG", "ON"); Gdal.SetConfigOption("CPL_LOG", System.IO.Directory.GetCurrentDirectory() + "\\gdallog.txt"); /** * 打开数据源 */ //--------------------------------------- //目标 string strDriverName = null; if (System.IO.Path.GetExtension(saveFileName).ToUpper().Equals(".TAB")) { strDriverName = "MapInfo File"; } if (System.IO.Path.GetExtension(saveFileName).ToUpper().Equals(".SHP")) { strDriverName = "ESRI Shapefile"; } OSGeo.OGR.Driver Tdriver = Ogr.GetDriverByName(strDriverName); if (Tdriver == null) { return(false); } string dir = System.IO.Path.GetDirectoryName(saveFileName); DataSource dsT = Tdriver.CreateDataSource(dir, null); if (dsT == null) { return(false); } //--------------------------------------- //源 DataSource dsS = Ogr.Open(fileName, 0); if (dsS == null) { return(false); } OSGeo.OGR.Driver Sdriver = dsS.GetDriver(); if (Sdriver == null) { return(false); } //------------------------------------------------- try { for (int iLayer = 0; iLayer < dsS.GetLayerCount(); iLayer++) { //获得图层信息 Layer layerS = dsS.GetLayerByIndex(iLayer); //创建图层 //图层名称 string saveName = System.IO.Path.GetFileNameWithoutExtension(saveFileName); Layer layerT = dsT.CreateLayer(saveName, layerS.GetSpatialRef(), layerS.GetGeomType(), null); if (layerS != null) { Feature pFeatureS; Feature pFeatureT; Geometry geomS, geomT; //地理要素 long countFeature = layerS.GetFeatureCount(0); FeatureDefn fd = layerS.GetLayerDefn(); //对目标图层进行属性定义 for (int i = 0; i < fd.GetFieldCount(); i++) { layerT.CreateField(fd.GetFieldDefn(i), 1); } fd.Dispose(); //释放资源 for (int i = 0; i < countFeature; i++) { pFeatureS = layerS.GetFeature(i); if (pFeatureS != null) { geomS = pFeatureS.GetGeometryRef(); geomT = GeometryCoordTransfrom2D(geomS, deleCoordsTransfrom); pFeatureT = pFeatureS.Clone(); pFeatureT.SetFrom(pFeatureS, 1); pFeatureT.SetGeometryDirectly(geomT); //newGeotry.Dispose(); layerT.CreateFeature(pFeatureT); geomS.Dispose(); geomT.Dispose(); pFeatureS.Dispose(); pFeatureT.Dispose(); //layerT.SetFeature(pFeatureT); //pFeature.Dispose(); } } //endfor } //endif layerS.Dispose(); layerT.Dispose(); }//endfor } catch (Exception ex) { throw new Exception(ex.Message); } dsS.Dispose(); dsT.Dispose(); return(true); }
private void button2_Click(object sender, EventArgs e) { OpenFileDialog dlg = new OpenFileDialog(); dlg.Title = "打开ShapeFile数据"; dlg.Filter = "ShapeFile数据(*.shp)|*.shp"; if (dlg.ShowDialog() == DialogResult.OK) { Ogr.RegisterAll(); string strVectorFile = dlg.FileName; textBox1.Text = strVectorFile; //打开数据 DataSource ds = Ogr.Open(strVectorFile, 0); if (ds == null) { listBox1.Items.Add(string.Format("打开文件【{0}】失败!", strVectorFile)); return; } listBox1.Items.Add(string.Format("打开文件【{0}】成功!", strVectorFile)); // 获取该数据源中的图层个数,一般shp数据图层只有一个,如果是mdb、dxf等图层就会有多个 int iLayerCount = ds.GetLayerCount(); // 获取第一个图层 Layer oLayer = ds.GetLayerByIndex(0); if (oLayer == null) { listBox1.Items.Add(string.Format("获取第{0}个图层失败!\n", 0)); return; } // 对图层进行初始化,如果对图层进行了过滤操作,执行这句后,之前的过滤全部清空 oLayer.ResetReading(); // 通过属性表的SQL语句对图层中的要素进行筛选,这部分详细参考SQL查询章节内容 //oLayer.SetAttributeFilter("\"NAME99\"LIKE \"北京市市辖区\""); // 通过指定的几何对象对图层中的要素进行筛选 //oLayer.SetSpatialFilter(); // 通过指定的四至范围对图层中的要素进行筛选 //oLayer.SetSpatialFilterRect(); // 获取图层中的属性表表头并输出 listBox1.Items.Add("属性表结构信息:"); FeatureDefn oDefn = oLayer.GetLayerDefn(); int iFieldCount = oDefn.GetFieldCount(); for (int iAttr = 0; iAttr < iFieldCount; iAttr++) { FieldDefn oField = oDefn.GetFieldDefn(iAttr); listBox1.Items.Add(string.Format("{0}:{1} ({2}.{3})", oField.GetNameRef(), oField.GetFieldTypeName(oField.GetFieldType()), oField.GetWidth(), oField.GetPrecision())); } // 输出图层中的要素个数 listBox1.Items.Add(string.Format("要素个数 = {0}", oLayer.GetFeatureCount(0))); Feature oFeature = null; // 下面开始遍历图层中的要素 while ((oFeature = oLayer.GetNextFeature()) != null) { Geometry geo = oFeature.GetGeometryRef(); wkbGeometryType wkb = geo.GetGeometryType(); listBox1.Items.Add(string.Format("当前处理第要素值:{0}", wkb.ToString())); string strGml = geo.ExportToGML(); listBox1.Items.Add(strGml); listBox1.Items.Add(string.Format("当前处理第{0}个: \n属性值:", oFeature.GetFID())); // 获取要素中的属性表内容 for (int iField = 0; iField < iFieldCount; iField++) { FieldDefn oFieldDefn = oDefn.GetFieldDefn(iField); FieldType type = oFieldDefn.GetFieldType(); switch (type) { case FieldType.OFTString: listBox1.Items.Add(string.Format("{0}\t", oFeature.GetFieldAsString(iField))); break; case FieldType.OFTReal: listBox1.Items.Add(string.Format("{0}\t", oFeature.GetFieldAsDouble(iField))); break; case FieldType.OFTInteger: listBox1.Items.Add(string.Format("{0}\t", oFeature.GetFieldAsInteger(iField))); break; default: listBox1.Items.Add(string.Format("{0}\t", oFeature.GetFieldAsString(iField))); break; } } // 获取要素中的几何体 Geometry oGeometry = oFeature.GetGeometryRef(); // 为了演示,只输出一个要素信息 break; } listBox1.Items.Add("数据集关闭!"); } }