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;
      }
    }
Esempio n. 2
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <Curve> boundary = new List <Curve>();

            DA.GetDataList <Curve>(0, boundary);

            string shpFileLoc = "";

            DA.GetData <string>("Shapefile Location", ref shpFileLoc);

            ////int SRef = 3857;
            GdalConfiguration.ConfigureOgr();
            GdalConfiguration.ConfigureGdal();

            OSGeo.OGR.Driver     drv = OSGeo.OGR.Ogr.GetDriverByName("ESRI Shapefile");
            OSGeo.OGR.DataSource ds  = OSGeo.OGR.Ogr.Open(shpFileLoc, 0);

            List <OSGeo.OGR.Layer> layerset = new List <OSGeo.OGR.Layer>();
            List <int>             fc       = new List <int>();

            for (int iLayer = 0; iLayer < ds.GetLayerCount(); iLayer++)
            {
                OSGeo.OGR.Layer layer = ds.GetLayerByIndex(iLayer);

                if (layer == null)
                {
                    Console.WriteLine("FAILURE: Couldn't fetch advertised layer " + iLayer);
                    System.Environment.Exit(-1);
                }
                long count        = layer.GetFeatureCount(1);
                int  featureCount = System.Convert.ToInt32(count);
                fc.Add(featureCount);
                layerset.Add(layer);
            }

            //Get OGR envelope of Shapefile
            OSGeo.OGR.Envelope ext = new OSGeo.OGR.Envelope();
            layerset[0].GetExtent(ext, 1);
            Point3d extMin = new Point3d();
            Point3d extMax = new Point3d();

            extMin.X = ext.MinX;
            extMin.Y = ext.MinY;
            extMax.X = ext.MaxX;
            extMax.Y = ext.MaxY;

            OSGeo.OSR.SpatialReference sr = layerset[0].GetSpatialRef();

            OSGeo.OSR.SpatialReference dst = new OSGeo.OSR.SpatialReference("");
            dst.SetWellKnownGeogCS("WGS84");

            //Get the spatial refernce of the input Shapefile
            string sRef;

            sr.ExportToWkt(out sRef);

            OSGeo.OSR.CoordinateTransformation coordTransform = new OSGeo.OSR.CoordinateTransformation(sr, dst);
            OSGeo.OSR.CoordinateTransformation revTransform   = new OSGeo.OSR.CoordinateTransformation(dst, sr);

            //Get bounding box of data in Shapefile
            double[] extMinPT = new double[3] {
                extMin.X, extMin.Y, extMin.Z
            };
            double[] extMaxPT = new double[3] {
                extMax.X, extMax.Y, extMax.Z
            };
            coordTransform.TransformPoint(extMinPT);
            coordTransform.TransformPoint(extMaxPT);
            Point3d     extPTmin = new Point3d(extMinPT[0], extMinPT[1], extMinPT[2]);
            Point3d     extPTmax = new Point3d(extMaxPT[0], extMaxPT[1], extMaxPT[2]);
            Rectangle3d rec      = new Rectangle3d(Plane.WorldXY, Heron.Convert.ToXYZ(extPTmin), Heron.Convert.ToXYZ(extPTmax));

            //Declare trees
            GH_Structure <GH_String> fset    = new GH_Structure <GH_String>();
            GH_Structure <GH_Point>  gset    = new GH_Structure <GH_Point>();
            GH_Structure <GH_String> layname = new GH_Structure <GH_String>();

            OSGeo.OGR.FeatureDefn def = layerset[0].GetLayerDefn();

            //Loop through input boundaries
            for (int i = 0; i < boundary.Count; i++)
            {
                if (rec.BoundingBox.Contains(boundary[i].GetBoundingBox(true).Min) && (rec.BoundingBox.Contains(boundary[i].GetBoundingBox(true).Max)))
                {
                    //Create bounding box for clipping geometry
                    Point3d  min   = Heron.Convert.ToWGS(boundary[i].GetBoundingBox(true).Min);
                    Point3d  max   = Heron.Convert.ToWGS(boundary[i].GetBoundingBox(true).Max);
                    double[] minpT = new double[3];
                    double[] maxpT = new double[3];

                    minpT[0] = min.X;
                    minpT[1] = min.Y;
                    minpT[2] = min.Z;
                    maxpT[0] = max.X;
                    maxpT[1] = max.Y;
                    maxpT[2] = max.Z;
                    revTransform.TransformPoint(minpT);
                    revTransform.TransformPoint(maxpT);

                    OSGeo.OGR.Geometry bbox  = OSGeo.OGR.Geometry.CreateFromWkt("POLYGON((" + min.X + " " + min.Y + ", " + min.X + " " + max.Y + ", " + max.X + " " + max.Y + ", " + max.X + " " + min.Y + ", " + min.X + " " + min.Y + "))");
                    OSGeo.OGR.Geometry ebbox = OSGeo.OGR.Geometry.CreateFromWkt("POLYGON((" + minpT[0] + " " + minpT[1] + ", " + minpT[0] + " " + maxpT[1] + ", " + maxpT[0] + " " + maxpT[1] + ", " + maxpT[0] + " " + minpT[1] + ", " + minpT[0] + " " + minpT[1] + "))");

                    //Clip Shapefile
                    //http://pcjericks.github.io/py-gdalogr-cookbook/vector_layers.html
                    OSGeo.OGR.Layer clipped_layer = layerset[0];
                    clipped_layer.SetSpatialFilter(ebbox);

                    //Loop through geometry
                    OSGeo.OGR.Feature feat;
                    def = clipped_layer.GetLayerDefn();

                    int m = 0;
                    while ((feat = layerset[0].GetNextFeature()) != null)
                    {
                        if (feat.GetGeometryRef() != null)
                        {
                            //Get geometry points and field values
                            OSGeo.OGR.Geometry geom = feat.GetGeometryRef();
                            OSGeo.OGR.Geometry sub_geom;

                            //Start get points if open polylines and points
                            for (int gpc = 0; gpc < geom.GetPointCount(); gpc++)
                            { //Loop through geometry points
                                double[] pT = new double[3];
                                pT[0] = geom.GetX(gpc);
                                pT[1] = geom.GetY(gpc);
                                pT[2] = geom.GetZ(gpc);
                                if (Double.IsNaN(geom.GetZ(gpc)))
                                {
                                    pT[2] = 0;
                                }
                                coordTransform.TransformPoint(pT);

                                Point3d pt3D = new Point3d();
                                pt3D.X = pT[0];
                                pt3D.Y = pT[1];
                                pt3D.Z = pT[2];

                                gset.Append(new GH_Point(Heron.Convert.ToXYZ(pt3D)), new GH_Path(i, m));
                                //End loop through geometry points

                                // Get Feature Values
                                if (fset.PathExists(new GH_Path(i, m)))
                                {
                                    fset.get_Branch(new GH_Path(i, m)).Clear();
                                }
                                for (int iField = 0; iField < feat.GetFieldCount(); iField++)
                                {
                                    OSGeo.OGR.FieldDefn fdef = def.GetFieldDefn(iField);
                                    if (feat.IsFieldSet(iField))
                                    {
                                        fset.Append(new GH_String(feat.GetFieldAsString(iField)), new GH_Path(i, m));
                                    }
                                    else
                                    {
                                        fset.Append(new GH_String("null"), new GH_Path(i, m));
                                    }
                                }
                                //End Get Feature Values
                            }
                            //End getting points if open polylines or points

                            //Start getting points if closed polylines and multipolygons
                            for (int gi = 0; gi < geom.GetGeometryCount(); gi++)
                            {
                                sub_geom = geom.GetGeometryRef(gi);
                                List <Point3d> geom_list = new List <Point3d>();

                                for (int ptnum = 0; ptnum < sub_geom.GetPointCount(); ptnum++)
                                {
                                    //Loop through geometry points
                                    double[] pT = new double[3];
                                    pT[0] = sub_geom.GetX(ptnum);
                                    pT[1] = sub_geom.GetY(ptnum);
                                    pT[2] = sub_geom.GetZ(ptnum);
                                    coordTransform.TransformPoint(pT);

                                    Point3d pt3D = new Point3d();
                                    pt3D.X = pT[0];
                                    pt3D.Y = pT[1];
                                    pt3D.Z = pT[2];

                                    gset.Append(new GH_Point(Heron.Convert.ToXYZ(pt3D)), new GH_Path(i, m, gi));
                                    //End loop through geometry points

                                    // Get Feature Values
                                    if (fset.PathExists(new GH_Path(i, m)))
                                    {
                                        fset.get_Branch(new GH_Path(i, m)).Clear();
                                    }
                                    for (int iField = 0; iField < feat.GetFieldCount(); iField++)
                                    {
                                        OSGeo.OGR.FieldDefn fdef = def.GetFieldDefn(iField);
                                        if (feat.IsFieldSet(iField))
                                        {
                                            fset.Append(new GH_String(feat.GetFieldAsString(iField)), new GH_Path(i, m));
                                        }
                                        else
                                        {
                                            fset.Append(new GH_String("null"), new GH_Path(i, m));
                                        }
                                    }
                                    //End Get Feature Values
                                }
                                //End getting points from closed polylines
                            }
                            m++;
                        }
                        feat.Dispose();
                    }
                }
                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "One or more boundaries may be outside the bounds of the Shapefile dataset.");
                    //return;
                }
            }

            //Get the field names
            List <string> fieldnames = new List <string>();

            for (int iAttr = 0; iAttr < def.GetFieldCount(); iAttr++)
            {
                OSGeo.OGR.FieldDefn fdef = def.GetFieldDefn(iAttr);
                fieldnames.Add(fdef.GetNameRef());
            }

            DA.SetData(0, def.GetName());
            DA.SetDataList(1, fc);
            DA.SetData(2, rec);
            DA.SetData(3, sRef);
            DA.SetDataList(4, fieldnames);
            DA.SetDataTree(5, fset);
            DA.SetDataTree(6, gset);
        }
