Example #1
0
        //分块清理,提高效率
        public static OSGeo.OGR.Layer cleanLayer_Cut(OSGeo.OGR.Layer pdLayer, double minArea, double maxArea, double maxCha = 1)
        {
            List <CutBox> Tree = buildTree(pdLayer);


            shpDataSet.deleteLayerByName("pdClear");
            OSGeo.OGR.Layer    outLayer = shpDataSet.CreateLayer("pdClear", pdLayer.GetSpatialRef(), pdLayer.GetGeomType(), null);
            OSGeo.OGR.Envelope oriEnve  = new OSGeo.OGR.Envelope();
            OSGeo.OGR.Envelope nextEnve = new OSGeo.OGR.Envelope();
            StaticTools.msgLine("clean SlopeLine...");
            for (int c = 0; c < Tree.Count; c++)
            {
                CutBox cb        = Tree[c];
                int    featCount = cb.pdxIDs.Count;

                for (int i = 0; i < featCount - 1; i++)
                {
                    bool isOnly               = true;
                    OSGeo.OGR.Feature ori     = pdLayer.GetFeature(cb.pdxIDs[i]);
                    double            oriArea = ori.GetGeometryRef().GetArea();

                    if (oriArea < minArea || oriArea > maxArea)
                    {
                        //判断当前要素的面积,过小或过大时,认为其有相同的图形,不加入新的Layer
                        isOnly = false;
                    }
                    else
                    {
                        //判断当前要素与其它要素的包围盒的对应边,差值都小于阈值时,认为是相同的图形,需要跳过
                        //没有相同的图型时,isOnly为true ,塞到新的layer里
                        ori.GetGeometryRef().GetEnvelope(oriEnve);
                        for (int j = i + 1; j < featCount; j++)
                        {
                            pdLayer.GetFeature(cb.pdxIDs[j]).GetGeometryRef().GetEnvelope(nextEnve);
                            if (Math.Abs(oriEnve.MaxX - nextEnve.MaxX) < maxCha &&
                                Math.Abs(oriEnve.MaxY - nextEnve.MaxY) < maxCha &&
                                Math.Abs(oriEnve.MinX - nextEnve.MinX) < maxCha &&
                                Math.Abs(oriEnve.MinY - nextEnve.MinY) < maxCha)
                            {
                                isOnly = false;
                                break;
                            }
                        }
                    }
                    if (isOnly)
                    {
                        outLayer.CreateFeature(ori);
                    }
                    StaticTools.progress((i + 2) * 100 / featCount, $"{i + 1} / {featCount}");
                }
            }

            if (IsDelete)
            {
                shpDataSet.deleteLayerByName(pdLayer.GetName());
            }

            return(outLayer);
        }
Example #2
0
        private static void _标准差(string dzx, out double aue, out double bzc)
        {
            OSGeo.OGR.Ogr.RegisterAll();
            OSGeo.OGR.Driver     dr       = OSGeo.OGR.Ogr.GetDriverByName("ESRI shapefile");
            OSGeo.OGR.DataSource dzxDS    = dr.Open(dzx, 0);
            OSGeo.OGR.Layer      dzxLayer = dzxDS.GetLayerByIndex(0);

            //获取Featuer数
            int featCount = dzxLayer.GetFeatureCount(0);

            // 1 拿到每个Featuer的Value
            double[] values = new double[featCount];
            for (int i = 0; i < featCount; i++)
            {
                OSGeo.OGR.Feature  fileFeat = dzxLayer.GetFeature(i);
                OSGeo.OGR.Geometry fileGeom = fileFeat.GetGeometryRef();
                values[i] = fileFeat.GetFieldAsDouble("EVE");
                fileGeom.Dispose();
                fileFeat.Dispose();
            }
            dzxDS.Dispose();
            // 2 求Values的平均值
            aue = values.Average();

            // 3 求values与平均值差的平方和
            double pingFangHe = 0;

            for (int i = 0; i < featCount; i++)
            {
                pingFangHe += (values[i] - aue) * (values[i] - aue);
            }
            // 4 每个值与平均值的差相加,除Featuer数.再开方,得到标准差
            bzc = Math.Sqrt(pingFangHe / featCount);
        }
Example #3
0
        static void getMinOutLineFromLayerToLayer(OSGeo.OGR.Layer inLayer)
        {
            shpDataSet.deleteLayerByName("minOutLine");
            OSGeo.OGR.Layer   minoutline = shpDataSet.CreateLayer("minOutLine", inLayer.GetSpatialRef(), inLayer.GetGeomType(), null);
            OSGeo.OGR.Feature aFeat      = null;

            StaticTools.msgLine("getMinOutline...");
            int featCount = inLayer.GetFeatureCount(0);

            for (int i = 0; i < featCount; i++)
            {
                aFeat = inLayer.GetFeature(i);
                OSGeo.OGR.Geometry oGeometry = aFeat.GetGeometryRef();
                OSGeo.OGR.Geometry ogeo      = oGeometry.GetGeometryRef(0);
                QTGeometry         qtGeo     = new QTGeometry(ogeo);
                minoutline.CreateFeature(qtGeo.GetSMBR());
                StaticTools.progress((i + 1) * 100 / featCount, $"{i} / {featCount}");
            }
            minoutline.Dispose();
            //inLayer.ResetReading();
            //while ((aFeat = inLayer.GetNextFeature()) != null)
            //{
            //    OSGeo.OGR.Geometry oGeometry = aFeat.GetGeometryRef();
            //    OSGeo.OGR.Geometry ogeo = oGeometry.GetGeometryRef(0);
            //    QTGeometry qtGeo = new QTGeometry(ogeo);
            //    minoutline.CreateFeature(qtGeo.GetSMBR());
            //}
        }
Example #4
0
        /// <summary>
        /// 通过ID数组提取出所有要素
        /// </summary>
        /// <param name="dzLine"></param>
        /// <param name="pdLing"></param>
        /// <param name="savePath"></param>
        public static void selectFeat(string dzLine, string pdLing, string savePath)
        {
            //获得数组
            int[] a = getMinIdGroup(dzLine, pdLing);

            OSGeo.OGR.Ogr.RegisterAll();
            OSGeo.OGR.Driver dr = OSGeo.OGR.Ogr.GetDriverByName("ESRI shapefile");
            //读取原Layer
            OSGeo.OGR.DataSource dzDS    = dr.Open(dzLine, 0);
            OSGeo.OGR.Layer      dzLayer = dzDS.GetLayerByIndex(0);
            //新建Layer
            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++)
            {
                OSGeo.OGR.Feature  dzFeat   = dzLayer.GetFeature(a[i]);
                OSGeo.OGR.Geometry dzGeom   = dzFeat.GetGeometryRef();
                OSGeo.OGR.Geometry fileGeom = dzGeom;
                OSGeo.OGR.Feature  fileFeat = new OSGeo.OGR.Feature(dzFeat.GetDefnRef());
                fileFeat.SetGeometry(fileGeom);
                fileLayer.CreateFeature(dzFeat);
            }
            fileLayer.Dispose();
            ds.Dispose();
            dzDS.Dispose();
        }
Example #5
0
        public void QueryShape(IGeometry pGeometry)
        {
            if (pGeometry == null)
            {
                return;
            }

            try
            {
                OSGeo.OGR.Geometry ogrGeometry = m_currentOGRFeature.GetGeometryRef();

                //export geometry from OGR to WKB
                int    wkbSize   = ogrGeometry.WkbSize();
                byte[] wkbBuffer = new byte[wkbSize];
                ogrGeometry.ExportToWkb(wkbBuffer);

                //import geometry from WKB to ESRI Shape
                IWkb pWKB = pGeometry as IWkb;
                pWKB.ImportFromWkb(wkbSize, ref wkbBuffer[0]);

                pGeometry.SpatialReference = m_pDataset.SpatialReference;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(" Error: " + ex.Message);
                pGeometry.SetEmpty();
            }
        }
