コード例 #1
0
        /// <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();
            }
        }
コード例 #2
0
        /// <summary>
        /// Gest the Src WKT given the EPSG code
        /// </summary>
        /// <param name="EPSG"></param>
        public static string EPSG2WKT(int EPSG)
        {
            var src = new OSGeo.OSR.SpatialReference("");

            src.ImportFromEPSG(EPSG);
            src.ExportToWkt(out var proj_wkt, null);
            return(proj_wkt);
        }
コード例 #3
0
        /// <summary>
        /// 线声源离散
        /// </summary>
        /// <param name="sourcePath">声源路径</param>
        /// <param name="resultPath">离散后路径</param>
        /// <param name="splitLength">分割长度</param>
        /// <param name="timeType">时段</param>
        /// <param name="frequency">频率</param>
        /// <returns></returns>
        private Layer getSource()
        {
            String sourceResultPath = m_resultPath + "\\SourceTemp.shp";//输出路径

            // 写入文件
            OSGeo.OGR.Driver resultDriver = Ogr.GetDriverByName("ESRI Shapefile");

            // 创建数据源

            DataSource resultDataSource;

            if (Ogr.Open(sourceResultPath, 0) != null)
            {
                resultDataSource = Ogr.Open(sourceResultPath, 1);
                resultDataSource.DeleteLayer(0);
            }
            else
            {
                resultDataSource = resultDriver.CreateDataSource(sourceResultPath, null);
            }

            //投影信息
            OSGeo.OSR.SpatialReference projection = new OSGeo.OSR.SpatialReference("");
            projection.ImportFromEPSG(3395);

            //构建声源点图层
            Layer resultLayer = resultDataSource.CreateLayer("POINT", projection, wkbGeometryType.wkbPoint, null);

            //构建属性
            resultLayer.CreateField(new FieldDefn("HEIGHT_G", FieldType.OFTReal), 1);  //高度
            resultLayer.CreateField(new FieldDefn("PWLs", FieldType.OFTReal), 1);      //单一频率声功率级
            resultLayer.CreateField(new FieldDefn("FREQUENCY", FieldType.OFTReal), 1); //频率

            ISource    sourceBean = null;
            DataSource sourceDataSource;

            foreach (KeyValuePair <String, String> item in m_sourcePath)
            {
                switch (item.Key)
                {
                case "road":
                    sourceBean = new RoadSourrce();
                    break;

                case "rainway":
                    sourceBean = new RainwaySource();
                    break;

                case "subway":
                    sourceBean = new RoadSourrce();
                    break;
                }
                //源文件
                sourceDataSource = Ogr.Open(item.Value, 0);
                resultLayer      = sourceBean.getSource(sourceDataSource.GetLayerByIndex(0), resultLayer, m_splitLength, m_timeType, m_frequency);
            }
            return(resultLayer);
        }
コード例 #4
0
    public static string ToCoordinateSystem(string srs, bool isName)
    {
      if (string.IsNullOrEmpty(srs))
        return srs;

      string result = null;
      if (_srCache.TryGetValue(srs, out result))
        return result;

      using (SpatialReference sr = new SpatialReference(null))
      {
        if (isName)
        {
          int srsId;
          if (int.TryParse(srs, out srsId))
            sr.ImportFromEPSG(srsId);
          else
          {
            // TODO
          }
        }
        else
        {
          if (srs.StartsWith("+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0"))
          {   //      +proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs
              //sr.ImportFromProj4(srs);
            sr.ImportFromEPSG(900913);
          }
          else
          {
            sr.ImportFromProj4(srs);
          }
        }

        sr.ExportToWkt(out result);

        if (result != null)
          _srCache.TryAdd(srs, result);

        return result;
      }
    }