Esempio n. 3
0
        public static void Rasterize(string inputFeature, string referRaster, string outRaster, string fieldName = "")
        {
            //Register the raster drivers
            Gdal.AllRegister();
            //Register the vector drivers
            Ogr.RegisterAll();
            //Open referRaster
            Dataset _referRaster = Gdal.Open(referRaster, Access.GA_ReadOnly);

            //Get geoTransform Args
            double[] _geoTransform = new double[6];
            _referRaster.GetGeoTransform(_geoTransform);
            // Define pixel_size and NoData value of new raster
            //int rasterCellSize = cellSize;
            double _xCellSize = _geoTransform[1];
            double _yCellSize = -_geoTransform[5];

            const double noDataValue      = -10000;
            string       outputRasterFile = outRaster;

            //Reading the vector data
            DataSource dataSource = Ogr.Open(inputFeature, 0);
            Layer      layer      = dataSource.GetLayerByIndex(0);
            Envelope   envelope   = new Envelope();

            layer.GetExtent(envelope, 0);
            //Compute the out raster cell resolutions
            int x_res = _referRaster.RasterXSize;
            int y_res = _referRaster.RasterYSize;

            //Console.WriteLine("Extent: " + envelope.MaxX + " " + envelope.MinX + " " + envelope.MaxY + " " + envelope.MinY);
            //Console.WriteLine("X resolution: " + x_res);
            //Console.WriteLine("X resolution: " + y_res);

            //Check if output raster exists & delete (optional)
            if (File.Exists(outputRasterFile))
            {
                File.Delete(outputRasterFile);
            }
            //Create new tiff
            DataType dType = _referRaster.GetRasterBand(1).DataType;

            //OSGeo.GDAL.Driver outputDriver = Gdal.GetDriverByName("GTiff");
            OSGeo.GDAL.Driver outputDriver = Gdal.GetDriverByName("HFA");

            Dataset outputDataset = outputDriver.Create(outputRasterFile, x_res, y_res, 1, dType, null);
            //Extrac srs from input feature
            string inputShapeSrs;

            OSGeo.OSR.SpatialReference spatialRefrence = layer.GetSpatialRef();
            if (spatialRefrence != null)
            {
                spatialRefrence.ExportToWkt(out inputShapeSrs);
                //Assign input feature srs to outpur raster
                outputDataset.SetProjection(inputShapeSrs);
            }
            //Geotransform
            outputDataset.SetGeoTransform(_geoTransform);
            //Set no data
            Band band = outputDataset.GetRasterBand(1);

            band.SetNoDataValue(noDataValue);
            //close tiff
            outputDataset.FlushCache();
            outputDataset.Dispose();
            //Feature to raster rasterize layer options
            //No of bands (1)
            int[] bandlist = new int[] { 1 };
            //Values to be burn on raster (10.0)
            double[] burnValues = new double[] { 10.0 };
            Dataset  myDataset  = Gdal.Open(outputRasterFile, Access.GA_Update);

            //additional options
            string[] rasterizeOptions;
            //rasterizeOptions = new string[] { "ALL_TOUCHED=TRUE", "ATTRIBUTE=" + fieldName }; //To set all touched pixels into raster pixel
            //rasterizeOptions = new string[] { "ATTRIBUTE=" + fieldName };
            rasterizeOptions = new string[] { };
            //Rasterize layer
            //Gdal.RasterizeLayer(myDataset, 1, bandlist, layer, IntPtr.Zero, IntPtr.Zero, 1, burnValues, null, null, null); // To burn the given burn values instead of feature attributes
            //Gdal.RasterizeLayer(myDataset, 1, bandlist, layer, IntPtr.Zero, IntPtr.Zero, 1, burnValues, rasterizeOptions, new Gdal.GDALProgressFuncDelegate(ProgressFunc), "Raster conversion");
            Gdal.RasterizeLayer(
                myDataset, //NEW inDS
                1,         //BAND
                bandlist,  //int[] bandlist = new int[] { 1 };Band数量
                layer,     // 待转
                IntPtr.Zero,
                IntPtr.Zero,
                1,
                burnValues, //Values to be burn on raster (10.0)
                rasterizeOptions,
                new Gdal.GDALProgressFuncDelegate(ProgressFunc),
                "Raster conversion"
                );
            myDataset.FlushCache();
            myDataset.Dispose();
        }