Example #6
0
        /*************************************************************************************************/



        /***************************读入SHP文件***************************/
        /// <summary>
        /// shpPolygon To List<Point[]>
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static List <Point[]> shpPolygonToPointGL(string filePath)
        {
            List <Point[]> allFeature = new List <Point[]>();

            OSGeo.OGR.Ogr.RegisterAll();
            OSGeo.OGR.Driver     dr        = OSGeo.OGR.Ogr.GetDriverByName("ESRI shapefile");
            OSGeo.OGR.DataSource ds        = dr.Open(filePath, 0);
            OSGeo.OGR.Layer      fileLayer = ds.GetLayerByIndex(0);

            int FeatCount = fileLayer.GetFeatureCount(0);

            for (int u = 0; u < FeatCount; u++)
            {
                OSGeo.OGR.Feature  fileFeature = fileLayer.GetFeature(u);
                OSGeo.OGR.Geometry fileGeom    = fileFeature.GetGeometryRef();
                OSGeo.OGR.Geometry subGeom     = fileGeom.GetGeometryRef(0);
                int     k     = subGeom.GetPointCount();
                Point[] aFeat = new Point[k];
                for (int i = 0; i < k; i++)
                {
                    aFeat[i].X = subGeom.GetX(i);
                    aFeat[i].Y = subGeom.GetY(i);
                    aFeat[i].Z = subGeom.GetZ(i);
                }
                allFeature.Add(aFeat);
            }
            return(allFeature);
        }
        /********************************   等值线转换为多边形   ***********************************************/

        /// <summary>
        /// 等值线转为POLYGON
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static string dzPoly(string filePath)
        {
            OSGeo.OGR.Ogr.RegisterAll();
            OSGeo.OGR.Driver dr = OSGeo.OGR.Ogr.GetDriverByName("ESRI shapefile");

            string a = StaticTools.tempFilePath("shp", "等值线POLY");

            OSGeo.OGR.DataSource newDS     = dr.CreateDataSource(a, null);
            OSGeo.OGR.Layer      polyLayer = newDS.CreateLayer("", null, OSGeo.OGR.wkbGeometryType.wkbPolygon, null);
            OSGeo.OGR.FieldDefn  fieldDf0  = new OSGeo.OGR.FieldDefn("LID", OSGeo.OGR.FieldType.OFTInteger);
            OSGeo.OGR.FieldDefn  fieldDf1  = new OSGeo.OGR.FieldDefn("EVE", OSGeo.OGR.FieldType.OFTReal);
            polyLayer.CreateField(fieldDf0, 1); //ID
            polyLayer.CreateField(fieldDf1, 1); //Value
            OSGeo.OGR.FeatureDefn featDF = new OSGeo.OGR.FeatureDefn("");
            Console.WriteLine("开始等值线转POLY!");
            OSGeo.OGR.DataSource cleanDS    = dr.Open(filePath, 0);
            OSGeo.OGR.Layer      cleanLayer = cleanDS.GetLayerByIndex(0);
            for (int i = 0; i < cleanLayer.GetFeatureCount(0); i++)
            {
                OSGeo.OGR.Feature  lineFeat = cleanLayer.GetFeature(i);
                OSGeo.OGR.Geometry lineGeom = lineFeat.GetGeometryRef();

                OSGeo.OGR.Feature  polyFeat = new OSGeo.OGR.Feature(featDF);
                OSGeo.OGR.Geometry polyGeom = new OSGeo.OGR.Geometry(OSGeo.OGR.wkbGeometryType.wkbPolygon);
                OSGeo.OGR.Geometry subGeom  = new OSGeo.OGR.Geometry(OSGeo.OGR.wkbGeometryType.wkbLinearRing);
                int u = lineGeom.GetPointCount();
                for (int s = 0; s < u; s++)
                {
                    double x = lineGeom.GetX(s);
                    double y = lineGeom.GetY(s);
                    double z = lineGeom.GetZ(s);
                    subGeom.AddPoint(x, y, z);
                }
                polyGeom.AddGeometry(subGeom);
                polyFeat.SetGeometry(polyGeom);
                polyLayer.CreateFeature(polyFeat);
                lineGeom.Dispose();
                polyGeom.Dispose();
                subGeom.Dispose();
                lineFeat.Dispose();
                polyFeat.Dispose();
            }
            cleanLayer.Dispose();
            polyLayer.Dispose();
            cleanDS.Dispose();
            newDS.Dispose();
            Console.WriteLine("等值线转POLY完成!");
            return(a);
        }
Example #8
0
        /// <summary>
        /// 清理Layer中重复的,面积过小的featuer,返回一个新的Layer
        /// </summary>
        /// <param name="inLayer">源layer</param>
        /// <param name="andArea">是否判断最小面积</param>
        /// <param name="minArea">最小面积</param>
        /// <returns></returns>
        public static OSGeo.OGR.Layer cleanLayer_FF(OSGeo.OGR.Layer inLayer)
        {
            string oldLayerName = inLayer.GetName();
            string newLayerName = oldLayerName + "Clear";

            shpDataSet.deleteLayerByName(newLayerName);
            OSGeo.OGR.Layer outLayer = shpDataSet.CreateLayer(newLayerName, srs, inLayer.GetGeomType(), null);

            int featCount = inLayer.GetFeatureCount(0);

            StaticTools.msgLine($"clean resLine... before {featCount}");
            for (int i = 0; i < featCount - 1; i++)
            {
                bool isOnly                = true;
                OSGeo.OGR.Feature  ori     = inLayer.GetFeature(i);
                OSGeo.OGR.Envelope oriEnve = new OSGeo.OGR.Envelope();
                ori.GetGeometryRef().GetEnvelope(oriEnve);
                double maxCha = 1;
                for (int j = i + 1; j < featCount; j++)
                {
                    OSGeo.OGR.Feature  next     = inLayer.GetFeature(j);
                    OSGeo.OGR.Envelope nextEnve = new OSGeo.OGR.Envelope();
                    next.GetGeometryRef().GetEnvelope(nextEnve);
                    if (Math.Abs(oriEnve.MaxX - nextEnve.MaxX) < maxCha &&
                        Math.Abs(oriEnve.MaxY - nextEnve.MaxY) < maxCha &&
                        Math.Abs(oriEnve.MinX - nextEnve.MinX) < maxCha &&
                        Math.Abs(oriEnve.MinY - nextEnve.MinY) < maxCha)
                    {
                        isOnly = false;
                        break;
                    }
                }
                if (isOnly)
                {
                    outLayer.CreateFeature(ori);
                }
                ori.Dispose();
                StaticTools.progress((i + 2) * 100 / featCount, $"{i + 1} / {featCount}");
            }
            if (IsDelete)
            {
                shpDataSet.deleteLayerByName(inLayer.GetName());
            }
            StaticTools.msgLine($"clean resLine... after {outLayer.GetFeatureCount(0)}");
            return(outLayer);
        }
Example #9
0
        /// <summary>
        /// 清理等值线上的点
        /// </summary>
        /// <param name="filePath"></param>
        public static void claenPoint(string filePath)
        {
            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(filePath.Substring(0, filePath.LastIndexOf(".")) + "_targ.shp"))
            {
                // UsefullTools.deleteFiles(filePath.Substring(0, filePath.LastIndexOf(".")) + "_targ.shp");
            }
            OSGeo.OGR.DataSource targDs    = dr.CreateDataSource(filePath.Substring(0, filePath.LastIndexOf(".")) + "_targ.shp", 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
                OSGeo.OGR.Feature newFeat = JID(aFeat);

                if (newFeat != null)
                {
                    targLayer.CreateFeature(newFeat);
                }
            }
            oriDs.Dispose();
            targDs.Dispose();
        }
