Пример #1
0
        public void AddValueToField(PointFeature featureData)
        {
            OSGeo.OGR.Feature feature = new OSGeo.OGR.Feature(_ogrLayer.GetLayerDefn());

            feature.SetField(nameof(featureData.SampleId), featureData.SampleId);
            feature.SetField(nameof(featureData.Confidence), featureData.Confidence);
            feature.SetField(nameof(featureData.AgreeingValidations), featureData.AgreeingValidations);
            feature.SetField(nameof(featureData.UserConf), featureData.UserConf);

            feature.SetField(nameof(featureData.ValidityTime),
                             featureData.ValidityTime != null ? featureData.ValidityTime.Value.ToString("yyyy-MM-dd") : "");

            feature.SetField(nameof(featureData.ImageryTime),
                             featureData.ImageryTime != null ? featureData.ImageryTime.Value.ToString("yyyy-MM-dd") : "");

            feature.SetField(nameof(featureData.ValidationTime),
                             featureData.ValidationTime != null ? featureData.ValidationTime.Value.ToString("yyyy-MM-dd") : "");

            feature.SetField(nameof(featureData.LandCover), featureData.LandCover);
            feature.SetField(nameof(featureData.CropType1), featureData.CropType1);
            feature.SetField(nameof(featureData.CropType2), featureData.CropType2);
            feature.SetField(nameof(featureData.Irrigation1), featureData.Irrigation1);
            feature.SetField(nameof(featureData.Irrigation2), featureData.Irrigation2);
            feature.SetField(nameof(featureData.Irrigation3), featureData.Irrigation3);
            feature.SetField(nameof(featureData.ExtendedData), featureData.ExtendedData);

            Geometry geometry = Geometry.CreateFromWkt($"POINT({featureData.Geometry.X} {featureData.Geometry.Y})");

            feature.SetGeometry(geometry);

            _ogrLayer.CreateFeature(feature);
        }
Пример #2
0
        /************************************  对比并筛选 ***************************************************/

        /// <summary>
        /// 通过ID数组提取出所有要素,创建动作
        /// </summary>
        /// <param name="dzLine"></param>
        /// <param name="pdLing"></param>
        /// <param name="savePath"></param>
        public static void selectFeat(string dzx, string pdx, string savePath)
        {
            Stopwatch ssww = new Stopwatch(); ssww.Start();

            //获得数组
            int[] a = getMinIdGroupM(dzx, pdx);

            Console.WriteLine("ID to Feater...");
            OSGeo.OGR.Ogr.RegisterAll();
            OSGeo.OGR.Driver     dr      = OSGeo.OGR.Ogr.GetDriverByName("ESRI shapefile");
            OSGeo.OGR.DataSource dzDS    = dr.Open(dzx, 0);
            OSGeo.OGR.Layer      dzLayer = dzDS.GetLayerByIndex(0);
            if (System.IO.File.Exists(savePath))
            {
                System.IO.File.Delete(savePath);
            }
            OSGeo.OGR.DataSource ds        = dr.CreateDataSource(savePath, null);
            OSGeo.OGR.Layer      fileLayer = ds.CreateLayer("", null, OSGeo.OGR.wkbGeometryType.wkbPolygon, null);
            //get featuer by ID
            for (int i = 0; i < a.Length; i++)
            {
                fileLayer.CreateFeature(dzLayer.GetFeature(a[i]));
                dzLayer.GetFeature(a[i]).Dispose();
            }
            dzLayer.Dispose();
            dzDS.Dispose();
            fileLayer.Dispose();
            ds.Dispose();
            _2_坡度线.OutLine.CutImg.cleanPdxM(savePath);
            ssww.Stop();
            Console.WriteLine("提取轮廓线完成!用时:{0}", ssww.Elapsed.ToString());
        }
Пример #3
0
        /// <summary>
        /// 整合坡度线(Line)
        /// </summary>
        /// <param name="subPdx"></param>
        /// <returns></returns>
        public static string zhengHePdLine(List <string> subPdx)
        {
            OSGeo.OGR.Ogr.RegisterAll();
            OSGeo.OGR.Driver dr = OSGeo.OGR.Ogr.GetDriverByName("ESRI shapefile");

            string newPath = StaticTools.tempFilePath("shp", "整合线");

            OSGeo.OGR.DataSource newDs    = dr.CreateDataSource(newPath, null);/////////////////
            OSGeo.OGR.Layer      newLayer = newDs.CreateLayer("Lines",
                                                              dr.Open(subPdx[0], 0).GetLayerByIndex(0).GetSpatialRef(),
                                                              dr.Open(subPdx[0], 0).GetLayerByIndex(0).GetGeomType(), null);

            for (int i = 0; i < subPdx.Count; i++)
            {
                OSGeo.OGR.DataSource dsLine    = dr.Open(subPdx[i], 0);///////////////////////
                OSGeo.OGR.Layer      lineLayer = dsLine.GetLayerByIndex(0);
                for (int j = 0; j < lineLayer.GetFeatureCount(0); j++)
                {
                    newLayer.CreateFeature(lineLayer.GetFeature(j));
                }
                dsLine.Dispose();
            }
            newDs.Dispose();
            return(newPath);
        }