Esempio n. 4
0
        public static void Rasterize(string inputFeature, string outRaster, string fieldName, int cellSize)
        {
            int rasterCellSize = cellSize;

            const double noDataValue = -9999;

            string outputRasterFile = outRaster;

            Ogr.RegisterAll();

            DataSource dataSource = Ogr.Open(inputFeature, 0);
            Layer      layer      = dataSource.GetLayerByIndex(0);
            Envelope   envelope   = new Envelope();

            layer.GetExtent(envelope, 0);

            int x_res = Convert.ToInt32((envelope.MaxX - envelope.MinX) / rasterCellSize);
            int y_res = Convert.ToInt32((envelope.MaxY - envelope.MinY) / rasterCellSize);

            Console.WriteLine("Extent: " + envelope.MaxX + " " + envelope.MinX + " " + envelope.MaxY + " " + envelope.MinY);
            Console.WriteLine("X resolution: " + x_res);
            Console.WriteLine("X resolution: " + y_res);



            Gdal.AllRegister();

            if (File.Exists(outputRasterFile))
            {
                File.Delete(outputRasterFile);
            }
            //Create new tiff
            OSGeo.GDAL.Driver outputDriver = Gdal.GetDriverByName("GTiff");
            //OSGeo.GDAL.Driver outputDriver = Gdal.GetDriverByName("HFA");
            Dataset outputDataset = outputDriver.Create(outputRasterFile, x_res, y_res, 1, DataType.GDT_Float64, null);
            //Extrac srs from input feature
            string inputShapeSrs;

            OSGeo.OSR.SpatialReference spatialRefrence = layer.GetSpatialRef();
            spatialRefrence.ExportToWkt(out inputShapeSrs);
            //Assign input feature srs to outpur raster
            outputDataset.SetProjection(inputShapeSrs);
            //Geotransform
            double[] argin = new double[] { envelope.MinX, rasterCellSize, 0, envelope.MaxY, 0, -rasterCellSize };
            outputDataset.SetGeoTransform(argin);
            //Set no data
            Band band = outputDataset.GetRasterBand(1);

            band.SetNoDataValue(noDataValue);
            //close tiff
            outputDataset.FlushCache();
            outputDataset.Dispose();
            //Feature to raster rasterize layer options
            //No of bands (1)
            int[] bandlist = new int[] { 1 };
            //Values to be burn on raster (10.0)
            double[] burnValues = new double[] { 10.0 };
            Dataset  myDataset  = Gdal.Open(outputRasterFile, Access.GA_Update);

            //additional options
            string[] rasterizeOptions;
            //rasterizeOptions = new string[] { "ALL_TOUCHED=TRUE", "ATTRIBUTE=" + fieldName }; //To set all touched pixels into raster pixel
            //rasterizeOptions = new string[] { "ATTRIBUTE=" + fieldName };
            rasterizeOptions = new string[] { "ATTRIBUTE=" + fieldName };
            //Rasterize layer
            //Gdal.RasterizeLayer(myDataset, 1, bandlist, layer, IntPtr.Zero, IntPtr.Zero, 1, burnValues, null, null, null); // To burn the given burn values instead of feature attributes
            //Gdal.RasterizeLayer(myDataset, 1, bandlist, layer, IntPtr.Zero, IntPtr.Zero, 1, burnValues, rasterizeOptions, new Gdal.GDALProgressFuncDelegate(ProgressFunc), "Raster conversion");
            Gdal.RasterizeLayer(myDataset, 1, bandlist, layer, IntPtr.Zero, IntPtr.Zero, 1, burnValues, rasterizeOptions, new Gdal.GDALProgressFuncDelegate(ProgressFunc), "Raster conversion");
        }
Esempio n. 5
0
        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();
        }