コード例 #5
0
        /// <summary>
        /// Reproject a raster.
        /// Working with errors
        /// </summary>
        /// <param name="InputFilePath"></param>
        /// <param name="OutputFilePath"></param>
        /// <param name="EPSG">output EPSG</param>
        public static void RasterReprojection(string InputFilePath, string OutputFilePath, int EPSG)
        {
            // TODO: Check for errors!
            var sr = new OSGeo.OSR.SpatialReference(null);

            sr.ImportFromEPSG(EPSG);
            sr.ExportToWkt(out var srs_wkt, null);

            // reproject raster and save to EHdr
            using (var srcDs = Gdal.Open(InputFilePath, Access.GA_ReadOnly))
                using (var vrt = Gdal.AutoCreateWarpedVRT(srcDs, srcDs.GetProjectionRef(), srs_wkt, ResampleAlg.GRA_Average, 0)) {
                    var OutDirver = srcDs.GetDriver();
                    OutDirver.CreateCopy(OutputFilePath, vrt, 1, null, GDalProgress, "Raster Reprojection");
                }
            //using( var MemDirver = Gdal.GetDriverByName("MEM"))

            //using( var bilDirver = srcDs.GetDriver() Gdal.GetDriverByName("EHdr"))
            //using( var bilfile = bilDirver.CreateCopy("lo que sea/asd/", vrt, 1, null,null, null))

            return;
        }
コード例 #6
0
ファイル: OgrProvider.cs プロジェクト: lishxi/_SharpMap
        /// <summary>
        /// Creates an OGR data source from a FeatureDataTable
        /// </summary>
        /// <param name="table">The name of the table</param>
        /// <param name="geometryType">The geometry type</param>
        /// <param name="driver">The driver</param>
        /// <param name="connection">The connection string</param>
        /// <param name="driverOptions">The options for the driver</param>
        /// <param name="layerOptions">The options for the layer</param>
        public static void CreateFromFeatureDataTable(FeatureDataTable table, 
            OgcGeometryType geometryType, int srid, string driver, string connection, string[] driverOptions = null, string[] layerOptions = null)
        {
            if (table == null)
                throw new ArgumentNullException("table");

            if (table.Rows.Count == 0)
                throw new ArgumentException("The table contains no rows", "table");

            if (geometryType < OgcGeometryType.Point || geometryType > OgcGeometryType.MultiPolygon)
                throw new ArgumentException("Invalid geometry type", "geometryType");

            if (string.IsNullOrWhiteSpace(driver))
                throw new ArgumentException("No driver specified", "driver");

            var dr = OSGeo.OGR.Ogr.GetDriverByName(driver);
            if (dr == null)
                throw new Exception(string.Format("Cannot load driver '{0}'!", driver));

            //if (!dr.TestCapability("ODrCCreateDataSource"))
            //    throw new Exception(string.Format("Driver '{0}' cannot create a data source!", driver));

            // Create the data source
            var ds = dr.CreateDataSource(connection, driverOptions);
            //if (!ds.TestCapability("ODsCCreateLayer"))
            //    throw new Exception(string.Format("Driver '{0}' cannot create a layer!", driver));

            // Create the spatial reference
            var sr = new OSGeo.OSR.SpatialReference(string.Empty);
            sr.ImportFromEPSG(srid);

            // Create the layer
            var lyr = ds.CreateLayer(table.TableName, sr, (OgrGeometryType)geometryType, layerOptions);
            sr.Dispose();

            //lyr.GetSpatialRef();
            foreach (System.Data.DataColumn dc in table.Columns)
            {
                using (var fldDef = GetFieldDefinition(dc))
                    lyr.CreateField(fldDef, 0);
            }

            using (var ld = lyr.GetLayerDefn())
            {
                foreach (FeatureDataRow fdr in table.Rows)
                {
                    if ((int)fdr.Geometry.OgcGeometryType != (int)geometryType)
                        continue;

                    using (var feature = new OgrFeature(ld))
                    {
                        feature.SetGeometry(OgrGeometry.CreateFromWkb(fdr.Geometry.AsBinary()));
                        var idx = -1;
                        foreach (System.Data.DataColumn dc in table.Columns)
                        {
                            idx++;
                            var fd = ld.GetFieldDefn(idx);
                            DateTime dt;
                            switch (fd.GetFieldType())
                            {
                                case OgrFieldType.OFTBinary:
                                    //Nothing
                                    break;
                                case OgrFieldType.OFTDate:
                                    dt = ((DateTime)fdr[dc]).Date;
                                    feature.SetField(idx, dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, 0);
                                    break;
                                case OgrFieldType.OFTDateTime:
                                    dt = (DateTime)fdr[dc];
                                    feature.SetField(idx, dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, 0);
                                    break;
                                case OgrFieldType.OFTTime:
                                    var tod = ((DateTime)fdr[dc]).TimeOfDay;
                                    feature.SetField(idx, 0, 0, 0, tod.Hours, tod.Minutes, tod.Seconds, 0);
                                    break;
                                case OgrFieldType.OFTInteger:
                                    feature.SetField(idx, Convert.ToInt32(fdr[dc]));
                                    break;
                                case OgrFieldType.OFTIntegerList:
                                    var il = GetIntegerList(fdr[dc], dc.DataType);
                                    feature.SetFieldIntegerList(idx, il.Length, il);
                                    break;
                                case OgrFieldType.OFTReal:
                                    feature.SetField(idx, Convert.ToDouble(fdr[dc]));
                                    break;
                                case OgrFieldType.OFTRealList:
                                    var dl = GetDoubleList(fdr[dc], dc.DataType);
                                    feature.SetFieldDoubleList(idx, dl.Length, dl);
                                    break;
                                case OgrFieldType.OFTString:
                                    feature.SetField(idx, Convert.ToString(fdr[dc]));
                                    break;
                                case OgrFieldType.OFTStringList:
                                    var sl = (string[])fdr[dc];
                                    feature.SetFieldStringList(idx, sl);
                                    break;

                            }
                            fd.Dispose();
                        }
                        lyr.CreateFeature(feature);
                        feature.Dispose();
                    }
                    //ld.Dispose();
                }
            }

            lyr.Dispose();
            ds.Dispose();
            dr.Dispose();
        }