Пример #4
0
        /*************************************  点角式  *****************************************/
        /// <summary>
        /// 清理等后生成新的文件
        ///
        /// </summary>
        public static void claenPoint(string filePath, string savefile, double jiaodu, int cishu)
        {
            OSGeo.OGR.Ogr.RegisterAll();
            OSGeo.OGR.Driver dr = OSGeo.OGR.Ogr.GetDriverByName("ESRI shapefile");
            //进来的Layer
            OSGeo.OGR.DataSource oriDs    = dr.Open(filePath, 0);
            OSGeo.OGR.Layer      oriLayer = oriDs.GetLayerByIndex(0);
            //出去的Layer
            if (System.IO.File.Exists(savefile))
            {
                savefile.deleteFiles();
            }
            OSGeo.OGR.DataSource targDs    = dr.CreateDataSource(savefile, null);
            OSGeo.OGR.Layer      targLayer = targDs.CreateLayer("targ", null, OSGeo.OGR.wkbGeometryType.wkbPolygon, null);

            int featCount = oriLayer.GetFeatureCount(0);

            for (int i = 0; i < featCount; i++)
            {
                ///进来的Featuer
                OSGeo.OGR.Feature oriFeat = oriLayer.GetFeature(i);

                ///把一个Featuer转为点数组
                OSGeo.OGR.Geometry oriGeom = oriFeat.GetGeometryRef();
                OSGeo.OGR.Geometry subGeom = oriGeom.GetGeometryRef(0);
                int     pointCount         = subGeom.GetPointCount();
                Point[] aFeat = new Point[pointCount];
                for (int c = 0; c < pointCount; c++)
                {
                    aFeat[c].X = subGeom.GetX(c);
                    aFeat[c].Y = subGeom.GetY(c);
                    aFeat[c].Z = subGeom.GetZ(c);
                }

                ///调选点方法,得到一个新的Featuer
                Geometry newGeom = null;
                if (aFeat.Length > cishu * 3)
                {
                    newGeom = JID(aFeat, jiaodu, cishu);
                }
                else
                {
                    oriFeat.Dispose();
                    continue;
                }
                if (newGeom != null)
                {
                    Feature temp = new Feature(new FeatureDefn(""));
                    temp.SetGeometry(newGeom);
                    targLayer.CreateFeature(temp);
                    temp.Dispose();
                }
                oriFeat.Dispose();
                Console.WriteLine("已完成{0}/{1}", i, featCount);
            }
            oriDs.Dispose();
            targDs.Dispose();
        }
