Esempio n. 1
0
        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数据集关闭!";
        }
Esempio n. 2
0
        private DataTable BuildSchemaTable()
        {
            _schemaTable        = new DataTable("SchemaTable");
            _schemaTable.Locale = CultureInfo.InvariantCulture;

            AddDataColumn(_schemaTable, SchemaTableColumn.ColumnName, typeof(string));
            AddDataColumn(_schemaTable, SchemaTableColumn.ColumnOrdinal, typeof(int));
            AddDataColumn(_schemaTable, SchemaTableColumn.ColumnSize, typeof(int), -1);
            AddDataColumn(_schemaTable, SchemaTableColumn.NumericPrecision, typeof(short));
            AddDataColumn(_schemaTable, SchemaTableColumn.NumericScale, typeof(short));
            AddDataColumn(_schemaTable, SchemaTableColumn.DataType, typeof(Type));
            AddDataColumn(_schemaTable, SchemaTableColumn.ProviderType, typeof(int));
            AddDataColumn(_schemaTable, SchemaTableColumn.IsLong, typeof(bool), false);
            AddDataColumn(_schemaTable, SchemaTableColumn.AllowDBNull, typeof(bool), true);
            AddDataColumn(_schemaTable, SchemaTableColumn.IsUnique, typeof(bool), false);
            AddDataColumn(_schemaTable, SchemaTableColumn.IsKey, typeof(bool), false);
            AddDataColumn(_schemaTable, SchemaTableColumn.BaseSchemaName, typeof(string));
            AddDataColumn(_schemaTable, SchemaTableColumn.BaseTableName, typeof(string), String.Empty);
            AddDataColumn(_schemaTable, SchemaTableColumn.BaseColumnName, typeof(string));

            AddDataRow(_schemaTable, GeometryFieldName, GeometryFieldOrdinal, 1, typeof(byte[]), true, false, false);
            AddDataRow(_schemaTable, FidFieldName, FidFieldOrdinal, 1, typeof(long), false, true, true);

            for (int i = 0; i < _iFieldCount; i++)
            {
                FieldDefn f = _ogrFeatureDefinition.GetFieldDefn(i);

                AddDataRow(_schemaTable, f.GetName(), i + 2, f.GetWidth(), TranslateOgrType(f.GetFieldType()), true, false, false);
            }

            _schemaTable.AcceptChanges();

            return(_schemaTable);
        }
        /// <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();
            }
        }
Esempio n. 4
0
        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);
        }
Esempio n. 5
0
        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();              //释放对象
            }
        }
Esempio n. 6
0
        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() + ")");
            }
        }
Esempio n. 7
0
        private void createExporterFieldDefns(List <TypeAndName> fields)
        {
            FieldDefn fieldDefn;

            exporterFeatDefn = new FeatureDefn("ok");
            for (int i = 0; i < fields.Count; i++)
            {
                var field = fields[i];
                switch (field.TypeDef.ToString())
                {
                case "System.Int32":
                    fieldDefn = new FieldDefn(field.Name, FieldType.OFTInteger);
                    break;

                case "System.DateTime":
                    fieldDefn = new FieldDefn(field.Name, FieldType.OFTString);
                    //fieldDefn = new FieldDefn(field.Name, FieldType.OFTDateTime);
                    break;

                case "System.Double":
                    fieldDefn = new FieldDefn(field.Name, FieldType.OFTReal);
                    break;

                case "System.String":
                default:
                    fieldDefn = new FieldDefn(field.Name, FieldType.OFTString);
                    break;
                }
                exporterLayer.CreateField(fieldDefn, 1);
                exporterFeatDefn.AddFieldDefn(fieldDefn);
                fieldDefn.Dispose();
            }
        }
Esempio n. 8
0
        public static Dictionary <string, object> GetAll(this Feature feature)
        {
            Dictionary <string, object> ret = new Dictionary <string, object>();

            if (feature != null)
            {
                int fieldCount = feature.GetFieldCount();
                for (int i = 0; i < fieldCount; i++)
                {
                    FieldDefn fd    = feature.GetFieldDefnRef(i);
                    string    key   = fd.GetName();
                    object    value = null;
                    FieldType ft    = fd.GetFieldType();
                    switch (ft)
                    {
                    case FieldType.OFTString:
                        value = feature.GetFieldAsString(i);
                        break;

                    case FieldType.OFTReal:
                        value = feature.GetFieldAsDouble(i);
                        break;

                    case FieldType.OFTInteger:
                        value = feature.GetFieldAsInteger(i);
                        break;
                    }
                    ret.Add(key, value);
                }
            }
            return(ret);
        }