Example #10
0
        /**************************************   清理等值线   *****************************************/
        /// <summary>
        /// 通过线长,值 清理等值线
        /// </summary>
        /// <param name="filePath"></param>
        public static string cleanDS(string dzx)
        {
            Console.WriteLine("开始清理等值线!");
            double aue, bzc; _标准差(dzx, out aue, out bzc);
            double minLength = 50;
            double maxLength = 2600;
            double minValue  = aue - bzc * 2;
            double maxValue  = aue + bzc * 2;

            //open dzx
            OSGeo.OGR.Ogr.RegisterAll();
            OSGeo.OGR.Driver     dr       = OSGeo.OGR.Ogr.GetDriverByName("ESRI shapefile");
            OSGeo.OGR.DataSource dzxDS    = dr.Open(dzx, 0);
            OSGeo.OGR.Layer      dzxLayer = dzxDS.GetLayerByIndex(0);
            //new a shp
            string cleanline = StaticTools.tempFilePath("shp", "清理后的等值线");

            OSGeo.OGR.DataSource newdzxDS    = dr.CreateDataSource(cleanline, null);
            OSGeo.OGR.Layer      newdzxLayer = newdzxDS.CreateLayer(dzxLayer.GetName(), dzxLayer.GetSpatialRef(), dzxLayer.GetGeomType(), null);

            for (int i = 0; i < dzxLayer.GetFeatureCount(0); i++)
            {
                OSGeo.OGR.Feature  fileFeat = dzxLayer.GetFeature(i);
                OSGeo.OGR.Geometry fileGeom = fileFeat.GetGeometryRef();

                double FeatLength = fileGeom.Length();
                bool   s1         = FeatLength > minLength && FeatLength < maxLength;

                double featValue = fileFeat.GetFieldAsDouble("EVE");
                bool   s2        = featValue > minValue && featValue < maxValue;

                bool isR = fileGeom.IsRing();
                if (s1 && s2 && isR)
                {
                    newdzxLayer.CreateFeature(fileFeat);
                }
                fileFeat.Dispose();
            }
            newdzxDS.Dispose();
            dzxDS.Dispose();
            Console.WriteLine("清理等值线完成!");
            return(cleanline);
        }
Example #11
0
        /// <summary>
        /// 判断两个Featuer是否重复,两外接矩形相同位置的边差小于1时为true
        /// </summary>
        /// <param name="ori"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public static bool isSame(OSGeo.OGR.Feature ori, OSGeo.OGR.Feature next, double maxCha = 1)
        {
            OSGeo.OGR.Envelope oriEnve = new OSGeo.OGR.Envelope();
            ori.GetGeometryRef().GetEnvelope(oriEnve);
            OSGeo.OGR.Envelope nextEnve = new OSGeo.OGR.Envelope();
            next.GetGeometryRef().GetEnvelope(nextEnve);

            if (Math.Abs(oriEnve.MaxX - nextEnve.MaxX) < maxCha && //外接矩形差
                Math.Abs(oriEnve.MaxY - nextEnve.MaxY) < maxCha &&
                Math.Abs(oriEnve.MinX - nextEnve.MinX) < maxCha &&
                Math.Abs(oriEnve.MinY - nextEnve.MinY) < maxCha)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Example #12
0
        /// <summary>
        /// 获取与一个Feature有关的Raster参数,[0]offX,[1]offY,[2]sizeX,[3]sizeY
        /// </summary>
        /// <param name="Trans"></param>
        /// <param name="aFeat"></param>
        /// <returns></returns>
        private static int[] subRasterInfo(double[] Trans, int xSize, int ySize, OSGeo.OGR.Feature aFeat)
        {
            //拿到Buffer Featuer的壳
            OSGeo.OGR.Geometry bufGeom = aFeat.GetGeometryRef();
            OSGeo.OGR.Envelope bufEnve = new OSGeo.OGR.Envelope();
            bufGeom.GetEnvelope(bufEnve);
            //判断壳是否超出全局范围,是则赋边界值
            double maxX, minY;

            StaticTools.imageToGeoSpace(Trans, xSize, ySize, out maxX, out minY);
            if (bufEnve.MinX < Trans[0])
            {
                bufEnve.MinX = Trans[0];
            }
            if (bufEnve.MaxY > Trans[3])
            {
                bufEnve.MaxY = Trans[3];
            }
            if (bufEnve.MaxX > maxX)
            {
                bufEnve.MaxX = maxX;
            }
            if (bufEnve.MinY < minY)
            {
                bufEnve.MinY = minY;
            }

            //通过壳坐标拿到SubRaster的起点及行列数
            var a = new int[4];
            int leftUpX, leftUpY, rightDownX, rightDownY;

            StaticTools.geoToImageSpace(Trans, bufEnve.MinX, bufEnve.MaxY, out leftUpX, out leftUpY);
            StaticTools.geoToImageSpace(Trans, bufEnve.MaxX, bufEnve.MinY, out rightDownX, out rightDownY);

            a[0] = leftUpX;
            a[1] = leftUpY;
            a[2] = Math.Abs(rightDownX - leftUpX);
            a[3] = Math.Abs(leftUpY - rightDownY);
            bufGeom.Dispose();
            bufEnve.Dispose();
            return(a);
        }
Example #13
0
        /// <summary>
        /// 通过线长,值 清理等值线
        /// </summary>
        /// <param name="dzx"></param>
        /// <returns></returns>
        static OSGeo.OGR.Layer cleanDZX(OSGeo.OGR.Layer dzxLayer)
        {
            //创建poly层
            shpDataSet.deleteLayerByName("dzPoly");
            OSGeo.OGR.Layer newdzxLayer = shpDataSet.CreateLayer("dzPoly", dzxLayer.GetSpatialRef(), OSGeo.OGR.wkbGeometryType.wkbPolygon, null);

            //aue平均值,bzc标准差
            double aue, bzc;

            StaticTools.getBZC(dzxLayer, out aue, out bzc);
            //清理过大和过小的高度值,取值范围为平均值两则,2倍的标准差,约为95.4%
            double minValue     = aue - bzc * sec;
            double maxValue     = aue + bzc * sec;
            int    FeatureCount = dzxLayer.GetFeatureCount(0);

            StaticTools.msgLine("cleanDZX...");
            for (int i = 0; i < FeatureCount; i++)
            {
                OSGeo.OGR.Feature  fileFeat = dzxLayer.GetFeature(i);
                OSGeo.OGR.Geometry fileGeom = fileFeat.GetGeometryRef();

                if (fileGeom.IsRing() &&//判断闭合
                    fileFeat.GetFieldAsDouble("EVE") > minValue &&
                    fileFeat.GetFieldAsDouble("EVE") < maxValue && //判断值
                    fileGeom.Length() > minLength &&
                    fileGeom.Length() < maxLength)    //判断长度
                {
                    OSGeo.OGR.Feature newFeat = polyFeat(fileGeom);
                    newdzxLayer.CreateFeature(newFeat);
                    StaticTools.progress((i + 1) * 100 / FeatureCount, $"{i} / {FeatureCount}");
                }
            }
            StaticTools.progress(100);
            if (IsDelete)
            {
                shpDataSet.deleteLayerByName(dzxLayer.GetName());
            }

            return(newdzxLayer);
        }
Example #14
0
        /// <summary>
        /// shpPoint To Point[]
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static Point[] shpPointtoPointG(string filePath)
        {
            var temp = new List <Point>();

            OSGeo.OGR.Ogr.RegisterAll();
            OSGeo.OGR.Driver     dr        = OSGeo.OGR.Ogr.GetDriverByName("ESRI shapefile");
            OSGeo.OGR.DataSource ds        = dr.Open(filePath, 0);
            OSGeo.OGR.Layer      fileLayer = ds.GetLayerByIndex(0);
            int FeatCount = fileLayer.GetFeatureCount(0);

            for (int i = 0; i < FeatCount; i++)
            {
                OSGeo.OGR.Feature  fileFeature = fileLayer.GetFeature(i);
                OSGeo.OGR.Geometry fileGeom    = fileFeature.GetGeometryRef();
                var newPoint = new Point();
                newPoint.X = fileGeom.GetX(0);
                newPoint.Y = fileGeom.GetY(0);
                newPoint.Z = fileGeom.GetZ(0);
                temp.Add(newPoint);
            }
            return(temp.ToArray());
        }
Example #15
0
        public static void claenPoint(this OSGeo.OGR.Layer resLayer, double jiaodu, int cishu)
        {
            int featCount = resLayer.GetFeatureCount(0);

            for (int i = 0; i < featCount; i++)
            {
                OSGeo.OGR.Feature  oriFeat = resLayer.GetFeature(i);
                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);
                }

                OSGeo.OGR.Geometry newGeom = null;
                if (aFeat.Length > cishu * 3)
                {
                    newGeom = JID(aFeat, jiaodu, cishu);
                }
                else
                {
                    oriFeat.Dispose();
                    continue;
                }
                if (newGeom != null)
                {
                    oriFeat.SetGeometry(newGeom);
                    resLayer.SetFeature(oriFeat);
                }
                oriFeat.Dispose();
            }
        }