Пример #5
0
        public static void selectDZXFromPoint(string point, string dzx, string savePath)
        {
            OSGeo.OGR.Ogr.RegisterAll();
            OSGeo.OGR.Driver     dr    = OSGeo.OGR.Ogr.GetDriverByName("ESRI shapefile");
            OSGeo.OGR.DataSource poiDS = dr.Open(point, 0);
            OSGeo.OGR.DataSource dzxDS = dr.Open(dzx, 0);
            if (File.Exists(savePath))
            {
                File.Delete(savePath);
            }
            OSGeo.OGR.DataSource newDS    = dr.CreateDataSource(savePath, null);
            OSGeo.OGR.Layer      poiLayer = poiDS.GetLayerByIndex(0);
            OSGeo.OGR.Layer      dzxLayer = dzxDS.GetLayerByIndex(0);
            OSGeo.OGR.Layer      newLayer = newDS.CreateLayer("", dzxLayer.GetSpatialRef(), dzxLayer.GetGeomType(), null);

            int poiCount = poiLayer.GetFeatureCount(0);
            int dzxCount = dzxLayer.GetFeatureCount(0);

            for (int i = 0; i < poiCount; i++)
            {
                OSGeo.OGR.Feature  poiFeat = poiLayer.GetFeature(i);
                OSGeo.OGR.Geometry poiGeom = poiFeat.GetGeometryRef();
                for (int t = 0; t < dzxCount; t++)
                {
                    OSGeo.OGR.Feature  dzxFeat = dzxLayer.GetFeature(t);
                    OSGeo.OGR.Geometry dzxGeom = dzxFeat.GetGeometryRef();

                    if (poiGeom.Within(dzxGeom))
                    {
                        newLayer.CreateFeature(dzxFeat);
                    }
                    dzxFeat.Dispose();
                    Console.WriteLine("getFeatureByPoint:{0}/{1}", i, poiCount);
                }
                poiFeat.Dispose();
            }
            Console.WriteLine("【本次提取到{0}个要素】", newLayer.GetFeatureCount(0));
            newDS.Dispose();
            dzxDS.Dispose();
            poiDS.Dispose();
        }
        public static bool ExportSelectedDatabaseToGML(Action <string, bool> aLog, string pOutputFilename)
        {
            // Get database, return if no database selected
            if (frmMain.dbx == null)
            {
                aLog("Please select a database first...", true);
                return(false);
            }

            // Setup driver
            OSGeo.OGR.Driver drv = Ogr.GetDriverByName("GML");
            if (drv == null)
            {
                aLog("Could not load driver", true);
                return(false);
            }

            // Create fieldAttributes datasource
            DataSource ds = drv.CreateDataSource(pOutputFilename, null);

            if (ds == null)
            {
                aLog("Could not create datasource", true);
                return(false);
            }

            // Create fieldAttributes layer
            OSGeo.OGR.Layer l = ds.CreateLayer("AddressUnits", null, wkbGeometryType.wkbPoint, null);
            if (l == null)
            {
                aLog("Failed to create GML file: AddressUnits", true);
                return(false);
            }

            // Create fieldAttributes class to hold address unit data
            AddressUnit mAddressUnits = new AddressUnit();

            // Add fields to shapefile
            foreach (System.Reflection.FieldInfo mFld in mAddressUnits.GetType().GetFields())
            {
                var val       = (DatFld)mFld.GetValue(mAddressUnits);
                var mNewField = new FieldDefn(mFld.Name, val.type);
                if (val.type == FieldType.OFTString)
                {
                    mNewField.SetWidth(val.length);
                }
                if (Ogr.OGRERR_NONE != l.CreateField(mNewField, 1))
                {
                    aLog("Failed to add field: " + mFld.Name, true);
                }
            }

            int    ctr = 0;
            double mX, mY;

            var mAdmAdrFeature = new AddressUnitFeature(frmMain.dbx);

            DataTable mTable = mAdmAdrFeature.GetTable(sqlStatements.selectAddressUnitsSQL);

            // Add features
            foreach (DataRow mRow in mTable.Rows)
            {
                if (Double.TryParse(mRow["loc_x"].ToString(), out mX) && Double.TryParse(mRow["loc_y"].ToString(), out mY))
                {
                    var mFeature = new OSGeo.OGR.Feature(l.GetLayerDefn());
                    var mPoint   = new OSGeo.OGR.Geometry(wkbGeometryType.wkbPoint);

                    mPoint.SetPoint(0, mX, mY, 0);
                    mFeature.SetFID(ctr);
                    mFeature.SetGeometry(mPoint);
                    mFeature.SetField("ADDRESSUNITID", int.Parse(mRow["id"].ToString()));
                    mFeature.SetField("ROADID", int.Parse(mRow["road_id"].ToString()));
                    mFeature.SetField("ADDRESSUNITNR", int.Parse(mRow["addressUnitNumber"].ToString()));
                    mFeature.SetField("ROADNAME_EN", Utilities.GetANSI(mRow["NAMEENGLISH"].ToString()));
                    mFeature.SetField("ROADNAME_AR", Utilities.GetANSI(mRow["NAMEARABIC"].ToString()));
                    mFeature.SetField("DISTRICT_EN", Utilities.GetANSI(mRow["DISTRICT_EN"].ToString()));
                    mFeature.SetField("DISTRICT_AR", Utilities.GetANSI(mRow["DISTRICT_AR"].ToString()));
                    mFeature.SetField("MUNICIPALITY_EN", Utilities.GetANSI(Utilities.LABEL_ABUDHABI_EN));
                    mFeature.SetField("MUNICIPALITY_AR", Utilities.GetANSI(Utilities.LABEL_ABUDHABI_AR));
                    mFeature.SetField("QR_CODE", Utilities.GetANSI(mAdmAdrFeature.GetQRCode(mRow, mTable)));
                    l.CreateFeature(mFeature);
                }
                else
                {
                    Utilities.LogDebug("Error");
                }

                ctr++;
            }

            l.Dispose();
            ds.Dispose();
            drv.Dispose();
            return(true);
        }