Esempio n. 9
0
        public static void _Polygong节点转为ShpPoint(Feature aPoly, string outFile)
        {
            OSGeo.OGR.Geometry geom    = aPoly.GetGeometryRef();
            OSGeo.OGR.Geometry subGeom = geom.GetGeometryRef(0);

            Driver     dr            = Ogr.GetDriverByName("ESRI shapefile");
            DataSource outDS         = dr.CreateDataSource(outFile, null);
            Layer      outLayer      = outDS.CreateLayer("toPoint", null, wkbGeometryType.wkbPoint25D, null);
            FieldDefn  pointID       = new FieldDefn("FeatID", FieldType.OFTReal);
            FieldDefn  cutField      = new FieldDefn("CUT", FieldType.OFTReal);
            FieldDefn  straightField = new FieldDefn("STRAIGHT", FieldType.OFTInteger);

            outLayer.CreateField(pointID, 1);
            outLayer.CreateField(cutField, 1);
            outLayer.CreateField(straightField, 1);

            int pointCount = subGeom.GetPointCount();

            for (int i = 0; i < pointCount; i++)
            {
                Feature  pFeat = new Feature(new FeatureDefn(""));
                Geometry pGeom = new Geometry(wkbGeometryType.wkbPoint);
                pGeom.AddPoint_2D(subGeom.GetX(i), subGeom.GetY(i));
                pFeat.SetGeometry(pGeom);
                outLayer.CreateFeature(pFeat);
                pGeom.Dispose();
                pFeat.Dispose();
            }
            outLayer.Dispose();
            outDS.Dispose();
        }
Esempio n. 10
0
        public static object Get(this Feature feature, string name)
        {
            int    fieldCount = feature.GetFieldCount();
            object ret        = null;

            for (int i = 0; i < fieldCount; i++)
            {
                FieldDefn fd = feature.GetFieldDefnRef(i);
                if (fd.GetName() == name)
                {
                    FieldType ft = fd.GetFieldType();
                    switch (ft)
                    {
                    case FieldType.OFTString:
                        ret = feature.GetFieldAsString(i);
                        break;

                    case FieldType.OFTReal:
                        ret = feature.GetFieldAsDouble(i);
                        break;

                    case FieldType.OFTInteger:
                        ret = feature.GetFieldAsInteger(i);
                        break;
                    }
                }
            }
            return(ret);
        }
Esempio n. 11
0
    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);
    }
Esempio n. 12
0
 public void addField(FieldDefn f)
 {
     if (_fieldList == null)
     {
         _fieldList = new List <FieldDefn>();
     }
     _fieldList.Add(f);
 }
Esempio n. 13
0
 public void addElement(FieldDefn f)
 {
     if (_elementList == null)
     {
         _elementList = new List <FieldDefn>();
     }
     _elementList.Add(f);
 }
Esempio n. 14
0
        public void testStaticPartition()
        {
            Gdal.AllRegister();
            Gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES");
            Gdal.SetConfigOption("SHAPE_ENCODING", "");
            Ogr.RegisterAll();

            //读取文件
            DataSource ds     = Ogr.Open(fromPath, 0);
            Layer      oLayer = ds.GetLayerByIndex(0);

            // 写入文件

            OSGeo.OGR.Driver oDriver = Ogr.GetDriverByName("ESRI Shapefile");

            // 创建数据源

            DataSource oDS;

            if (Ogr.Open(toPath, 0) != null)
            {
                oDS = Ogr.Open(toPath, 1);
                oDS.DeleteLayer(0);
            }
            else
            {
                oDS = oDriver.CreateDataSource(toPath, null);
            }


            Layer       toLayer  = oDS.CreateLayer("POINT", oLayer.GetSpatialRef(), wkbGeometryType.wkbPoint, null);
            Random      ran      = new Random();
            Feature     oFeature = null;
            Geometry    lines    = null;
            FeatureDefn oDefn    = oLayer.GetLayerDefn();

            FieldDefn oFieldID = new FieldDefn("HEIGHT_G", FieldType.OFTReal);

            toLayer.CreateField(oFieldID, 1);

            FieldDefn oFieldName = new FieldDefn("PWLs", FieldType.OFTReal);

            toLayer.CreateField(oFieldName, 1);

            while ((oFeature = oLayer.GetNextFeature()) != null)
            {
                //read current feature

                lines = oFeature.GetGeometryRef();
                Feature feature = new Feature(oDefn);
                feature.SetGeometry(Line.getPoint(lines, lines.Centroid()));
                feature.SetField(0, 4.0);
                feature.SetField(1, ran.Next(40, 120));
                toLayer.CreateFeature(feature);
            }

            oDS.SyncToDisk();
        }
Esempio n. 15
0
        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);
        }
Esempio n. 16
0
        public void AddFieldDate(string name)
        {
            FieldDefn fdefn = new FieldDefn(name, FieldType.OFTDate);

            if (_layer.CreateField(fdefn, 1) != 0)
            {
                throw new Exception("Nie można utworzyć pola " + name);
            }
        }
Esempio n. 17
0
        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);
        }
Esempio n. 18
0
        public static MG_Field AsField(FieldDefn f)
        {
            MG_Field mgField = new MG_Field();

            mgField.Name      = f.GetNameRef();                  //collect data
            mgField.Type      = AsFieldDBType(f.GetFieldType()); //collect data
            mgField.Width     = f.GetWidth();                    //collect data
            mgField.Precision = f.GetPrecision();                //collect data
            return(mgField);
        }
