示例#1
0
        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);
        }
示例#2
0
 private void endWrite(EndWriteOption option)
 {
     exporterOpened = false;
     if (option == EndWriteOption.AppendBadGeometries && exporterBadFeatures != null)
     {
         foreach (var feat in exporterBadFeatures)
         {
             exporterLayer.CreateFeature(feat);
         }
     }
     exporterLayer.CommitTransaction();
     exporterLayer.SyncToDisk();
     exporterBadFeatures = null;
     exporterSrid.Dispose();
     exporterSrid = null;
     exporterFeatDefn.Dispose();
     exporterFeatDefn = null;
     exporterLayer.Dispose();
     exporterLayer = null;
     exporterDataSource.Dispose();
     exporterDataSource = 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);
        }
示例#4
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            GH_Structure <IGH_GeometricGoo> gGoo = new GH_Structure <IGH_GeometricGoo>();

            DA.GetDataTree <IGH_GeometricGoo>("Feature Geometry", out gGoo);

            GH_Structure <GH_Number> bufferInt = new GH_Structure <GH_Number>();

            DA.GetDataTree <GH_Number>("Buffer Distance", out bufferInt);

            GH_Structure <IGH_GeometricGoo> gGooBuffered = new GH_Structure <IGH_GeometricGoo>();

            ///GDAL setup
            RESTful.GdalConfiguration.ConfigureOgr();

            ///Use WGS84 spatial reference
            OSGeo.OSR.SpatialReference dst = new OSGeo.OSR.SpatialReference("");
            dst.SetWellKnownGeogCS("WGS84");
            Transform transform    = new Transform(1); // Heron.Convert.XYZToWGSTransform();
            Transform revTransform = new Transform(1); //Heron.Convert.WGSToXYZTransform();

            ///Create virtual datasource to be converted later
            ///Using geojson as a flexiblle base file type which can be converted later with ogr2ogr
            OSGeo.OGR.Driver drv = Ogr.GetDriverByName("GeoJSON");
            DataSource       ds  = drv.CreateDataSource("/vsimem/out.geojson", null);

            ///Use OGR catch-all for geometry types
            var gtype = wkbGeometryType.wkbGeometryCollection;

            ///Create layer
            OSGeo.OGR.Layer layer = ds.CreateLayer("temp", dst, gtype, null);
            FeatureDefn     def   = layer.GetLayerDefn();

            var branchPaths = gGoo.Paths;

            for (int a = 0; a < gGoo.Branches.Count; a++)
            {
                ///create feature
                OSGeo.OGR.Feature feature = new OSGeo.OGR.Feature(def);

                ///Get geometry type(s) in branch
                var    geomList = gGoo.Branches[a];
                string geomType = string.Empty;

                List <string> geomTypeList = geomList.Select(o => o.TypeName).ToList();
                ///Test if geometry in the branch is of the same type.
                ///If there is more than one element of a type, tag as multi, if there is more than one type, tag as mixed
                if (geomTypeList.Count == 1)
                {
                    geomType = geomTypeList.First();
                }
                else if (geomTypeList.Count > 1 && geomTypeList.All(gt => gt == geomTypeList.First()))
                {
                    geomType = "Multi" + geomTypeList.First();
                }

                else
                {
                    geomType = "Mixed";
                }

                //var buffList = bufferInt.Branches[a];
                var buffList = new List <GH_Number>();
                //var path = new GH_Path(a);
                var path = branchPaths[a];
                if (path.Valid)
                {
                    buffList = (List <GH_Number>)bufferInt.get_Branch(path);
                }
                else
                {
                    buffList = bufferInt.Branches[0];
                }
                int buffIndex = 0;


                double buffDist = 0;
                GH_Convert.ToDouble(buffList[buffIndex], out buffDist, GH_Conversion.Primary);

                ///For testing
                //AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, geomType);

                ///Add geomtery to feature
                ///Create containers for translating from GH Goo
                Point3d        pt  = new Point3d();
                List <Point3d> pts = new List <Point3d>();

                Curve        crv  = null;
                List <Curve> crvs = new List <Curve>();

                Mesh mesh      = new Mesh();
                Mesh multiMesh = new Mesh();

                int quadsecs = 10;

                switch (geomType)
                {
                case "Point":
                    geomList.First().CastTo <Point3d>(out pt);
                    var bufferPt = Heron.Convert.Point3dToOgrPoint(pt, transform).Buffer(buffDist, quadsecs);
                    gGooBuffered.AppendRange(Heron.Convert.OgrGeomToGHGoo(bufferPt, revTransform), new GH_Path(a));
                    break;

                case "MultiPoint":
                    foreach (var point in geomList)
                    {
                        point.CastTo <Point3d>(out pt);
                        pts.Add(pt);
                    }
                    var bufferPts = Heron.Convert.Point3dsToOgrMultiPoint(pts, transform).Buffer(buffDist, quadsecs);
                    gGooBuffered.AppendRange(Heron.Convert.OgrGeomToGHGoo(bufferPts, revTransform), new GH_Path(a));
                    break;

                case "Curve":
                    geomList.First().CastTo <Curve>(out crv);
                    var bufferCrv = Heron.Convert.CurveToOgrLinestring(crv, transform).Buffer(buffDist, quadsecs);
                    gGooBuffered.AppendRange(Heron.Convert.OgrGeomToGHGoo(bufferCrv, revTransform), new GH_Path(a));
                    break;

                case "MultiCurve":
                    bool allClosed = true;
                    foreach (var curve in geomList)
                    {
                        curve.CastTo <Curve>(out crv);
                        if (!crv.IsClosed)
                        {
                            allClosed = false;
                        }
                        crvs.Add(crv);
                    }
                    if (allClosed)
                    {
                        var bufferCrvs = Heron.Convert.CurvesToOgrPolygon(crvs, transform).Buffer(buffDist, quadsecs);
                        gGooBuffered.AppendRange(Heron.Convert.OgrGeomToGHGoo(bufferCrvs, revTransform), new GH_Path(a));
                    }
                    else
                    {
                        var bufferCrvs = Heron.Convert.CurvesToOgrMultiLinestring(crvs, transform).Buffer(buffDist, quadsecs);
                        gGooBuffered.AppendRange(Heron.Convert.OgrGeomToGHGoo(bufferCrvs, revTransform), new GH_Path(a));
                    }

                    break;

                case "Mesh":
                    geomList.First().CastTo <Mesh>(out mesh);
                    mesh.Ngons.AddPlanarNgons(DocumentTolerance());
                    var bufferPoly = Ogr.ForceToMultiPolygon(Heron.Convert.MeshToMultiPolygon(mesh, transform)).Buffer(buffDist, quadsecs);
                    gGooBuffered.AppendRange(Heron.Convert.OgrGeomToGHGoo(bufferPoly, revTransform), new GH_Path(a));
                    break;

                case "MultiMesh":
                    foreach (var m in geomList)
                    {
                        Mesh meshPart = new Mesh();
                        m.CastTo <Mesh>(out meshPart);
                        meshPart.Ngons.AddPlanarNgons(DocumentTolerance());
                        multiMesh.Append(meshPart);
                    }
                    var bufferPolys = Ogr.ForceToMultiPolygon(Heron.Convert.MeshToMultiPolygon(multiMesh, transform)).Buffer(buffDist, quadsecs);
                    gGooBuffered.AppendRange(Heron.Convert.OgrGeomToGHGoo(bufferPolys, revTransform), new GH_Path(a));
                    break;

                case "Mixed":
                    OSGeo.OGR.Geometry geoCollection = new OSGeo.OGR.Geometry(wkbGeometryType.wkbGeometryCollection);
                    for (int gInt = 0; gInt < geomList.Count; gInt++)
                    {
                        string geomTypeMixed = geomTypeList[gInt];
                        switch (geomTypeMixed)
                        {
                        case "Point":
                            geomList[gInt].CastTo <Point3d>(out pt);
                            geoCollection.AddGeometry(Heron.Convert.Point3dToOgrPoint(pt, transform));
                            break;

                        case "Curve":
                            geomList[gInt].CastTo <Curve>(out crv);
                            geoCollection.AddGeometry(Heron.Convert.CurveToOgrLinestring(crv, transform));
                            break;

                        case "Mesh":
                            geomList[gInt].CastTo <Mesh>(out mesh);
                            geoCollection.AddGeometry(Ogr.ForceToMultiPolygon(Heron.Convert.MeshToMultiPolygon(mesh, transform)));
                            break;

                        default:
                            AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Not able to export " + geomType + " geometry at branch " + gGoo.get_Path(a).ToString() +
                                              ". Geometry must be a Point, Curve or Mesh.");
                            break;
                        }
                    }
                    var bufferCol = geoCollection.Buffer(buffDist, quadsecs);
                    gGooBuffered.AppendRange(Heron.Convert.OgrGeomToGHGoo(bufferCol, revTransform), new GH_Path(a));
                    break;


                default:
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Not able to export " + geomType + " geometry at branch " + gGoo.get_Path(a).ToString() +
                                      ". Geometry must be a Point, Curve or Mesh.");
                    break;
                }
            }

            def.Dispose();
            layer.Dispose();
            ds.Dispose();

            DA.SetDataTree(0, gGooBuffered);
        }