Example #16
0
        /// <summary>
        /// 创建一个Buffer file,用于获取最小高度,juli是buffer的距离
        /// </summary>
        /// <param name="infile"></param>
        /// <param name="juli"></param>
        /// <returns></returns>
        private static OSGeo.OGR.Layer bufferFile(OSGeo.OGR.Layer inLayer, int juli)
        {
            string buf = inLayer.GetName() + "buf";

            shpDataSet.deleteLayerByName(buf);
            OSGeo.OGR.Layer bufferLayer = shpDataSet.CreateLayer(buf, inLayer.GetSpatialRef(), inLayer.GetGeomType(), null);

            int featCount = inLayer.GetFeatureCount(0);

            for (int i = 0; i < featCount; i++)
            {
                OSGeo.OGR.Feature  inFeat  = inLayer.GetFeature(i);
                OSGeo.OGR.Geometry inGeom  = inFeat.GetGeometryRef();
                OSGeo.OGR.Geometry outGeom = inGeom.Buffer(juli, 0);
                OSGeo.OGR.Feature  outFeat = new OSGeo.OGR.Feature(new OSGeo.OGR.FeatureDefn(""));
                outFeat.SetGeometry(outGeom);
                bufferLayer.CreateFeature(outFeat);
                inFeat.Dispose();
                outFeat.Dispose();
            }
            return(bufferLayer);
        }
Example #17
0
        public void QueryShape(IGeometry pGeometry)
        {
            if (pGeometry == null)
            {
                return;
            }

            try
            {
                OSGeo.OGR.Geometry ogrGeometry = m_currentOGRFeature.GetGeometryRef();

                // Flatten the geometry and ommit Z value until we add manual
                // Z-value zupport
                // See:
                // https://github.com/RBURHUM/arcgis-ogr/issues/11
                //
                //
                ogrGeometry.FlattenTo2D();

                //export geometry from OGR to WKB
                int    wkbSize   = ogrGeometry.WkbSize();
                byte[] wkbBuffer = new byte[wkbSize];
                ogrGeometry.ExportToWkb(wkbBuffer);

                //import geometry from WKB to ESRI Shape
                IWkb pWKB = pGeometry as IWkb;
                pWKB.ImportFromWkb(wkbSize, ref wkbBuffer[0]);

                pGeometry.SpatialReference = m_pDataset.SpatialReference;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(" Error: " + ex.Message);
                pGeometry.SetEmpty();
            }
        }