Esempio n. 19
0
        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();
        }
Esempio n. 20
0
        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);
            }
        }
Esempio n. 21
0
        public static MG_Feature AsFeature(Feature f)
        {
            FeatureDefn def       = f.GetDefnRef();
            MG_FieldSet fieldSet  = AsFieldSet(def);
            MG_Feature  mgFeature = new MG_Feature(fieldSet);//collect data

            // geometry
            Geometry    g        = f.GetGeometryRef();
            MG_Geometry geometry = AsGeometry(g);
            string      wkt      = geometry.AsWKT(); // Test

            mgFeature.SetGeometry(geometry);         //collect data

            // symbol
            string styleString = f.GetStyleString();
            //f.SetStyleString(styleString);

            // attribute value
            MG_ValueSet valueSet    = new MG_ValueSet();
            int         fid         = f.GetFID();
            int         nFieldCount = f.GetFieldCount();

            for (int iField = 0; iField < nFieldCount; iField++)
            {
                FieldDefn fdef      = def.GetFieldDefn(iField);
                FieldType fieldType = fdef.GetFieldType();//OFTInteger OFTString OFTString

                MG_Value mgValue = new MG_Value();
                mgValue.Index = iField;// collect data
                //collect data
                if (fieldType == FieldType.OFTString)
                {
                    mgValue.Value = f.GetFieldAsString(iField);
                }
                else if (fieldType == FieldType.OFTInteger)
                {
                    mgValue.Value = f.GetFieldAsInteger(iField);
                }
                else if (fieldType == FieldType.OFTReal)
                {
                    mgValue.Value = f.GetFieldAsDouble(iField);
                }
                else if (fieldType == FieldType.OFTDateTime)
                {
                    int year, month, day, hour, minute, second, flag;
                    f.GetFieldAsDateTime(iField, out year, out month, out day, out hour, out minute, out second, out flag);
                    mgValue.Value = new DateTime(year, month, day, hour, minute, second, flag);
                }
                valueSet.Add(mgValue);
            }
            mgFeature.ValueSet = valueSet;//collect data

            return(mgFeature);
        }
Esempio n. 22
0
        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);
            }
        }
Esempio n. 23
0
        public static FeatureDefn ToFeatureDefn(MG_FieldSet fieldSet)
        {
            FeatureDefn def = new FeatureDefn(null);

            for (int i = 0; i < fieldSet.Count(); i++)
            {
                MG_Field  field = fieldSet.GetAt(i);
                FieldDefn fdef  = ToFieldDefn(field);
                def.AddFieldDefn(fdef);
            }
            return(def);
        }
Esempio n. 24
0
        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);
        }
Esempio n. 25
0
        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-");
            }
        }
        /// <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);
        }
        // the field names in shapefile have limit of 10 characteres
        private string getValidFieldName(FieldDefn fieldDefn)
        {
            string fieldName = fieldDefn.GetName();

            //string valuname = fieldDefn.GetDefault();
            //var valuname1 = fieldDefn.GetFieldType();
            //var valuname2 = fieldDefn.GetJustify();
            //string valuname3 = fieldDefn.GetTypeName();
            //string valuname4 = fieldDefn.GetNameRef();
            //var valuname5 = fieldDefn.GetSubType();
            //var valuname6 = fieldDefn.GetType();
            return(fieldName.Length > 10 ? fieldName.Substring(0, 10) : fieldName);
        }
Esempio n. 28
0
        /// <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);
        }
Esempio n. 29
0
        public static void CreateShapeFile(MG_Layer mgLayer, string filePath)
        {
            string dataSourceName = filePath;
            string layerName      = Path.GetFileNameWithoutExtension(filePath);

            mgLayer.SetLayerPath(filePath);
            try
            {
                Ogr.RegisterAll();
                string driverName = "ESRI Shapefile";
                Driver driver     = Ogr.GetDriverByName(driverName);

                if (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[] { });
                wkbGeometryType gt    = TowkbGeometryType(mgLayer.Type);// retrieve data
                Layer           layer = ds.CreateLayer(layerName, null, gt, new string[] { });
                // create three files  xxx.shp xxx.dbf xxx.shx

                // fieldset
                int fieldCount = mgLayer.FieldSet.Count();
                for (int i = 0; i < fieldCount; i++)
                {
                    MG_Field  field = mgLayer.FieldSet.GetAt(i);
                    FieldDefn def   = ToFieldDefn(field);
                    layer.CreateField(def, 1);
                }

                // feature
                int featureCount = mgLayer.GetFeatureCount();
                for (int i = 0; i < featureCount; i++)
                {
                    Feature f = ToFeature(mgLayer.GetFeature(i));
                    layer.CreateFeature(f);
                    f.Dispose();
                }

                // flush data to file
                layer.Dispose();
                ds.Dispose();
                driver.Dispose();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
Esempio n. 30
0
        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);
        }