Пример #7
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)
        {
            ///TODO:    fix crash with "multi" types in a branch for shapefiles, can't create lines in a points layer
            ///         fix mesh/polygon face creation issue on sphere, dropping faces or flipped faces
            ///         fix swtich case for shapfiles so that points and multipoints (eg) are written to the same file. don't use switch anymore, us ifs
            ///         fix sql statements, they don't seem to have an effect.  Need these to work for pulling apart geometry collections.

            ///Gather GHA inputs
            string filename = string.Empty;

            DA.GetData <string>("Vector Data Filename", ref filename);

            string folder = string.Empty;

            DA.GetData <string>("Vector Data Folder", ref folder);
            folder = Path.GetFullPath(folder);
            if (!folder.EndsWith(Path.DirectorySeparatorChar.ToString()))
            {
                folder += Path.DirectorySeparatorChar;
            }

            string shpPath = folder + filename + drvExtension;
            ///for more than one geometry type, a list of files for shapefile output needs to be established
            List <string> shpPathList = new List <string>();
            List <string> shpTypeList = new List <string>();

            List <string> fields = new List <string>();

            DA.GetDataList <string>("Fields", fields);

            GH_Structure <GH_String> values = new GH_Structure <GH_String>();

            DA.GetDataTree <GH_String>("Values", out values);

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

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

            bool export = false;

            DA.GetData <bool>("Export", ref export);

            ///GDAL setup
            RESTful.GdalConfiguration.ConfigureOgr();
            OSGeo.GDAL.Gdal.SetConfigOption("OGR_SKIP", "KML");

            string driverType = drvType;

            //OSGeo.OGR.Driver drv = Ogr.GetDriverByName("LIBKML");// driverType);
            OSGeo.OGR.Driver drv = Ogr.GetDriverByName("GeoJSON");



            if (export == true)
            {
                ///File setup for save
                FileInfo file = new FileInfo(folder);
                file.Directory.Create();

                if (File.Exists(shpPath))
                {
                    drv.DeleteDataSource(shpPath);
                }

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

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

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

                ///Create layer
                //string[] layerOptions = new string[] { "LIBKML_USE_SCHEMADATA=NO", "LIBKML_USE_SIMPLEFIELD=NO", "LIBKML_ALTITUDEMODE_FIELD=relativeToGround" };
                //string[] layerOptions = new string[] { "LIBKML_STRICT_COMPLIANCE=FALSE" };
                OSGeo.OGR.Layer layer = ds.CreateLayer(filename, dst, gtype, null);
                FeatureDefn     def   = layer.GetLayerDefn();

                ///Add fields to layer
                for (int f = 0; f < fields.Count; f++)
                {
                    OSGeo.OGR.FieldDefn fname = new OSGeo.OGR.FieldDefn(fields[f], OSGeo.OGR.FieldType.OFTString);
                    layer.CreateField(fname, f);
                }

                ///Specific fields for LIBKML for use in Google Earth
                ///See LIBMKL driver for more info https://gdal.org/drivers/vector/libkml.html
                if (drvType == "LIBKML")
                {
                    OSGeo.OGR.FieldDefn kmlFieldAltitudeMode = new OSGeo.OGR.FieldDefn("altitudeMode", OSGeo.OGR.FieldType.OFTString);
                    layer.CreateField(kmlFieldAltitudeMode, fields.Count());
                    //OSGeo.OGR.FieldDefn kmlFieldExtrude = new OSGeo.OGR.FieldDefn("tessellate", OSGeo.OGR.FieldType.OFTInteger);
                    //layer.CreateField(kmlFieldExtrude, fields.Count()+1);
                }


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

                    ///Set LIBKML specific fields for use in Google Earth, defaulting to 'relativeToGround'.  Consider setting to 'absolute'.
                    if (drvType == "LIBKML")
                    {
                        feature.SetField("altitudeMode", "relativeToGround");
                        //feature.SetField("altitudeMode", "absolute");
                        //feature.SetField("tessellate", 0);
                    }

                    ///TODO: Build style table
                    OSGeo.OGR.StyleTable styleTable = new StyleTable();
                    //feature.SetStyleString("BRUSH(fc:#0000FF);PEN(c:#000000)");

                    ///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";
                    }

                    ///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();

                    switch (geomType)
                    {
                    case "Point":
                        geomList.First().CastTo <Point3d>(out pt);
                        feature.SetGeometry(Heron.Convert.Point3dToOgrPoint(pt, transform));
                        if (!shpTypeList.Contains("POINT"))
                        {
                            shpTypeList.Add("POINT");
                        }
                        break;

                    case "MultiPoint":
                        foreach (var point in geomList)
                        {
                            point.CastTo <Point3d>(out pt);
                            pts.Add(pt);
                        }
                        feature.SetGeometry(Heron.Convert.Point3dsToOgrMultiPoint(pts, transform));
                        if (!shpTypeList.Contains("MULTIPOINT"))
                        {
                            shpTypeList.Add("MULTIPOINT");
                        }
                        break;

                    case "Curve":
                        geomList.First().CastTo <Curve>(out crv);
                        feature.SetGeometry(Heron.Convert.CurveToOgrLinestring(crv, transform));
                        if (!shpTypeList.Contains("LINESTRING"))
                        {
                            shpTypeList.Add("LINESTRING");
                        }
                        break;

                    case "MultiCurve":
                        foreach (var curve in geomList)
                        {
                            curve.CastTo <Curve>(out crv);
                            crvs.Add(crv);
                        }
                        feature.SetGeometry(Heron.Convert.CurvesToOgrMultiLinestring(crvs, transform));
                        if (!shpTypeList.Contains("MULTILINESTRING"))
                        {
                            shpTypeList.Add("MULTILINESTRING");
                        }
                        break;

                    case "Mesh":
                        geomList.First().CastTo <Mesh>(out mesh);
                        feature.SetGeometry(Heron.Convert.MeshToMultiPolygon(mesh, transform));
                        if (!shpTypeList.Contains("MULTIPOLYGON"))
                        {
                            shpTypeList.Add("MULTIPOLYGON");
                        }
                        break;

                    case "MultiMesh":
                        foreach (var m in geomList)
                        {
                            Mesh meshPart = new Mesh();
                            m.CastTo <Mesh>(out meshPart);
                            multiMesh.Append(meshPart);
                        }
                        feature.SetGeometry(Heron.Convert.MeshToMultiPolygon(multiMesh, transform));
                        if (!shpTypeList.Contains("MULTIPOLYGON"))
                        {
                            shpTypeList.Add("MULTIPOLYGON");
                        }
                        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;
                            }
                        }
                        feature.SetGeometry(geoCollection);
                        if (!shpTypeList.Contains("GEOMETRYCOLLECTION"))
                        {
                            shpTypeList.Add("GEOMETRYCOLLECTION");
                        }
                        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;
                    }



                    ///Give the feature a unique ID
                    feature.SetFID(a);

                    ///Add values to fields
                    GH_Path path = gGoo.get_Path(a);

                    for (int vInt = 0; vInt < fields.Count; vInt++)
                    {
                        string val = string.Empty;
                        if (values.get_Branch(path) != null)
                        {
                            val = values.get_DataItem(path, vInt).ToString();
                        }
                        feature.SetField(fields[vInt], val);
                    }

                    ///Save feature to layer
                    layer.CreateFeature(feature);

                    ///Cleanup
                    feature.Dispose();
                }

                layer.Dispose();
                ds.Dispose();
                drv.Dispose();

                ///Convert in memory dataset to file using ogr2ogr
                ///For KML set 'altitudeMode' to 'relativeToGround' or 'absolute'

                ///Set base options for all export types
                if (drvType == "KML")
                {
                    drvType = "LIBKML";
                }
                List <string> ogr2ogrOptions = new List <string> {
                    "-overwrite",
                    "-f", drvType,
                    "-dim", "XYZ",
                    "-skipfailures",

                    //"-lco", "LIBKML_STRICT_COMPLIANCE=FALSE",
                    //"-lco", "AltitudeMode=absolute",

                    //"-dsco", "SHAPE_REWIND_ON_WRITE=YES"
                };

                Dataset src = Gdal.OpenEx("/vsimem/out.geojson", 0, null, null, null);

                if (drvType != "ESRI Shapefile")
                {
                    Dataset destDataset = Gdal.wrapper_GDALVectorTranslateDestName(shpPath, src, new GDALVectorTranslateOptions(ogr2ogrOptions.ToArray()), null, null);
                    destDataset.Dispose();
                    shpPathList.Add(shpPath);
                }

                ///Export multiple layers for shapefile
                ///https://trac.osgeo.org/gdal/wiki/FAQVector#HowdoItranslateamixedgeometryfiletoshapefileformat
                else
                {
                    ///
                    if (shpTypeList.Count <= 1 && shpTypeList.First() != "GEOMETRYCOLLECTION")
                    {
                        if (shpTypeList.First() == "POLYGON" || shpTypeList.First() == "MULTIPOLYGON")
                        {
                            ogr2ogrOptions.AddRange(new List <string> {
                                "-lco", "SHPT=MULTIPATCH"
                            });
                        }
                        Dataset destDataset = Gdal.wrapper_GDALVectorTranslateDestName(shpPath, src, new GDALVectorTranslateOptions(ogr2ogrOptions.ToArray()), null, null);
                        destDataset.Dispose();
                        shpPathList.Add(shpPath);
                    }

                    else
                    {
                        ///Add -explodecollections for mixed geometries in a branch
                        ///"-where" statement is not necessary, but could speed up big datasets

                        string        shpFileName       = string.Empty;
                        List <string> ogr2ogrShpOptions = new List <string>();

                        if (shpTypeList.Contains("POINT") || shpTypeList.Contains("MULTIPOINT"))
                        {
                            shpFileName = folder + filename + "_points.shp";
                            shpPathList.Add(shpFileName);
                            List <string> ogr2ogrShpOptionsPts = new List <string> {
                                "-overwrite",
                                "-f", drvType,
                                "-dim", "XYZ",
                                "-skipfailures"
                            };
                            //ogr2ogrShpOptionsPts.AddRange(new List<string> { "-where", "ogr_geometry=POINT", "-where", "ogr_geometry=MULTIPOINT", "-lco", "SHPT=MULTIPOINTZ", "-nlt", "PROMOTE_TO_MULTI"});
                            ogr2ogrShpOptionsPts.AddRange(new List <string> {
                                "-sql", "SELECT * FROM " + filename + " WHERE OGR_GEOMETRY='MULTIPOINT' OR OGR_GEOMETRY='POINT'", "-lco", "SHPT=MULTIPOINTZ", "-nlt", "PROMOTE_TO_MULTI"
                            });
                            //ogr2ogrShpOptionsPts.AddRange(new List<string> { "-dialect", "sqlite", "-sql", "select * from " + filename + " where GeometryType(geometry) in ('POINT','MULTIPOINT')", "-lco", "SHPT=MULTIPOINTZ", "-nlt", "PROMOTE_TO_MULTI" });

                            Dataset destDatasetPoint = Gdal.wrapper_GDALVectorTranslateDestName(shpFileName, src, new GDALVectorTranslateOptions(ogr2ogrShpOptionsPts.ToArray()), null, null);
                            destDatasetPoint.Dispose();
                        }

                        if (shpTypeList.Contains("LINESTRING") || shpTypeList.Contains("MULTILINESTRING"))
                        {
                            shpFileName = folder + filename + "_lines.shp";
                            shpPathList.Add(shpFileName);
                            List <string> ogr2ogrShpOptionsLines = new List <string> {
                                "-overwrite",
                                "-f", drvType,
                                "-dim", "XYZ",
                                "-skipfailures"
                            };
                            //ogr2ogrShpOptionsLines.AddRange(new List<string> { "-where", "ogr_geometry=LINESTRING25D", "-where", "ogr_geometry=MULTILINESTRING25D", "-lco", "SHPT=ARCZ", "-nlt", "PROMOTE_TO_MULTI" });
                            ogr2ogrShpOptionsLines.AddRange(new List <string> {
                                "-sql", "SELECT * FROM " + filename + " WHERE OGR_GEOMETRY='LINESTRING' OR OGR_GEOMETRY='MULTILINESTRING'", "-lco", "SHPT=ARCZ", "-nlt", "PROMOTE_TO_MULTI"
                            });
                            //ogr2ogrShpOptionsLines.AddRange(new List<string> { "-dialect", "sqlite", "-sql", "select * from " + filename + " where GeometryType(geometry) in ('LINESTRING','MULTILINESTRING')", "-lco", "SHPT=ARCZ", "-nlt", "PROMOTE_TO_MULTI" });

                            Dataset destDatasetLinestring = Gdal.wrapper_GDALVectorTranslateDestName(shpFileName, src, new GDALVectorTranslateOptions(ogr2ogrShpOptionsLines.ToArray()), null, null);
                            destDatasetLinestring.Dispose();
                        }

                        if (shpTypeList.Contains("POLYGON") || shpTypeList.Contains("MULTIPOLYGON"))
                        {
                            shpFileName = folder + filename + "_polygons.shp";
                            shpPathList.Add(shpFileName);
                            List <string> ogr2ogrShpOptionsPolygons = new List <string> {
                                "-overwrite",
                                "-f", drvType,
                                "-dim", "XYZ",
                                "-skipfailures",
                                "-dsco", "SHAPE_REWIND_ON_WRITE=NO"
                            };
                            //ogr2ogrShpOptionsPolygons.AddRange(new List<string> { "-where", "ogr_geometry=POLYGON", "-where", "ogr_geometry=MULTIPOLYGON", "-lco", "SHPT=POLYGONZ", "-nlt", "PROMOTE_TO_MULTI" });
                            ogr2ogrShpOptionsPolygons.AddRange(new List <string> {
                                "-sql", "SELECT * FROM " + filename + " WHERE OGR_GEOMETRY='MULTIPOLYGON25D' OR OGR_GEOMETRY='POLYGON25D'", "-lco", "SHPT=POLYGONZ", "-nlt", "PROMOTE_TO_MULTI"
                            });
                            Dataset destDatasetPolygon = Gdal.wrapper_GDALVectorTranslateDestName(shpFileName, src, new GDALVectorTranslateOptions(ogr2ogrShpOptionsPolygons.ToArray()), null, null);
                            destDatasetPolygon.Dispose();
                        }

                        ///Not working properly when multiple geometry types are part of the same branch for SHP export.
                        if (shpTypeList.Contains("GEOMETRYCOLLECTION"))
                        {
                            AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "One or more branches contain a mix of geometry types.");
                            ///export points
                            shpFileName = folder + filename + "_gc-points.shp";
                            shpPathList.Add(shpFileName);
                            List <string> ogr2ogrShpOptionsGCPts = new List <string> {
                                "-overwrite",
                                "-f", drvType,
                                "-dim", "XYZ",
                                "-skipfailures"
                            };
                            ogr2ogrShpOptionsGCPts.AddRange(new List <string> {
                                "-explodecollections", "-where", "ogr_geometry=GEOMETRYCOLLECTION", "-lco", "SHPT=MULTIPOINTZ", "-nlt", "PROMOTE_TO_MULTI"
                            });
                            //ogr2ogrShpOptionsGCPts.AddRange(new List<string> { "-explodecollections", "-sql", "SELECT * FROM " + filename + " WHERE OGR_GEOMETRY='MULTIPOINT' OR OGR_GEOMETRY='POINT'", "-lco", "SHPT=MULTIPOINTZ", "-nlt", "PROMOTE_TO_MULTI" });

                            Dataset destDatasetGCPoints = Gdal.wrapper_GDALVectorTranslateDestName(shpFileName, src, new GDALVectorTranslateOptions(ogr2ogrShpOptionsGCPts.ToArray()), null, null);
                            destDatasetGCPoints.Dispose();

                            ///export lines
                            shpFileName = folder + filename + "_gc-lines.shp";
                            shpPathList.Add(shpFileName);
                            List <string> ogr2ogrShpOptionsGCLines = new List <string> {
                                "-overwrite",
                                "-f", drvType,
                                "-dim", "XYZ",
                                "-skipfailures"
                            };
                            ogr2ogrShpOptionsGCLines.AddRange(new List <string> {
                                "-explodecollections", "-where", "ogr_geometry=GEOMETRYCOLLECTION", "-lco", "SHPT=ARCZ", "-nlt", "PROMOTE_TO_MULTI"
                            });
                            //ogr2ogrShpOptionsGCLines.AddRange(new List<string> { "-explodecollections", "-sql", "SELECT * FROM " + filename + " WHERE OGR_GEOMETRY='MULTILINESTRING25D' OR OGR_GEOMETRY='LINESTRING25D'", "-lco", "SHPT=ARCZ", "-nlt", "PROMOTE_TO_MULTI" });
                            Dataset destDatasetGCLines = Gdal.wrapper_GDALVectorTranslateDestName(shpFileName, src, new GDALVectorTranslateOptions(ogr2ogrShpOptionsGCLines.ToArray()), null, null);
                            destDatasetGCLines.Dispose();

                            ///export meshes
                            shpFileName = folder + filename + "_gc-polygons.shp";
                            shpPathList.Add(shpFileName);
                            List <string> ogr2ogrShpOptionsGCPolygons = new List <string> {
                                "-overwrite",
                                "-f", drvType,
                                "-dim", "XYZ",
                                "-skipfailures",
                                "-dsco", "SHAPE_REWIND_ON_WRITE=NO"
                            };
                            ogr2ogrShpOptionsGCPolygons.AddRange(new List <string> {
                                "-explodecollections", "-where", "ogr_geometry=GEOMETRYCOLLECTION", "-lco", "SHPT=POLYGONZ", "-nlt", "PROMOTE_TO_MULTI"
                            });
                            //ogr2ogrShpOptionsGCPolygons.AddRange(new List<string> { "-explodecollections", "-sql", "SELECT * FROM " + filename + " WHERE OGR_GEOMETRY='MULTIPOLYGON' OR OGR_GEOMETRY='POLYGON'", "-lco", "SHPT=POLYGONZ", "-nlt", "PROMOTE_TO_MULTI" });
                            Dataset destDatasetGCPolygons = Gdal.wrapper_GDALVectorTranslateDestName(shpFileName, src, new GDALVectorTranslateOptions(ogr2ogrShpOptionsGCPolygons.ToArray()), null, null);
                            destDatasetGCPolygons.Dispose();
                        }
                    }
                }

                ///Clean up
                Gdal.Unlink("/vsimem/out.geojson");
            }

            DA.SetDataList(0, shpPathList);
        }