Example #18
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)
        {
            // See if gdal and ogr are working first.
            string output = "";

            try
            {
                GdalConfiguration.ConfigureOgr();

                GdalConfiguration.ConfigureGdal();

                output = "It works!";
            }

            catch (Exception e)
            {
                output = "{0} Exception caught. " + e;
            }

            string input = "";

            DA.GetData(0, ref input);

            var driver = OSGeo.OGR.Ogr.GetDriverByName("ESRI Shapefile");

            if (driver == null)
            {
                output = "Driver is null";
            }

            else
            {
                var ds = driver.Open(input, 0);

                if (ds == null)
                {
                    output = "DataSource is null";
                }

                else
                {
                    Grasshopper.DataTree <double> latitudesOut = new Grasshopper.DataTree <double>(), longitudesOut = new Grasshopper.DataTree <double>(), altitudesOut = new Grasshopper.DataTree <double>();
                    Grasshopper.DataTree <bool>   cullPattern = new Grasshopper.DataTree <bool>();

                    long numberOfFeatures = 0;

                    var layer = ds.GetLayerByIndex(0);

                    string geoType = layer.GetGeomType().ToString();

                    numberOfFeatures = unchecked ((int)layer.GetFeatureCount(0));

                    bool parallel = false;

                    DA.GetData(1, ref parallel);

                    GH_Path path = new GH_Path();

                    OSGeo.OGR.Feature  feature = null;
                    OSGeo.OGR.Geometry geo = null, ring = null;

                    double[] pointList = { 0, 0, 0 };

                    if (parallel == false)
                    {
                        if (geoType == "wkbPolygon")
                        {
                            for (int i = 0; i < numberOfFeatures; ++i)
                            {
                                path    = new GH_Path(i);
                                feature = layer.GetFeature(i);
                                geo     = feature.GetGeometryRef();
                                ring    = geo.GetGeometryRef(0);
                                int pointCount = ring.GetPointCount();

                                cullPattern.Add(pointCount > 0 ? true : false, path);

                                for (int j = 0; j < pointCount; ++j)
                                {
                                    ring.GetPoint(j, pointList);

                                    latitudesOut.Add(pointList[1], path);
                                    longitudesOut.Add(pointList[0], path);
                                    altitudesOut.Add(pointList[2], path);
                                }
                            }
                        }

                        else if (geoType == "wkbLineString")
                        {
                            for (int i = 0; i < numberOfFeatures; ++i)
                            {
                                path    = new GH_Path(i);
                                feature = layer.GetFeature(i);
                                geo     = feature.GetGeometryRef();
                                int pointCount = geo.GetPointCount();

                                cullPattern.Add(pointCount > 0 ? true : false, path);

                                for (int j = 0; j < pointCount; ++j)
                                {
                                    geo.GetPoint(j, pointList);

                                    latitudesOut.Add(pointList[1], path);
                                    longitudesOut.Add(pointList[0], path);
                                    altitudesOut.Add(pointList[2], path);
                                }
                            }
                        }

                        else if (geoType == "wkbPoint" || geoType == "wkbPoint25D")
                        {
                            // TODO add reprojections if needed.
                            //OSGeo.OSR.CoordinateTransformation.TransformPoint(  )

                            for (int i = 0; i < numberOfFeatures; ++i)
                            {
                                path = new GH_Path(i);

                                try
                                {
                                    feature = layer.GetFeature(i);

                                    geo = feature.GetGeometryRef();

                                    geo.GetPoint(0, pointList);

                                    latitudesOut.Add(pointList[1], path);
                                    longitudesOut.Add(pointList[0], path);
                                    altitudesOut.Add(pointList[2], path);
                                }

                                catch (Exception e)
                                {
                                    output = "{0} Exception caught. " + e;
                                }
                            }
                        }

                        else
                        {
                            output = "Geometry type not implemented yet";
                        }
                    }

                    else
                    {
                        if (geoType == "wkbPolygon")
                        {
                            double[][] latMat = new double[numberOfFeatures][];
                            double[][] lonMat = new double[numberOfFeatures][];
                            double[][] altMat = new double[numberOfFeatures][];

                            for (int i = 0; i < numberOfFeatures; ++i)
                            {
                                path    = new GH_Path(i);
                                feature = layer.GetFeature(i);
                                geo     = feature.GetGeometryRef();
                                ring    = geo.GetGeometryRef(0);
                                int pointCount = ring.GetPointCount();

                                latMat[i] = new double[pointCount];
                                lonMat[i] = new double[pointCount];
                                altMat[i] = new double[pointCount];

                                System.Threading.Tasks.Parallel.For(0, pointCount, j =>
                                {
                                    layer.GetFeature(i).GetGeometryRef().GetPoint(j, pointList);

                                    latMat[i][j] = pointList[1];
                                    lonMat[i][j] = pointList[0];
                                    altMat[i][j] = pointList[2];
                                });

                                if (pointCount > 0)
                                {
                                    latitudesOut.AddRange(latMat[i], path);
                                    longitudesOut.AddRange(lonMat[i], path);
                                    altitudesOut.AddRange(altMat[i], path);
                                    cullPattern.Add(true, path);
                                }

                                else
                                {
                                    cullPattern.Add(false, path);
                                }
                            }
                        }

                        else if (geoType == "wkbLineString")
                        {
                            double[][]           latMat = new double[numberOfFeatures][];
                            double[][]           lonMat = new double[numberOfFeatures][];
                            double[][]           altMat = new double[numberOfFeatures][];
                            OSGeo.OGR.Geometry[] g      = new OSGeo.OGR.Geometry[numberOfFeatures];

                            for (int i = 0; i < numberOfFeatures; ++i)
                            {
                                path    = new GH_Path(i);
                                feature = layer.GetFeature(i);
                                geo     = feature.GetGeometryRef();

                                g[i] = geo;

                                int pointCount = geo.GetPointCount();

                                latMat[i] = new double[pointCount];
                                lonMat[i] = new double[pointCount];
                                altMat[i] = new double[pointCount];

                                System.Threading.Tasks.Parallel.For(0, pointCount, j =>
                                {
                                    g[i].GetPoint(j, pointList);



                                    latMat[i][j] = pointList[1];
                                    lonMat[i][j] = pointList[0];
                                    altMat[i][j] = pointList[2];
                                });

                                if (pointCount > 0)
                                {
                                    latitudesOut.AddRange(latMat[i], path);
                                    longitudesOut.AddRange(lonMat[i], path);
                                    altitudesOut.AddRange(altMat[i], path);
                                    cullPattern.Add(true, path);
                                }

                                else
                                {
                                    cullPattern.Add(false, path);
                                }
                            }
                        }

                        else if (geoType == "wkbPoint" || geoType == "wkbPoint25D")
                        {
                            double[] latMat = new double[numberOfFeatures];
                            double[] lonMat = new double[numberOfFeatures];
                            double[] altMat = new double[numberOfFeatures];

                            System.Threading.Tasks.Parallel.For(0, numberOfFeatures, i =>
                            {
                                //feature = layer.GetFeature(i);

                                //geo = feature.GetGeometryRef();
                                layer.GetFeature(i).GetGeometryRef().GetPoint(0, pointList);

                                latMat[i] = pointList[1];
                                lonMat[i] = pointList[0];
                                altMat[i] = pointList[2];
                            });

                            for (int i = 0; i < numberOfFeatures; ++i)
                            {
                                path = new GH_Path(i);

                                latitudesOut.Add(latMat[i], path);
                                longitudesOut.Add(lonMat[i], path);
                                altitudesOut.Add(altMat[i], path);
                            }
                        }

                        else
                        {
                            output = "Geometry type not implemented yet";
                        }
                    }

                    DA.SetDataTree(1, latitudesOut);
                    DA.SetDataTree(2, longitudesOut);
                    DA.SetDataTree(3, altitudesOut);
                    DA.SetDataTree(4, cullPattern);
                }
            }

            DA.SetData(0, output);
        }
Example #19
0
        //private static Geometry ParseOgrGeometry(OgrGeometry ogrGeometry, WKBReader reader)
        ////private static Geometry ParseOgrGeometry(OgrGeometry ogrGeometry, IGeometryFactory factory)
        //{
        //    if (ogrGeometry != null)
        //    {

        //        //Just in case it isn't 2D
        //        ogrGeometry.FlattenTo2D();
        //        var wkbBuffer = new byte[ogrGeometry.WkbSize()];
        //        ogrGeometry.ExportToWkb(wkbBuffer);
        //        //var geom = GeometryFromWKB.Parse(wkbBuffer, factory);
        //        var geom = reader.Read(wkbBuffer);
        //        if (geom == null)
        //            _log.Debug(t=> t("Failed to parse '{0}'", ogrGeometry.GetGeometryType()));
        //        return geom;

        //        ogrGeometry.GetGeometry()
        //    }
        //    return null;
        //}

        //private static FeatureDataRow LoadOgrFeatureToFeatureDataRow(FeatureDataTable table, OSGeo.OGR.Feature ogrFeature, GeoAPI.Geometries.IGeometryFactory factory)
        private static FeatureDataRow LoadOgrFeatureToFeatureDataRow(FeatureDataTable table, OSGeo.OGR.Feature ogrFeature, OgrGeometryReader reader)
        {
            var values = new object[ogrFeature.GetFieldCount()];

            for (var iField = 0; iField < ogrFeature.GetFieldCount(); iField++)
            {
                // No need to get field value if there's no value available...
                if (!ogrFeature.IsFieldSet(iField))
                {
                    continue;
                }

                int count;
                switch (ogrFeature.GetFieldType(iField))
                {
                case OgrFieldType.OFTString:
                case OgrFieldType.OFTWideString:
                    values[iField] = ogrFeature.GetFieldAsString(iField);
                    break;

                case OgrFieldType.OFTStringList:
                case OgrFieldType.OFTWideStringList:
                    values[iField] = ogrFeature.GetFieldAsStringList(iField);
                    break;

                case OgrFieldType.OFTInteger:
                    values[iField] = ogrFeature.GetFieldAsInteger(iField);
                    break;

                case OgrFieldType.OFTIntegerList:
                    values[iField] = ogrFeature.GetFieldAsIntegerList(iField, out count);
                    break;

                case OgrFieldType.OFTReal:
                    values[iField] = ogrFeature.GetFieldAsDouble(iField);
                    break;

                case OgrFieldType.OFTRealList:
                    values[iField] = ogrFeature.GetFieldAsDoubleList(iField, out count);
                    break;

                case OgrFieldType.OFTDate:
                case OgrFieldType.OFTDateTime:
                case OgrFieldType.OFTTime:
                    Int32 y, m, d, h, mi, tz;
                    float s;
                    ogrFeature.GetFieldAsDateTime(iField, out y, out m, out d, out h, out mi, out s, out tz);
                    try
                    {
                        if (y == 0 && m == 0 && d == 0)
                        {
                            values[iField] = DateTime.MinValue.AddMinutes(h * 60 + mi);
                        }
                        else
                        {
                            values[iField] = new DateTime(y, m, d, h, mi, (int)s);
                        }
                    }
// ReSharper disable once EmptyGeneralCatchClause
                    catch { }
                    break;

                default:
                    var iTmpField = iField;
                    _log.Debug(t => t("Cannot handle Ogr DataType '{0}'", ogrFeature.GetFieldType(iTmpField)));
                    break;
                }
            }

            var fdr = (FeatureDataRow)table.LoadDataRow(values, true);

            using (var gr = ogrFeature.GetGeometryRef())
            {
                //fdr.Geometry = ParseOgrGeometry(gr, factory);
                fdr.Geometry = reader.Read(gr);
            }
            return(fdr);
        }