コード例 #7
0
        public void testProjectionConvert()
        {
            Gdal.AllRegister();
            Gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES");
            Gdal.SetConfigOption("SHAPE_ENCODING", "");
            Ogr.RegisterAll();
            Gdal.SetConfigOption("GDAL_DATA", Environment.CurrentDirectory + "//data");
            //读取文件
            DataSource ds     = Ogr.Open(fromPath, 0);
            Layer      oLayer = ds.GetLayerByIndex(0);

            // 写入文件

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



            OSGeo.OSR.SpatialReference projection = new OSGeo.OSR.SpatialReference("");
            projection.ImportFromEPSG(3395);

            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", projection, oLayer.GetGeomType(), 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);

            OSGeo.OSR.CoordinateTransformation coordTrans = new OSGeo.OSR.CoordinateTransformation(oLayer.GetSpatialRef(), projection);



            while ((oFeature = oLayer.GetNextFeature()) != null)
            {
                lines = oFeature.GetGeometryRef();
                lines.Transform(coordTrans);

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

            oDS.SyncToDisk();
        }
コード例 #8
0
        /// <summary>
        /// Creates an OGR data source from a FeatureDataTable
        /// </summary>
        /// <param name="table">The name of the table</param>
        /// <param name="geometryType">The geometry type</param>
        /// <param name="driver">The driver</param>
        /// <param name="connection">The connection string</param>
        /// <param name="driverOptions">The options for the driver</param>
        /// <param name="layerOptions">The options for the layer</param>
        public static void CreateFromFeatureDataTable(FeatureDataTable table,
                                                      OgcGeometryType geometryType, int srid, string driver, string connection, string[] driverOptions = null, string[] layerOptions = null)
        {
            if (table == null)
            {
                throw new ArgumentNullException("table");
            }

            if (table.Rows.Count == 0)
            {
                throw new ArgumentException("The table contains no rows", "table");
            }

            if (geometryType < OgcGeometryType.Point || geometryType > OgcGeometryType.MultiPolygon)
            {
                throw new ArgumentException("Invalid geometry type", "geometryType");
            }

            if (string.IsNullOrWhiteSpace(driver))
            {
                throw new ArgumentException("No driver specified", "driver");
            }

            var dr = OSGeo.OGR.Ogr.GetDriverByName(driver);

            if (dr == null)
            {
                throw new Exception(string.Format("Cannot load driver '{0}'!", driver));
            }

            //if (!dr.TestCapability("ODrCCreateDataSource"))
            //    throw new Exception(string.Format("Driver '{0}' cannot create a data source!", driver));

            // Create the data source
            var ds = dr.CreateDataSource(connection, driverOptions);
            //if (!ds.TestCapability("ODsCCreateLayer"))
            //    throw new Exception(string.Format("Driver '{0}' cannot create a layer!", driver));

            // Create the spatial reference
            var sr = new OSGeo.OSR.SpatialReference(string.Empty);

            sr.ImportFromEPSG(srid);

            // Create the layer
            var lyr = ds.CreateLayer(table.TableName, sr, (OgrGeometryType)geometryType, layerOptions);

            sr.Dispose();

            //lyr.GetSpatialRef();
            foreach (System.Data.DataColumn dc in table.Columns)
            {
                using (var fldDef = GetFieldDefinition(dc))
                    lyr.CreateField(fldDef, 0);
            }

            using (var ld = lyr.GetLayerDefn())
            {
                foreach (FeatureDataRow fdr in table.Rows)
                {
                    if ((int)fdr.Geometry.OgcGeometryType != (int)geometryType)
                    {
                        continue;
                    }

                    using (var feature = new OgrFeature(ld))
                    {
                        feature.SetGeometry(OgrGeometry.CreateFromWkb(fdr.Geometry.AsBinary()));
                        var idx = -1;
                        foreach (System.Data.DataColumn dc in table.Columns)
                        {
                            idx++;
                            var      fd = ld.GetFieldDefn(idx);
                            DateTime dt;
                            switch (fd.GetFieldType())
                            {
                            case OgrFieldType.OFTBinary:
                                //Nothing
                                break;

                            case OgrFieldType.OFTDate:
                                dt = ((DateTime)fdr[dc]).Date;
                                feature.SetField(idx, dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, 0);
                                break;

                            case OgrFieldType.OFTDateTime:
                                dt = (DateTime)fdr[dc];
                                feature.SetField(idx, dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, 0);
                                break;

                            case OgrFieldType.OFTTime:
                                var tod = ((DateTime)fdr[dc]).TimeOfDay;
                                feature.SetField(idx, 0, 0, 0, tod.Hours, tod.Minutes, tod.Seconds, 0);
                                break;

                            case OgrFieldType.OFTInteger:
                                feature.SetField(idx, Convert.ToInt32(fdr[dc]));
                                break;

                            case OgrFieldType.OFTIntegerList:
                                var il = GetIntegerList(fdr[dc], dc.DataType);
                                feature.SetFieldIntegerList(idx, il.Length, il);
                                break;

                            case OgrFieldType.OFTReal:
                                feature.SetField(idx, Convert.ToDouble(fdr[dc]));
                                break;

                            case OgrFieldType.OFTRealList:
                                var dl = GetDoubleList(fdr[dc], dc.DataType);
                                feature.SetFieldDoubleList(idx, dl.Length, dl);
                                break;

                            case OgrFieldType.OFTString:
                                feature.SetField(idx, Convert.ToString(fdr[dc]));
                                break;

                            case OgrFieldType.OFTStringList:
                                var sl = (string[])fdr[dc];
                                feature.SetFieldStringList(idx, sl);
                                break;
                            }
                            fd.Dispose();
                        }
                        lyr.CreateFeature(feature);
                        feature.Dispose();
                    }
                    //ld.Dispose();
                }
            }

            lyr.Dispose();
            ds.Dispose();
            dr.Dispose();
        }
コード例 #9
0
ファイル: Class1.cs プロジェクト: sxlffxj/NoiseAnalysis
        public void readLayerTest(string strVectorFile)
        {
            Gdal.AllRegister();
            //为了支持中文路径,请添加下面这句代码
            Gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES");
            //为了使属性表字段支持中文,请添加下面这句
            Gdal.SetConfigOption("SHAPE_ENCODING", "");


            // 注册所有的驱动
            Ogr.RegisterAll();
            Gdal.SetConfigOption("GDAL_DATA", "E://lib//gdal//gdal1.9//data");

            //打开数据
            DataSource ds = Ogr.Open(strVectorFile, 0);



            if (ds == null)
            {
                Console.WriteLine("打开文件【{0}】失败!", strVectorFile);
                return;
            }
            Console.WriteLine("打开文件【{0}】成功!", strVectorFile);


            // 获取该数据源中的图层个数,一般shp数据图层只有一个,如果是mdb、dxf等图层就会有多个
            int iLayerCount = ds.GetLayerCount();

            // 获取第一个图层
            Layer oLayer = ds.GetLayerByIndex(0);


            String c = "";

            oLayer.GetSpatialRef().AutoIdentifyEPSG();

            Console.WriteLine(oLayer.GetSpatialRef().AutoIdentifyEPSG());


            OSGeo.OSR.SpatialReference spa = oLayer.GetSpatialRef();
            // if (spa==null)
            // {
            spa = new OSGeo.OSR.SpatialReference(null);
            spa.ImportFromEPSG(3395);


            spa.ExportToWkt(out c);
            Console.WriteLine(c);

            return;


            // }
            //  String a = "";
            // spa.EPSGTreatsAsLatLong();
            // Console.WriteLine(spa.ExportToWkt(out a));

            // oLayer.GetSpatialRef().ExportToWkt(out a);

            // Console.WriteLine(spa.GetProjParm(out a));

            // Console.WriteLine(oLayer.GetSpatialRef().GetLinearUnitsName());
            if (oLayer == null)
            {
                Console.WriteLine("获取第{0}个图层失败!\n", 0);
                return;
            }

            // 对图层进行初始化,如果对图层进行了过滤操作,执行这句后,之前的过滤全部清空
            oLayer.ResetReading();

            // 通过属性表的SQL语句对图层中的要素进行筛选,这部分详细参考SQL查询章节内容
            //  oLayer.SetAttributeFilter("\"NAME99\"LIKE \"北京市市辖区\"");

            // 通过指定的几何对象对图层中的要素进行筛选
            //oLayer.SetSpatialFilter();

            // 通过指定的四至范围对图层中的要素进行筛选
            //oLayer.SetSpatialFilterRect();

            // 获取图层中的属性表表头并输出
            // Console.WriteLine("属性表结构信息:");
            FeatureDefn oDefn       = oLayer.GetLayerDefn();
            int         iFieldCount = oDefn.GetFieldCount();

            for (int iAttr = 0; iAttr < iFieldCount; iAttr++)
            {
                FieldDefn oField = oDefn.GetFieldDefn(iAttr);

                Console.WriteLine("{0}:{1} ({2}.{3})", oField.GetNameRef(),
                                  oField.GetFieldTypeName(oField.GetFieldType()),
                                  oField.GetWidth(), oField.GetPrecision());
            }

            // 输出图层中的要素个数
            Console.WriteLine("要素个数 = {0}", oLayer.GetFeatureCount(0));

            Feature oFeature = null;

            // 下面开始遍历图层中的要素
            while ((oFeature = oLayer.GetNextFeature()) != null)
            {
                Console.WriteLine("当前处理第{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:
                        Console.WriteLine("{0}\t", oFeature.GetFieldAsString(iField));
                        break;

                    case FieldType.OFTReal:
                        Console.WriteLine("{0}\t", oFeature.GetFieldAsDouble(iField));
                        break;

                    case FieldType.OFTInteger:
                        Console.WriteLine("{0}\t", oFeature.GetFieldAsInteger(iField));
                        break;

                    default:
                        Console.WriteLine("{0}\t", oFeature.GetFieldAsString(iField));
                        break;
                    }
                }

                // 获取要素中的几何体
                Geometry oGeometry = oFeature.GetGeometryRef();

                //  String a=oGeometry.GetGeometryName();
                //  String b = "";
                //  oGeometry.ExportToWkt(out b);
                Console.WriteLine(oGeometry.GetGeometryName());
                // 为了演示,只输出一个要素信息
                break;
            }

            Console.WriteLine("数据集关闭!");
            Console.ReadLine();
        }