Пример #8
0
        /// <summary>
        /// 写shp文件
        /// </summary>
        /// <param name="lstAttribute"></param>
        /// <param name="geometryType"></param>
        /// <param name="lstWkt"></param>
        /// <param name="lstAttributeObj"></param>
        /// <param name="srsWkt"></param>
        /// <returns></returns>
        public bool DoExport(List <AttributeModel> lstAttribute, OSGeo.OGR.wkbGeometryType geometryType, List <string> lstWkt, List <AttributeObj> lstAttributeObj, string srsWkt)
        {
            _lstAttribute    = lstAttribute;
            _geoType         = geometryType;
            _lstWkt          = lstWkt;
            _lstAttributeObj = lstAttributeObj;

            try
            {
                //注册
                string pszDriverName = "ESRI Shapefile";

                //调用对Shape文件读写的Driver接口
                OSGeo.OGR.Driver poDriver = OSGeo.OGR.Ogr.GetDriverByName(pszDriverName);
                if (poDriver == null)
                {
                    throw new Exception("Driver Error");
                }

                //用此Driver创建Shape文件
                OSGeo.OGR.DataSource poDS;
                poDS = poDriver.CreateDataSource(_shpFileName, null);
                if (poDS == null)
                {
                    throw new Exception("DataSource Creation Error");
                }

                //定义坐标系
                OSGeo.OSR.SpatialReference srs = new OSGeo.OSR.SpatialReference(srsWkt);
                //创建层Layer
                OSGeo.OGR.Layer poLayer   = null;
                string          layerName = Path.GetFileNameWithoutExtension(_shpFileName);
                poLayer = poDS.CreateLayer(layerName, srs, _geoType, null);

                if (poLayer == null)
                {
                    throw new Exception("Layer Creation Failed");
                }

                //创建属性列
                foreach (AttributeModel att in _lstAttribute)
                {
                    OSGeo.OGR.FieldDefn oField = new OSGeo.OGR.FieldDefn(att.AttributeName, att.AttributeType);
                    //if (att.AttributeWidth > 0)
                    //{
                    oField.SetWidth(att.AttributeWidth);
                    //}
                    oField.SetPrecision(att.AttributePrecision);


                    poLayer.CreateField(oField, att.AttributeApproxOK);
                }

                //创建一个Feature,一个Geometry
                OSGeo.OGR.Feature         poFeature  = new OSGeo.OGR.Feature(poLayer.GetLayerDefn());
                OSGeo.OGR.wkbGeometryType wkbGeotype = OSGeo.OGR.wkbGeometryType.wkbGeometryCollection;
                OSGeo.OGR.Geometry        geo        = new OSGeo.OGR.Geometry(wkbGeotype);

                for (int i = 0; i < _lstWkt.Count; i++)
                {
                    foreach (KeyValuePair <string, string> item in _lstAttributeObj[i].AttributeValue)
                    {
                        poFeature.SetField(item.Key, item.Value);
                    }
                    geo = OSGeo.OGR.Geometry.CreateFromWkt(_lstWkt[i]);
                    poFeature.SetGeometry(geo);
                    poLayer.CreateFeature(poFeature);
                }
                //关闭文件读写
                poFeature.Dispose();
                poDS.Dispose();

                return(true);
            }
            catch (System.Exception e)
            {
                return(false);
                //throw new Exception(e.Message);
            }
        }