Example #20
0
        /// <summary>
        /// Query by geometry
        /// </summary>
        /// <param name="geo">input geometry</param>
        /// <param name="layer">target layer</param>
        /// <returns></returns>
        public List <int> QueryByGeometry(OSGeo.OGR.Geometry geo, OSGeo.OGR.Layer layer, SpatialRel sr)
        {
            List <int> result = new List <int>();

            try
            {
                OSGeo.OGR.Feature oFeature = null;

                while ((oFeature = layer.GetNextFeature()) != null)
                {
                    OSGeo.OGR.Geometry oGeometry = oFeature.GetGeometryRef();
                    switch (sr)
                    {
                    case SpatialQuery.SpatialRel.Undefined: break;

                    case SpatialQuery.SpatialRel.Intersects:
                        if (geo.Intersect(oGeometry))
                        {
                            result.Add((int)oFeature.GetFID());
                        }
                        break;

                    case SpatialQuery.SpatialRel.Contains:
                        if (oGeometry.Contains(geo))
                        {
                            result.Add((int)oFeature.GetFID());
                        }
                        break;

                    case SpatialQuery.SpatialRel.Crosses:
                        if (geo.Crosses(oGeometry))
                        {
                            result.Add((int)oFeature.GetFID());
                        }
                        break;

                    case SpatialQuery.SpatialRel.Overlaps:
                        if (geo.Overlaps(oGeometry))
                        {
                            result.Add((int)oFeature.GetFID());
                        }
                        break;

                    case SpatialQuery.SpatialRel.Touches:
                        if (geo.Touches(oGeometry))
                        {
                            result.Add((int)oFeature.GetFID());
                        }
                        break;

                    case SpatialQuery.SpatialRel.WithIn:
                        if (oGeometry.Within(geo))
                        {
                            result.Add((int)oFeature.GetFID());
                        }
                        break;
                    }
                }
            }
            catch
            {
                throw;
            }

            return(result);
        }
Example #21
0
        /// <summary>
        /// 以前的代码
        /// </summary>
        /// <param name="dsmDs"></param>
        /// <param name="oriFeat"></param>
        /// <param name="bufFeat"></param>
        /// <param name="subRasterOff_Size"></param>
        private static void getMaxMinValue_(OSGeo.GDAL.Dataset dsmDs, OSGeo.OGR.Feature oriFeat, OSGeo.OGR.Feature bufFeat, int[] subRasterOff_Size)
        {
            //拿到当前Feature对应的栅格值(数组)
            double[] rastValue = new double[subRasterOff_Size[2] * subRasterOff_Size[3]];
            //拿到全局Transfrom
            double[] Transfrom = new double[6];
            dsmDs.GetGeoTransform(Transfrom);

            //把SUBimg的值读进数组
            dsmDs.GetRasterBand(1).ReadRaster(
                subRasterOff_Size[0],
                subRasterOff_Size[1],
                subRasterOff_Size[2],
                subRasterOff_Size[3],
                rastValue,
                subRasterOff_Size[2],
                subRasterOff_Size[3],
                0, 0);

            OSGeo.OGR.Geometry oriGeom = oriFeat.GetGeometryRef();
            string             ddd     = oriFeat.GetFieldAsString("MAX");

            while (oriFeat.GetFieldAsString("MAX") == "")
            {
                //拿到数组中最大值的索引
                int maxId = Array.IndexOf(rastValue, rastValue.Max());

                //通过索引拿到空间坐标
                double maxX, maxY;
                StaticTools.indexToGeoSpace(maxId, subRasterOff_Size, Transfrom, out maxX, out maxY);

                //把空间坐标写进Geomtry
                OSGeo.OGR.Geometry maxGeom = new OSGeo.OGR.Geometry(OSGeo.OGR.wkbGeometryType.wkbPoint);
                maxGeom.AddPoint_2D(maxX, maxY);

                //判断坐标是否在Feature中,在则把值写入对应字段,不在则把当前值改为平均值

                if (maxGeom.Within(oriGeom))
                {
                    oriFeat.SetField("MAX", rastValue.Max());
                }
                else
                {
                    rastValue[maxId] = rastValue.Average();
                }
            }
            string dd = oriFeat.GetFieldAsString("MIN");

            while (oriFeat.GetFieldAsString("MIN") == "")
            {
                //拿到数组中最小值的索引
                double ffdf  = rastValue.Min();
                int    minId = Array.IndexOf(rastValue, rastValue.Min());

                //通过索引拿到空间坐标
                double minX, minY;
                StaticTools.indexToGeoSpace(minId, subRasterOff_Size, Transfrom, out minX, out minY);

                //把空间坐标写进Geomtry
                OSGeo.OGR.Geometry minGeom = new OSGeo.OGR.Geometry(OSGeo.OGR.wkbGeometryType.wkbPoint);
                minGeom.AddPoint_2D(minX, minY);

                //判断坐标是否在Feature中,在则把值写入对应字段,不在则把当前值改为平均值
                OSGeo.OGR.Geometry bufGeom = bufFeat.GetGeometryRef();
                if (minGeom.Within(bufGeom))
                {
                    oriFeat.SetField("MIN", rastValue.Min());
                }
                else
                {
                    rastValue[minId] = rastValue.Average();
                }
            }
            double max = oriFeat.GetFieldAsDouble("MAX");
            double min = oriFeat.GetFieldAsDouble("MIN");

            oriFeat.SetField("HIGHT", max - min);
        }