示例#5
0
        private void button4_Click(object sender, EventArgs e)
        {
            string dir_gdal_data = System.Environment.CurrentDirectory + "\\" + "gdal-data\\";

            Environment.SetEnvironmentVariable("GDAL_DATA", dir_gdal_data, EnvironmentVariableTarget.Process);
            DelegateCoordsTransform dele = null;

            VectorAdjust.CoordinateAdjust ca = new CoordinateAdjust();
            //------------WGS84--GCJ02--------------
            if (comboBox1.SelectedIndex == 0 && comboBox2.SelectedIndex == 1)
            {
                dele = new DelegateCoordsTransform(ca.WGS84ToGCJ02);
            }
            //------------GCJ02--WGS84--------------
            if (comboBox1.SelectedIndex == 1 && comboBox2.SelectedIndex == 0)
            {
                dele = new DelegateCoordsTransform(ca.GCJ02ToWGS84);
            }
            //------------WGS84--BD09--------------
            if (comboBox1.SelectedIndex == 0 && comboBox2.SelectedIndex == 2)
            {
                dele = new DelegateCoordsTransform(ca.WGS84ToBD09);
            }
            //------------BD09---WGS84--------------
            if (comboBox1.SelectedIndex == 2 && comboBox2.SelectedIndex == 0)
            {
                dele = new DelegateCoordsTransform(ca.BD09ToWGS84);
            }
            //------------BD09---GCJ02--------------
            if (comboBox1.SelectedIndex == 2 && comboBox2.SelectedIndex == 1)
            {
                dele = new DelegateCoordsTransform(ca.BD09ToGCJ02);
            }
            //------------GCJ02--BD09--------------
            if (comboBox1.SelectedIndex == 1 && comboBox2.SelectedIndex == 2)
            {
                dele = new DelegateCoordsTransform(ca.GCJ02ToBD09);
            }

            if (files == null || files.Length == 0)
            {
                MessageBox.Show("请选择要处理的数据");
                this.button1.Focus();
                return;
            }
            if (comboBox1.SelectedIndex == comboBox2.SelectedIndex)
            {
                MessageBox.Show("目标坐标系和原始坐标系相同,请重新选择");
                return;
            }
            if (String.IsNullOrWhiteSpace(textBox2.Text))
            {
                MessageBox.Show("请先选择保存数据目录");
                this.button2.Focus();
                return;
            }

            //初始化驱动信息
            //注册所有驱动
            Ogr.RegisterAll();
            OSGeo.GDAL.Gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES");
            //为支持属性表字段支持中文
            OSGeo.GDAL.Gdal.SetConfigOption("SHAPE_ENCODING", "");

            //开启日志
            Gdal.SetConfigOption("CPL_DEBUG", "ON");
            Gdal.SetConfigOption("CPL_LOG", System.IO.Directory.GetCurrentDirectory() + "\\gdallog.txt");
            //驱动名称
            string strDriverName = "ESRI Shapefile";

            OSGeo.OGR.Driver Tdriver = Ogr.GetDriverByName(strDriverName);
            if (Tdriver == null)
            {
                MessageBox.Show("获得驱动失败!程序退出");
                return;
            }
            //遍历某个图层
            this.progressBar1.Maximum = files.Length;
            this.progressBar1.Minimum = 0;
            this.progressBar1.Value   = 0;

            for (int i = 0; i < files.Length; i++)//遍历每个图层
            {
                string shp_file         = files[i];
                string shp_dir          = System.IO.Path.GetDirectoryName(shp_file);
                string shp_fileSaveName = System.IO.Path.GetFileNameWithoutExtension(shp_file);
                //打开源数据
                DataSource dsS = Ogr.Open(shp_file, 0);
                if (dsS == null)
                {
                    MessageBox.Show("打开" + shp_file + "文件失败", "提示");
                    this.progressBar1.Value++;
                    continue;
                }
                //创建目标数据
                string saveDir = this.textBox2.Text;

                DataSource dsT = Tdriver.CreateDataSource(saveDir, null);
                if (dsT == null)
                {
                    MessageBox.Show("创建" + saveDir + "\\" + shp_fileSaveName + "文件失败");
                    this.progressBar1.Value++;

                    continue;
                }
                Layer layerS = dsS.GetLayerByIndex(0);
                if (layerS == null)
                {
                    MessageBox.Show("获得" + shp_file + "图层失败");
                    this.progressBar1.Value++;
                    continue;
                }
                //string shp_fileSaveName_utf8 = TransferEncoding(Encoding.BigEndianUnicode,Encoding.UTF8,shp_fileSaveName);
                OSGeo.GDAL.Gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES");
                Layer LayerT = dsT.CreateLayer(shp_fileSaveName, layerS.GetSpatialRef(), layerS.GetGeomType(), null);//layerS.GetSpatialRef()
                if (LayerT == null)
                {
                    MessageBox.Show("创建" + saveDir + "\\" + shp_fileSaveName + "图层失败!", "提示");
                    this.progressBar1.Value++;
                    continue;
                }
                Feature  pFeatureS, pFeatureT;
                Geometry geomS, geomT;

                long        countFeature = layerS.GetFeatureCount(0);
                FeatureDefn fd           = layerS.GetLayerDefn();
                //对目标图层进行属性定义
                for (int ii = 0; ii < fd.GetFieldCount(); ii++)
                {
                    LayerT.CreateField(fd.GetFieldDefn(ii), 1);
                }
                fd.Dispose();
                this.progressBar2.Minimum = 0;
                this.progressBar2.Maximum = (int)countFeature;
                this.progressBar2.Value   = 0;
                for (int k = 0; k < countFeature; k++)
                {
                    pFeatureS = layerS.GetFeature(k);
                    if (pFeatureS != null)
                    {
                        geomS     = pFeatureS.GetGeometryRef();
                        geomT     = GeometryCoordTransfrom2D(geomS, dele);
                        pFeatureT = pFeatureS.Clone();
                        pFeatureT.SetFrom(pFeatureS, 1);
                        pFeatureT.SetGeometryDirectly(geomT);
                        LayerT.CreateFeature(pFeatureT);

                        geomS.Dispose();
                        geomT.Dispose();
                        pFeatureS.Dispose();
                        pFeatureT.Dispose();
                    }
                    this.progressBar2.Value++;
                }
                layerS.Dispose();
                LayerT.Dispose();


                dsS.Dispose();
                dsT.Dispose();
                this.progressBar1.Value++;
            }

            MessageBox.Show("处理完毕", "提示");
        }