Example #22
0
        ///通过坡度线筛选等值线
        /// 1 清理等值线,长度\ 值域
        /// 2 等值线转面
        /// 3 根据坡度线求交等值线,并通过面积筛选
        /// 输入文件路径,输出临时shp
        ///

        /**************************************   清理等值线   *****************************************
         * /// <summary>
         * /// 通过线长,值 清理等值线
         * /// </summary>
         * /// <param name="filePath"></param>
         * public static void cleanPolyline(string filePath)
         * {
         *  //获取数据
         *  OSGeo.OGR.Ogr.RegisterAll();
         *  OSGeo.OGR.Driver dr = OSGeo.OGR.Ogr.GetDriverByName("ESRI shapefile");
         *  OSGeo.OGR.DataSource ds = dr.Open(filePath, 1);
         *  OSGeo.OGR.Layer fileLayer = ds.GetLayerByIndex(0);
         *
         *  //获取Featuer数
         *  int featCount = fileLayer.GetFeatureCount(0);
         *
         *  //求标准差
         *  // 1 拿到每个Featuer的Value
         *  double[] values = new double[featCount];
         *  for (int i = 0; i < featCount; i++)
         *  {
         *      OSGeo.OGR.Feature fileFeat = fileLayer.GetFeature(i);
         *      OSGeo.OGR.Geometry fileGeom = fileFeat.GetGeometryRef();
         *      values[i] = fileFeat.GetFieldAsDouble("EVE");
         *  }
         *
         *  // 2 求Values的平均值
         *  double aue = UsefullTools.myAue(values);
         *
         *  // 3 求values与平均值差的平方和
         *  double pingFangHe = 0;
         *  for (int i = 0; i < featCount; i++)
         *  {
         *      pingFangHe += (values[i] - aue) * (values[i] - aue);
         *  }
         *
         *  // 4 每个值与平均值的差相加,除Featuer数.再开方,得到标准差
         *  double bzc = Math.Sqrt(pingFangHe / featCount);
         *
         *  double minLength = 80;
         *  double maxLength = 600;
         *  double minValue = aue - bzc;
         *  double maxValue = aue + bzc;
         *
         *  for (int i = 0; i < featCount; i++)
         *  {
         *      OSGeo.OGR.Feature fileFeat = fileLayer.GetFeature(i);
         *      OSGeo.OGR.Geometry fileGeom = fileFeat.GetGeometryRef();
         *      double featValue = fileFeat.GetFieldAsDouble("EVE");
         *      double FeatLength = fileGeom.Length();
         *      bool s1 = FeatLength < minLength || FeatLength > maxLength;
         *      bool s2 = featValue < minValue || featValue > maxValue;
         *      if (s1 || s2 || !fileGeom.IsRing())
         *      {
         *          fileLayer.DeleteFeature(i);
         *      }
         *  }
         *  string layerName = fileLayer.GetName();
         *  ds.ExecuteSQL("REPACK " + layerName, null, "");
         *  ds.Dispose();
         * }
         * /// <summary>
         * /// 用来清理坡度线
         * /// </summary>
         * /// <param name="filePath"></param>
         * public static void cleanPDPoly(string filePath)
         * {
         *  //获取数据
         *  OSGeo.OGR.Ogr.RegisterAll();
         *  OSGeo.OGR.Driver dr = OSGeo.OGR.Ogr.GetDriverByName("ESRI shapefile");
         *  OSGeo.OGR.DataSource ds = dr.Open(filePath, 1);
         *  OSGeo.OGR.Layer fileLayer = ds.GetLayerByIndex(0);
         *
         *  //获取Featuer数
         *  int featCount = fileLayer.GetFeatureCount(0);
         *
         *  for (int i = 0; i < featCount; i++)
         *  {
         *      OSGeo.OGR.Feature fileFeat = fileLayer.GetFeature(i);
         *      OSGeo.OGR.Geometry fileGeom = fileFeat.GetGeometryRef();
         *      OSGeo.OGR.Geometry subGeom = fileGeom.GetGeometryRef(0);
         *      double FeatLength = subGeom.Length();
         *      bool s1 = FeatLength < 80 || FeatLength > 800;
         *
         *      if (s1)
         *      {
         *          fileLayer.DeleteFeature(i);
         *      }
         *  }
         *  string layerName = fileLayer.GetName();
         *  ds.ExecuteSQL("REPACK " + layerName, null, "");
         *  ds.Dispose();
         * }
         *
         * /********************************   等值线转换为多边形   ***********************************************
         *
         *
         * /// <summary>
         * /// 等值线转为POLYGON
         * /// </summary>
         * /// <param name="filePath"></param>
         * /// <returns></returns>
         * public static string lineToPoly(string filePath)
         * {
         *  OSGeo.OGR.Ogr.RegisterAll();
         *  OSGeo.OGR.Driver dr = OSGeo.OGR.Ogr.GetDriverByName("ESRI shapefile");
         *  OSGeo.OGR.DataSource lineDS = dr.Open(filePath,0);
         *  OSGeo.OGR.Layer lineLayer = lineDS.GetLayerByIndex(0);
         *  string savePath = filePath.Substring(0, filePath.LastIndexOf(".")) + "_ToPolygong.shp";
         *  //存在即删除
         *  if (System.IO.File.Exists(savePath))
         *      System.IO.File.Delete(savePath);
         *  //创建 一个新的数据源 for Polygon
         *  OSGeo.OGR.DataSource polyDS = dr.CreateDataSource(savePath, null);
         *  OSGeo.OGR.Layer polyLayer = polyDS.CreateLayer("", null, OSGeo.OGR.wkbGeometryType.wkbPolygon, null);
         *  OSGeo.OGR.FieldDefn fieldDf0 = new OSGeo.OGR.FieldDefn("LID", OSGeo.OGR.FieldType.OFTInteger);
         *  OSGeo.OGR.FieldDefn fieldDf1 = new OSGeo.OGR.FieldDefn("EVE", OSGeo.OGR.FieldType.OFTReal);
         *  polyLayer.CreateField(fieldDf0, 1);//ID
         *  polyLayer.CreateField(fieldDf1, 1);//Value
         *  for (int i = 0; i < lineLayer.GetFeatureCount(0); i++)
         *  {
         *      OSGeo.OGR.Feature lineFeat = lineLayer.GetFeature(i);
         *      OSGeo.OGR.Geometry lineGeom = lineFeat.GetGeometryRef();
         *      OSGeo.OGR.FeatureDefn featDF = new OSGeo.OGR.FeatureDefn("");
         *      OSGeo.OGR.Feature polyFeat = new OSGeo.OGR.Feature(featDF);
         *      OSGeo.OGR.Geometry polyGeom = new OSGeo.OGR.Geometry(OSGeo.OGR.wkbGeometryType.wkbPolygon);
         *      OSGeo.OGR.Geometry subGeom = new OSGeo.OGR.Geometry(OSGeo.OGR.wkbGeometryType.wkbLinearRing);
         *      int u = lineGeom.GetPointCount();
         *      for (int s = 0; s < u; s++)
         *      {
         *          double x = lineGeom.GetX(s);
         *          double y = lineGeom.GetY(s);
         *          double z = lineGeom.GetZ(s);
         *          subGeom.AddPoint(x, y, z);
         *      }
         *      subGeom.CloseRings();
         *      polyGeom.AddGeometry(subGeom);
         *      polyFeat.SetGeometry(polyGeom);
         *      polyLayer.CreateFeature(polyFeat);
         *  }
         *  polyLayer.Dispose();
         *  polyDS.Dispose();
         *  lineDS.Dispose();
         *  return savePath;
         * }
         *
         * /************************************  获取坡度线  ***************************************************
         *
         * private void getPDlines()
         * {
         *  string _inFilepath = @"D:\code\testDATA\test2.img";
         *  string _outFilePath = @"D:\code\outputfile\test2.img";
         *  string _outShpPath = @"D:\code\outputfile\test2";
         *  SlopeDem.SlopeDemObj.Slope(_inFilepath, _outFilePath);
         *  SlopeDem.SlopeDemObj.CreatePolygon(_inFilepath, _outShpPath);
         *
         * }
         *
         * /************************************  对比并筛选 ***************************************************/


        /// <summary>
        /// 通过是否相交和面积差,获得最小面积差相交要素的ID数组
        /// </summary>
        /// <returns></returns>
        private static int[] getMinIdGroup(string dzLine, string pdLing)
        {
            OSGeo.OGR.Ogr.RegisterAll();
            OSGeo.OGR.Driver     dr      = OSGeo.OGR.Ogr.GetDriverByName("ESRI shapefile");
            OSGeo.OGR.DataSource dzDS    = dr.Open(dzLine, 0);
            OSGeo.OGR.DataSource pdDS    = dr.Open(pdLing, 0);
            OSGeo.OGR.Layer      dzLayer = dzDS.GetLayerByIndex(0);
            OSGeo.OGR.Layer      pdLayer = pdDS.GetLayerByIndex(0);
            int dzCount = dzLayer.GetFeatureCount(0);
            int pdCount = pdLayer.GetFeatureCount(0);

            //面积差值最小要素的ID数组
            List <int> minIdG = new List <int>();

            //坡度Layer中的每个要素,成为当前坡度参考线
            for (int pdi = 0; pdi < pdCount; pdi++)
            {
                //Get 坡度要素
                OSGeo.OGR.Feature  pdFeat = pdLayer.GetFeature(pdi);
                OSGeo.OGR.Geometry pdGeom = pdFeat.GetGeometryRef();

                //前个面积差,循环结束将此值为最小面积差
                double afterCha = -1;

                //前个ID,循环结束将此值添加到minID中
                int yesID = -1;

                //查找与当前坡度要素有交集的等值线
                for (int dzi = 0; dzi < dzCount; dzi++)
                {
                    //get 等值线要素
                    OSGeo.OGR.Feature  dzFeat = dzLayer.GetFeature(dzi);
                    OSGeo.OGR.Geometry dzGeom = dzFeat.GetGeometryRef();
                    if (dzGeom != null)
                    {
                        //判断是否相交
                        if (pdGeom.Intersect(dzGeom))
                        {
                            //求当前等值线要素与坡度线要素的面积差
                            double cha = Math.Abs(dzGeom.GetArea() - pdGeom.GetArea());

                            //如果前个面积差未被赋值,则把当前差赋值给前差,并记录ID
                            if (afterCha == -1)
                            {
                                afterCha = Math.Abs(dzGeom.GetArea() - pdGeom.GetArea());
                                yesID    = dzi;
                            }
                            //如果前差已赋值,且当前差小于前差,则把当前差赋值给前差,并记录ID
                            else if (cha < afterCha)
                            {
                                afterCha = cha;
                                yesID    = dzi;
                            }
                        }
                    }
                }
                //如果yesID被赋值,则把这个结果添加到ID数组中
                if (yesID != -1)
                {
                    minIdG.Add(yesID);
                }
            }
            dzDS.Dispose();
            pdDS.Dispose();
            return(minIdG.ToArray());
        }
Example #23
0
        private static FeatureDataRow OgrFeatureToFeatureDataRow(FeatureDataTable table, OSGeo.OGR.Feature ogrFeature, GeoAPI.Geometries.IGeometryFactory factory)
        {
            FeatureDataRow fdr      = table.NewRow();
            Int32          fdrIndex = 0;

            for (int iField = 0; iField < ogrFeature.GetFieldCount(); iField++)
            {
                //*** BEGIN FIX: Ensure fdrIndex is incremented if field value is not set and field is of a supported type.
                bool         valueAvailable = ogrFeature.IsFieldSet(iField);
                OgrFieldType fieldType      = ogrFeature.GetFieldType(iField);

                // No need to get field value if there's no value available...
                if (!valueAvailable)
                {
                    // We need to increment the data row column index if this is a supported field type
                    // otherwise the next field will be written to the wrong column...
                    // We support all types except OFTBinary...
                    // Supported field types must be consistent with the code in ReadColumnDefinition and the switch case below...
                    if (fieldType != OgrFieldType.OFTBinary)
                    {
                        fdrIndex++;
                    }

                    continue;
                }
                //*** END FIX
                //if (!ogrFeature.IsFieldSet(iField)) continue;
                try
                {
                    switch (ogrFeature.GetFieldType(iField))
                    {
                    case OgrFieldType.OFTString:
                    case OgrFieldType.OFTWideString:
                    {
                        fdr[fdrIndex++] = ogrFeature.GetFieldAsString(iField);
                        break;
                    }

                    case OgrFieldType.OFTStringList:
                    case OgrFieldType.OFTWideStringList:
                    {
                        fdr[fdrIndex++] = ogrFeature.GetFieldAsStringList(iField);
                        break;
                    }

                    case OgrFieldType.OFTInteger:
                    {
                        fdr[fdrIndex++] = ogrFeature.GetFieldAsInteger(iField);
                        break;
                    }

                    case OgrFieldType.OFTIntegerList:
                    {
                        int count = 0;
                        fdr[fdrIndex++] = ogrFeature.GetFieldAsIntegerList(iField, out count);
                        break;
                    }

                    case OgrFieldType.OFTReal:
                    {
                        fdr[fdrIndex++] = ogrFeature.GetFieldAsDouble(iField);
                        break;
                    }

                    case OgrFieldType.OFTRealList:
                    {
                        int count = 0;
                        fdr[fdrIndex++] = ogrFeature.GetFieldAsDoubleList(iField, out count);
                        break;
                    }

                    case OgrFieldType.OFTDate:
                    case OgrFieldType.OFTDateTime:
                    case OgrFieldType.OFTTime:
                        Int32 y, m, d, h, mi, s, tz;
                        ogrFeature.GetFieldAsDateTime(iField, out y, out m, out d, out h, out mi, out s, out tz);
                        try
                        {
                            if (y == 0 && m == 0 && d == 0)
                            {
                                fdr[fdrIndex++] = DateTime.MinValue.AddMinutes(h * 60 + mi);
                            }
                            else
                            {
                                fdr[fdrIndex++] = new DateTime(y, m, d, h, mi, s);
                            }
                        }
                        catch
                        {
                            throw;
                        }
                        break;

                    default:
                        Debug.WriteLine(string.Format("Cannot handle Ogr DataType '{0}', '{1}'", ogrFeature.GetFieldType(iField), iField));
                        break;
                    }
                }
                catch { }
            }

            using (var gr = ogrFeature.GetGeometryRef())
            {
                fdr.Geometry = ParseOgrGeometry(gr, factory);
                gr.Dispose();
            }
            return(fdr);
        }
Example #24
0
        private static FeatureDataRow OgrFeatureToFeatureDataRow(FeatureDataTable table, OSGeo.OGR.Feature ogrFeature, GeoAPI.Geometries.IGeometryFactory factory)
        {
            FeatureDataRow fdr      = table.NewRow();
            Int32          fdrIndex = 0;

            for (int iField = 0; iField < ogrFeature.GetFieldCount(); iField++)
            {
                if (!ogrFeature.IsFieldSet(iField))
                {
                    continue;
                }

                switch (ogrFeature.GetFieldType(iField))
                {
                case OgrFieldType.OFTString:
                case OgrFieldType.OFTWideString:
                    fdr[fdrIndex++] = ogrFeature.GetFieldAsString(iField);
                    break;

                case OgrFieldType.OFTStringList:
                case OgrFieldType.OFTWideStringList:
                    break;

                case OgrFieldType.OFTInteger:
                    fdr[fdrIndex++] = ogrFeature.GetFieldAsInteger(iField);
                    break;

                case OgrFieldType.OFTIntegerList:
                    break;

                case OgrFieldType.OFTReal:
                    fdr[fdrIndex++] = ogrFeature.GetFieldAsDouble(iField);
                    break;

                case OgrFieldType.OFTRealList:
                    break;

                case OgrFieldType.OFTDate:
                case OgrFieldType.OFTDateTime:
                case OgrFieldType.OFTTime:
                    Int32 y, m, d, h, mi, s, tz;
                    ogrFeature.GetFieldAsDateTime(iField, out y, out m, out d, out h, out mi, out s, out tz);
                    try
                    {
                        if (y == 0 && m == 0 && d == 0)
                        {
                            fdr[fdrIndex++] = DateTime.MinValue.AddMinutes(h * 60 + mi);
                        }
                        else
                        {
                            fdr[fdrIndex++] = new DateTime(y, m, d, h, mi, s);
                        }
                    }
                    catch { }
                    break;

                default:
                    Debug.WriteLine(string.Format("Cannot handle Ogr DataType '{0}'", ogrFeature.GetFieldType(iField)));
                    break;
                }
            }

            using (var gr = ogrFeature.GetGeometryRef())
            {
                fdr.Geometry = ParseOgrGeometry(gr, factory);
                gr.Dispose();
            }
            return(fdr);
        }
Example #25
0
 /// <summary>
 /// Returns the geometry corresponding to the Object ID
 /// </summary>
 /// <param name="oid">Object ID</param>
 /// <returns>geometry</returns>
 public Geometry GetGeometryByID(uint oid)
 {
     using (OgrFeature ogrFeature = _ogrLayer.GetFeature((int)oid))
         return(ParseOgrGeometry(ogrFeature.GetGeometryRef()));
 }