Esempio n. 1
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);
        }
Esempio n. 2
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);
        }
Esempio n. 3
0
        /// <summary>
        /// 删除Featuer后更新Layer,Layer会被释放
        /// </summary>
        /// <param name="myDS"></param>
        public static void deleteFeatUpdate(this OSGeo.OGR.DataSource myDS)
        {
            string a = "REPACK " + myDS.GetLayerByIndex(0).GetName();

            myDS.ExecuteSQL(a, null, "");
            myDS.Dispose();
        }
Esempio n. 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();
        }
Esempio n. 5
0
        /************************************   生成等值线  **********************************************/

        public static string dzx(string filePath)
        {
            Console.WriteLine("开始创建等值线!");
            OSGeo.OGR.Ogr.RegisterAll();
            OSGeo.GDAL.Gdal.AllRegister();
            //无效值
            double noDataValue;

            //0不使用无效值,1使用无效值
            int hasDataValue;

            //读入数据源
            OSGeo.GDAL.Dataset inData = OSGeo.GDAL.Gdal.Open(filePath, OSGeo.GDAL.Access.GA_ReadOnly);

            //分析数据源
            inData.GetRasterBand(1).GetNoDataValue(out noDataValue, out hasDataValue);

            double min, max, mean, std;

            inData.GetRasterBand(1).GetStatistics(0, 1, out min, out max, out mean, out std);

            int jianG = 2;

            int count = Convert.ToInt32((max - min) / jianG + 0.5);

            double[] shu = new double[count];

            for (int i = 0; i < count; i++)
            {
                shu[i] = min + jianG * i;
            }

            //创建空的SHP
            OSGeo.OGR.Ogr.RegisterAll();
            OSGeo.OGR.Driver dr = OSGeo.OGR.Ogr.GetDriverByName("ESRI shapefile");
            string           a  = StaticTools.tempFilePath("shp", "原始等值线");

            OSGeo.OGR.DataSource ds       = dr.CreateDataSource(a, null);
            OSGeo.OGR.Layer      dzxLayer = ds.CreateLayer("", null, OSGeo.OGR.wkbGeometryType.wkbMultiLineString, 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);
            dzxLayer.CreateField(fieldDf0, 1); //ID
            dzxLayer.CreateField(fieldDf1, 1); //Value
            //Band(1), 间隔, 起始高度, 分段数量, 分段值数组, 是否有无效值, 无效值, 预置图层. ID字段, 高度值字段, null , null
            OSGeo.GDAL.Gdal.ContourGenerate(inData.GetRasterBand(1), jianG, min, count, shu, hasDataValue, noDataValue, dzxLayer, 0, 1, null, null);
            if (dzxLayer.GetFeatureCount(0) > 0)
            {
                Console.WriteLine("等值线创建完成!");
            }
            else
            {
                Console.WriteLine("等值线创建失败!");
            }
            ds.Dispose();
            inData.Dispose();
            return(a);
        }
Esempio n. 6
0
 /// <summary>
 /// Get Layer from Path
 /// </summary>
 /// <param name="path">Path of Layer</param>
 /// <returns>Layer</returns>
 public static OSGeo.OGR.Layer GetOgrLayer(string path)
 {
     OSGeo.OGR.Layer layer = null;
     if (System.IO.File.Exists(path))
     {
         OSGeo.OGR.DataSource dsBaseLayer = OSGeo.OGR.Ogr.Open(path, 0);
         layer = dsBaseLayer.GetLayerByIndex(0);
     }
     return(layer);
 }
Esempio n. 7
0
        //返回值是函数的系数
        //例如:y=a0+a1*x 返回值则为a0 a1
        //例如:y=a0+a1*x+a2*x*x 返回值则为a0 a1 a2
        #endregion

        /*************************************************************************************************/


        /************************************   生成等值线  **********************************************/

        public static string dzxPath(string filePath)
        {
            OSGeo.OGR.Ogr.RegisterAll();
            OSGeo.GDAL.Gdal.AllRegister();

            //无效值
            double noDataValue;

            //0不使用无效值,1使用无效值
            int hasDataValue;

            //读入数据源
            OSGeo.GDAL.Dataset inData = OSGeo.GDAL.Gdal.Open(filePath, OSGeo.GDAL.Access.GA_ReadOnly);

            //分析数据源
            inData.GetRasterBand(1).GetNoDataValue(out noDataValue, out hasDataValue);

            double min, max, mean, std;

            inData.GetRasterBand(1).GetStatistics(0, 1, out min, out max, out mean, out std);

            int jianG = 2;

            int count = Convert.ToInt32((max - min) / jianG + 0.5);

            double[] shu = new double[count];

            for (int i = 0; i < count; i++)
            {
                shu[i] = min + jianG * i;
            }

            //创建空的SHP
            string dzSavePath = filePath.Substring(0, filePath.LastIndexOf(".")) + "_dzx.shp";

            OSGeo.OGR.Driver dr = OSGeo.OGR.Ogr.GetDriverByName("ESRI shapefile");
            if (System.IO.File.Exists(dzSavePath))
            {
                System.IO.File.Delete(dzSavePath);
            }
            OSGeo.OGR.DataSource ds       = dr.CreateDataSource(dzSavePath, null);
            OSGeo.OGR.Layer      dzxLayer = ds.CreateLayer("等值线", null, OSGeo.OGR.wkbGeometryType.wkbMultiLineString, 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);
            dzxLayer.CreateField(fieldDf0, 1); //ID
            dzxLayer.CreateField(fieldDf1, 1); //Value

            //Band(1), 间隔, 起始高度, 分段数量, 分段值数组, 是否有无效值, 无效值, 预置图层. ID字段, 高度值字段, null , null
            OSGeo.GDAL.Gdal.ContourGenerate(inData.GetRasterBand(1), jianG, min, count, shu, hasDataValue, noDataValue, dzxLayer, 0, 1, null, null);

            dzxLayer.Dispose();
            ds.Dispose();

            return(dzSavePath);
        }
Esempio n. 8
0
        public Ogr(string filename, string layerName)
        {
            Filename = filename;

            _ogrDataSource = OgrOgr.Open(filename, 1);
            _ogrLayer      = _ogrDataSource.GetLayerByName(layerName);
            OsrSpatialReference spatialReference = _ogrLayer.GetSpatialRef();

            if (spatialReference != null)
            {
                _srid = spatialReference.AutoIdentifyEPSG();
            }
        }
Esempio n. 9
0
        ///// <summary>
        ///// Loads a Ogr datasource with the specified layer
        ///// </summary>
        ///// <param name="filename">datasource</param>
        ///// <param name="layerName">name of layer</param>
        /////If you want this functionality use
        /////<example>
        /////SharpMap.Data.Providers.Ogr prov = new SharpMap.Data.Providers.Ogr(datasource);
        /////prov.LayerName = layerName;
        /////</example>
        //[Obsolete("This constructor does not work well with VB.NET. Use LayerName property instead")]
        //public Ogr(string filename, string layerName)
        //{
        //    Filename = filename;

        //    _ogrDataSource = OgrOgr.Open(filename, 1);
        //    _ogrLayer = _ogrDataSource.GetLayerByName(layerName);
        //    OsrSpatialReference spatialReference = _ogrLayer.GetSpatialRef();
        //    if (spatialReference != null)
        //        SRID = spatialReference.AutoIdentifyEPSG();
        //}

        /// <summary>
        /// Loads a Ogr datasource with the specified layer
        /// </summary>
        /// <param name="filename">datasource</param>
        /// <param name="layerNum">number of layer</param>
        public Ogr(string filename, int layerNum)
        {
            Filename = filename;

            _ogrDataSource = OgrOgr.Open(filename, 0);
            _ogrLayer      = _ogrDataSource.GetLayerByIndex(layerNum);
            OsrSpatialReference spatialReference = _ogrLayer.GetSpatialRef();

            if (spatialReference != null)
            {
                SRID = spatialReference.AutoIdentifyEPSG();
            }
        }
Esempio n. 10
0
        /// <summary>
        /// DotSpatial to Ogr at layer level
        /// </summary>
        /// <param name="featureSet">DotSpatial IFeatureSet</param>
        /// <returns>Ogr Layer</returns>
        public static OSGeo.OGR.Layer DS2OrgLayer(DotSpatial.Data.IFeatureSet featureSet)
        {
            using (OSGeo.OGR.Driver driver = OSGeo.OGR.Ogr.GetDriverByName("Memory"))
            {
                OSGeo.OGR.DataSource  dataSource  = driver.CreateDataSource(featureSet.Name, null);
                OSGeo.OGR.Layer       layer       = dataSource.CreateLayer("Result", DS2OgrProjection(featureSet.Projection), DS2OgrGeometryType(featureSet.FeatureType), new string[] { });
                OSGeo.OGR.FeatureDefn featureDefn = DS2OgrDataTable(featureSet.DataTable);

                for (int k = 0; k < featureDefn.GetFieldCount(); k++)
                {
                    layer.CreateField(featureDefn.GetFieldDefn(k), 0);
                }

                for (int i = 0; i < featureSet.NumRows(); i++)
                {
                    DotSpatial.Data.IFeature feature    = featureSet.GetFeature(i);
                    OSGeo.OGR.Feature        ogrFeature = new OSGeo.OGR.Feature(featureDefn);
                    ogrFeature.SetGeometry(DS2OgrGeometry(feature.Geometry, featureSet));
                    for (int j = 0; j < feature.DataRow.ItemArray.Length; j++)
                    {
                        #region Set Value to Feature

                        object value = feature.DataRow.ItemArray.GetValue(j);
                        if (value is int)
                        {
                            ogrFeature.SetField(j, (int)value);
                        }
                        else if (value is double)
                        {
                            ogrFeature.SetField(j, (double)value);
                        }
                        else if (value is string)
                        {
                            ogrFeature.SetField(j, (string)value);
                        }
                        else if (value is DateTime)
                        {
                            DateTime dateTime = (DateTime)value;
                            ogrFeature.SetField(j, dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, (float)dateTime.Second, 0);
                        }

                        #endregion
                    }
                    layer.CreateFeature(ogrFeature);
                }
                dataSource.FlushCache();
                return(layer);
            }
        }
        /********************************   等值线转换为多边形   ***********************************************/

        /// <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);
        }
Esempio n. 12
0
        ///// <summary>
        ///// Loads a Ogr datasource with the specified layer
        ///// </summary>
        ///// <param name="filename">datasource</param>
        ///// <param name="layerName">name of layer</param>
        /////If you want this functionality use
        /////<example>
        /////SharpMap.Data.Providers.Ogr prov = new SharpMap.Data.Providers.Ogr(datasource);
        /////prov.LayerName = layerName;
        /////</example>
        //[Obsolete("This constructor does not work well with VB.NET. Use LayerName property instead")]
        //public Ogr(string filename, string layerName)
        //{
        //    Filename = filename;

        //    _ogrDataSource = OgrOgr.Open(filename, 1);
        //    _ogrLayer = _ogrDataSource.GetLayerByName(layerName);
        //    OsrSpatialReference spatialReference = _ogrLayer.GetSpatialRef();
        //    if (spatialReference != null)
        //        SRID = spatialReference.AutoIdentifyEPSG();
        //}

        /// <summary>
        /// Loads a Ogr datasource with the specified layer
        /// </summary>
        /// <param name="filename">datasource</param>
        /// <param name="layerNum">number of layer</param>
        public Ogr(string filename, int layerNum)
        {
            Filename     = filename;
            ConnectionID = filename;

            _ogrDataSource = OgrOgr.OpenShared(filename, 0);
            using (var ogrLayer = GetLayer(layerNum))
            {
                OsrSpatialReference spatialReference = ogrLayer.GetSpatialRef();
                if (spatialReference != null)
                {
                    SRID = spatialReference.AutoIdentifyEPSG();
                }
            }
            _layerIndex = layerNum;
        }
Esempio n. 13
0
 /// <summary>
 /// LineD to shpLine
 /// </summary>
 /// <param name="savePath"></param>
 /// <param name="aLine"></param>
 public static void LineDtoshpLine(string savePath, LineD aLine)
 {
     OSGeo.OGR.Ogr.RegisterAll();
     OSGeo.OGR.Driver      dr        = OSGeo.OGR.Ogr.GetDriverByName("ESRI shapefile");
     OSGeo.OGR.DataSource  ds        = dr.CreateDataSource(savePath, null);
     OSGeo.OGR.Layer       fileLayer = ds.CreateLayer("", null, OSGeo.OGR.wkbGeometryType.wkbLineString, null);
     OSGeo.OGR.FeatureDefn FeatDf    = new OSGeo.OGR.FeatureDefn("");
     OSGeo.OGR.Feature     fileFeat  = new OSGeo.OGR.Feature(FeatDf);
     OSGeo.OGR.Geometry    fileGeom  = new OSGeo.OGR.Geometry(OSGeo.OGR.wkbGeometryType.wkbLineString);
     fileGeom.AddPoint(aLine.Start.X, aLine.Start.Y, aLine.Start.Z);
     fileGeom.AddPoint(aLine.End.X, aLine.End.Y, aLine.End.Z);
     fileFeat.SetGeometry(fileGeom);
     fileLayer.CreateFeature(fileFeat);
     fileLayer.Dispose();
     ds.Dispose();
 }
Esempio n. 14
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();
        }
Esempio n. 15
0
 /// <summary>
 /// Point[] to shpPoint
 /// </summary>
 /// <param name="savePath"></param>
 /// <param name="allFeat"></param>
 public static void pointGToShpPoint(string savePath, Point[] allFeat)
 {
     OSGeo.OGR.Ogr.RegisterAll();
     OSGeo.OGR.Driver     dr        = OSGeo.OGR.Ogr.GetDriverByName("ESRI shapefile");
     OSGeo.OGR.DataSource ds        = dr.CreateDataSource(savePath, null);
     OSGeo.OGR.Layer      fileLayer = ds.CreateLayer("", null, OSGeo.OGR.wkbGeometryType.wkbPoint, null);
     for (int i = 0; i < allFeat.Length; i++)
     {
         OSGeo.OGR.FeatureDefn FeatDf   = new OSGeo.OGR.FeatureDefn("");
         OSGeo.OGR.Feature     fileFeat = new OSGeo.OGR.Feature(FeatDf);
         OSGeo.OGR.Geometry    fileGeom = new OSGeo.OGR.Geometry(OSGeo.OGR.wkbGeometryType.wkbPoint);
         fileGeom.AddPoint(allFeat[i].X, allFeat[i].Y, allFeat[i].Z);
         fileFeat.SetGeometry(fileGeom);
         fileLayer.CreateFeature(fileFeat);
     }
     fileLayer.Dispose();
     ds.Dispose();
 }
Esempio n. 16
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);
        }
Esempio n. 17
0
        public bool Open()
        {
            try
            {
                OSGeo.OGR.Ogr.RegisterAll();

                _dataSource = OSGeo.OGR.Ogr.Open(_connectionString, 0);
                if (_dataSource != null)
                {
                    _state = DatasetState.opened;
                    return(true);
                }
                return(false);
            }
            catch (Exception ex)
            {
                _lastErrMsg = ex.Message;
                return(false);
            }
        }
Esempio n. 18
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());
        }
Esempio n. 19
0
 /// <summary>
 /// List<Point[]> To shpLine
 /// </summary>
 /// <param name="savePath"></param>
 /// <param name="allFeat"></param>
 public static void pointGtoshpLine(string savePath, List <Point[]> allFeat)
 {
     OSGeo.OGR.Ogr.RegisterAll();
     OSGeo.OGR.Driver     dr        = OSGeo.OGR.Ogr.GetDriverByName("ESRI shapefile");
     OSGeo.OGR.DataSource ds        = dr.CreateDataSource(savePath, null);
     OSGeo.OGR.Layer      fileLayer = ds.CreateLayer("", null, OSGeo.OGR.wkbGeometryType.wkbLineString, null);
     for (int u = 0; u < allFeat.Count; u++)
     {
         Point[] a = allFeat[u];
         OSGeo.OGR.FeatureDefn FeatDf   = new OSGeo.OGR.FeatureDefn("");
         OSGeo.OGR.Feature     fileFeat = new OSGeo.OGR.Feature(FeatDf);
         OSGeo.OGR.Geometry    fileGeom = new OSGeo.OGR.Geometry(OSGeo.OGR.wkbGeometryType.wkbLineString);
         for (int i = 0; i < a.Length; i++)
         {
             fileGeom.AddPoint(a[i].X, a[i].Y, a[i].Z);
         }
         fileFeat.SetGeometry(fileGeom);
         fileLayer.CreateFeature(fileFeat);
     }
     fileLayer.Dispose();
     ds.Dispose();
 }
Esempio n. 20
0
        /// <summary>
        /// 通过Layer名删除Layer
        /// </summary>
        /// <param name="myDS"></param>
        /// <param name="layerName"></param>
        /// <returns></returns>
        public static bool deleteLayerByName(this OSGeo.OGR.DataSource myDS, string layerName)
        {
            bool isDelete   = false;
            int  layerCount = myDS.GetLayerCount();

            for (int i = 0; i < layerCount; i++)
            {
                OSGeo.OGR.Layer itm = myDS.GetLayerByIndex(i);
                if (itm.GetName() == layerName)
                {
                    itm.Dispose();
                    myDS.DeleteLayer(i);
                    isDelete = true;
                    break;
                }
                else
                {
                    itm.Dispose();
                }
            }
            return(isDelete);
        }
Esempio n. 21
0
        private void btnTestConnecton_Click(object sender, EventArgs e)
        {
            OSGeo.OGR.Ogr.RegisterAll();

            OSGeo.OGR.DataSource dataSource = OSGeo.OGR.Ogr.Open(this.ConnectionString, 0);
            if (dataSource != null)
            {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < Math.Min(dataSource.GetLayerCount(), 20); i++)
                {
                    OSGeo.OGR.Layer ogrLayer = dataSource.GetLayerByIndex(i);
                    if (ogrLayer == null)
                    {
                        continue;
                    }
                    sb.Append("\n" + ogrLayer.GetName());
                }
                MessageBox.Show("Connection succeeded...\n" + sb.ToString(), "Test Connection", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("Connection failed...", "Test Connection", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Esempio n. 22
0
        static void Main(string[] args)
        {
            OSGeo.GDAL.Gdal.AllRegister();
            OSGeo.OGR.Ogr.RegisterAll();
            //shp驱动
            OSGeo.OGR.Driver shpDataDriver = OSGeo.OGR.Ogr.GetDriverByName("ESRI shapefile");
            //shp数据源
            shpDataSet = shpDataDriver.CreateDataSource(shpSavePath, null);
            //img驱动
            gdalDriver = OSGeo.GDAL.Gdal.GetDriverByName("HFA");
            //dsm数据源
            dsmDataset = OSGeo.GDAL.Gdal.Open(dsmPath, OSGeo.GDAL.Access.GA_Update);
            //dsm数据信息
            dsmDataset.GetGeoTransform(dsm_Transform);
            dsm_Xsize = dsmDataset.RasterXSize;
            dsm_Ysize = dsmDataset.RasterYSize;
            //投影信息
            srs = dsmDataset.GetProjectionRef() == "" ? null : new OSGeo.OSR.SpatialReference(dsmDataset.GetProjectionRef());

            Stopwatch aTime = new Stopwatch(); aTime.Start();

            //1 坡度图
            buildSlope();
            StaticTools.msgLine($"完成!用时:{aTime.Elapsed.ToString()}\n"); aTime.Restart();

            //2 坡度线
            OSGeo.OGR.Layer pdx = getPDX(1);
            StaticTools.msgLine($"完成!用时:{aTime.Elapsed.ToString()}\n"); aTime.Restart();
            OSGeo.OGR.Layer slopeCleanLayer = cleanLayer(pdx, 200, 5000);
            StaticTools.msgLine($"完成!用时:{aTime.Elapsed.ToString()}\n"); aTime.Restart();

            //3 等高线
            OSGeo.OGR.Layer dzx = getDZX_();
            StaticTools.msgLine($"完成!用时:{aTime.Elapsed.ToString()}\n"); aTime.Restart();
            OSGeo.OGR.Layer dzxPolyLayer = cleanDZX(dzx);
            StaticTools.msgLine($"完成!用时:{aTime.Elapsed.ToString()}\n"); aTime.Restart();

            //4 筛选
            OSGeo.OGR.Layer selectLayer = selectionFeatuers(slopeCleanLayer, dzxPolyLayer);
            StaticTools.msgLine($"完成!用时:{aTime.Elapsed.ToString()}\n"); aTime.Restart();
            OSGeo.OGR.Layer resLayer = cleanLayer_FF(selectLayer);
            StaticTools.msgLine($"完成!用时:{aTime.Elapsed.ToString()}\n"); aTime.Restart();

            // 最小外接矩形
            getMinOutLineFromLayerToLayer(resLayer);
            StaticTools.msgLine($"完成!用时:{aTime.Elapsed.ToString()}\n"); aTime.Restart();

            //5 简化
            jianhua(resLayer, 175, 5);
            StaticTools.msgLine($"完成!用时:{aTime.Elapsed.ToString()}\n"); aTime.Restart();

            //6 高度值 未完成
            //getH(resLayer);
            //StaticTools.msgLine($"完成!用时:{aTime.Elapsed.ToString()}\n"); aTime.Restart();

            shpDataSet.Dispose();
            shpDataDriver.Dispose();
            dsmDataset.Dispose();
            gdalDriver.Dispose();

            //   aTime.Stop();
            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }
Esempio n. 23
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            ///Gather GHA inputs
            List <Curve> boundary = new List <Curve>();

            DA.GetDataList <Curve>("Boundary", boundary);

            string shpFileLoc = "";

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


            bool cropIt = true;

            DA.GetData <Boolean>("Crop file", ref cropIt);

            string userSRStext = "WGS84";

            DA.GetData <string>(2, ref userSRStext);


            ///GDAL setup
            ///Some preliminary testing has been done to read SHP, GeoJSON, OSM, KML, MVT, GML and GDB
            ///It can be spotty with KML, MVT and GML and doesn't throw informative errors.  Likely has to do with getting a valid CRS and
            ///TODO: resolve errors with reading KML, MVT, GML.

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

            if (ds == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "The vector datasource was unreadable by this component. It may not a valid file type for this component or otherwise null/empty.");
                return;
            }

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

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

                if (layer == null)
                {
                    Console.WriteLine("Couldn't fetch advertised layer " + iLayer);
                    System.Environment.Exit(-1);
                }
                else
                {
                    layerset.Add(layer);
                }
            }

            ///Declare trees
            GH_Structure <GH_String>    layname = new GH_Structure <GH_String>();
            GH_Structure <GH_Integer>   fcs     = new GH_Structure <GH_Integer>();
            GH_Structure <GH_Rectangle> recs    = new GH_Structure <GH_Rectangle>();
            GH_Structure <GH_String>    sRefs   = new GH_Structure <GH_String>();
            GH_Structure <GH_String>    fnames  = new GH_Structure <GH_String>();
            GH_Structure <GH_String>    fset    = new GH_Structure <GH_String>();
            GH_Structure <GH_Point>     gset    = new GH_Structure <GH_Point>();

            GH_Structure <GH_Point>     gsetUser = new GH_Structure <GH_Point>();
            GH_Structure <GH_Rectangle> recsUser = new GH_Structure <GH_Rectangle>();


            ///Loop through each layer. Layers usually occur in Geodatabase GDB format. SHP usually has only one layer.
            for (int iLayer = 0; iLayer < ds.GetLayerCount(); iLayer++)
            {
                OSGeo.OGR.Layer layer = ds.GetLayerByIndex(iLayer);

                if (layer == null)
                {
                    Console.WriteLine("Couldn't fetch advertised layer " + iLayer);
                    System.Environment.Exit(-1);
                }

                long count        = layer.GetFeatureCount(1);
                int  featureCount = System.Convert.ToInt32(count);
                fcs.Append(new GH_Integer(featureCount), new GH_Path(iLayer));

                layname.Append(new GH_String(layer.GetName()), new GH_Path(iLayer));


                ///Get the spatial reference of the input vector file and set to WGS84 if not known
                OSGeo.OSR.SpatialReference sourceSRS = new SpatialReference(Osr.SRS_WKT_WGS84);
                string sRef = "";

                if (layer.GetSpatialRef() == null)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Coordinate Reference System (CRS) is missing.  CRS set automatically set to WGS84. Mapbox to 3857");
                    //sr.ImportFromXML(shpFileLoc);
                    //sr.ImportFromEPSG(3857);
                    //sr.SetWellKnownGeogCS("EPSG:3857");
                    sourceSRS.SetFromUserInput("WGS84"); ///this seems to work where SetWellKnownGeogCS doesn't

                    string pretty = "";
                    sourceSRS.ExportToPrettyWkt(out pretty, 0);
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, pretty);
                    //sr.SetWellKnownGeogCS("WGS84");
                    //sr.SetWellKnownGeogCS("EPSG:3857");
                    sRef = "Coordinate Reference System (CRS) is missing.  CRS set automatically set to WGS84.";
                }
                else
                {
                    if (layer.GetSpatialRef().Validate() != 0)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Coordinate Reference System (CRS) is unknown or unsupported.  CRS set automatically set to WGS84.");
                        sourceSRS.SetWellKnownGeogCS("WGS84");
                        sRef = "Coordinate Reference System (CRS) is unknown or unsupported.  SRS set automatically set to WGS84.";
                    }
                    else
                    {
                        sourceSRS = layer.GetSpatialRef();
                        sourceSRS.ExportToWkt(out sRef);
                        try
                        {
                            int sourceSRSInt = Int16.Parse(sourceSRS.GetAuthorityCode(null));
                            AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Source Coordinate Reference System (CRS) from layer " + layer.GetName() + " is EPSG:" + sourceSRSInt + ".");
                        }
                        catch
                        {
                            AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Failed to get Source Coordinate Reference System (CRS) from layer " + layer.GetName() + ".");
                        }
                    }
                }

                sRefs.Append(new GH_String(sRef), new GH_Path(iLayer));


                ///Set transform from input spatial reference to Rhino spatial reference
                ///TODO: look into adding a step for transforming to CRS set in SetCRS
                OSGeo.OSR.SpatialReference rhinoSRS = new OSGeo.OSR.SpatialReference("");
                rhinoSRS.SetWellKnownGeogCS("WGS84");

                ///TODO: verify the userSRS is valid
                ///TODO: use this as override of global SetSRS
                OSGeo.OSR.SpatialReference userSRS = new OSGeo.OSR.SpatialReference("");
                userSRS.SetFromUserInput(userSRStext);

                ///This transform moves and scales the points required in going from userSRS to XYZ and vice versa
                Transform userSRSToModel = Heron.Convert.GetUserSRSToModelTransform(userSRS);
                Transform modelToUserSRS = Heron.Convert.GetModelToUserSRSTransform(userSRS);

                OSGeo.OSR.CoordinateTransformation coordTransformSourceToRhino = new OSGeo.OSR.CoordinateTransformation(sourceSRS, rhinoSRS);
                OSGeo.OSR.CoordinateTransformation coordTransformRhinoToUser   = new OSGeo.OSR.CoordinateTransformation(rhinoSRS, userSRS);
                OSGeo.OSR.CoordinateTransformation coordTransformSourceToUser  = new OSGeo.OSR.CoordinateTransformation(sourceSRS, userSRS);

                OSGeo.OSR.CoordinateTransformation revTransformUserToRhino   = new OSGeo.OSR.CoordinateTransformation(userSRS, rhinoSRS);
                OSGeo.OSR.CoordinateTransformation revTransformRhinoToSource = new OSGeo.OSR.CoordinateTransformation(rhinoSRS, sourceSRS);
                OSGeo.OSR.CoordinateTransformation revTransformUserToSource  = new OSGeo.OSR.CoordinateTransformation(userSRS, sourceSRS);

                ///Get OGR envelope of the data in the layer in the sourceSRS
                OSGeo.OGR.Envelope ext = new OSGeo.OGR.Envelope();
                layer.GetExtent(ext, 1);
                Point3d extMinSource = new Point3d();
                Point3d extMaxSource = new Point3d();
                extMinSource.X = ext.MinX;
                extMinSource.Y = ext.MinY;
                extMaxSource.X = ext.MaxX;
                extMaxSource.Y = ext.MaxY;

                ///Get bounding box of data in layer for coordinate transformation in Rhino SRS
                double[] extMinPT = new double[3] {
                    extMinSource.X, extMinSource.Y, extMinSource.Z
                };
                double[] extMaxPT = new double[3] {
                    extMaxSource.X, extMaxSource.Y, extMaxSource.Z
                };

                ///Transform corners of extents from Source to Rhino SRS
                coordTransformSourceToRhino.TransformPoint(extMinPT);
                coordTransformSourceToRhino.TransformPoint(extMaxPT);

                ///Get extents in Rhino SRS
                Point3d     extPTmin = new Point3d(extMinPT[0], extMinPT[1], extMinPT[2]);
                Point3d     extPTmax = new Point3d(extMaxPT[0], extMaxPT[1], extMaxPT[2]);
                Rectangle3d rec      = new Rectangle3d(Plane.WorldXY, Heron.Convert.WGSToXYZ(extPTmin), Heron.Convert.WGSToXYZ(extPTmax));
                recs.Append(new GH_Rectangle(rec), new GH_Path(iLayer));

                if (boundary.Count == 0 && cropIt == true)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Define a boundary or set cropIt to False");
                }

                else if (boundary.Count == 0 && cropIt == false)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Clipping boundary has not been defined. File extents will be used instead");
                    boundary.Add(rec.ToNurbsCurve());
                }

                ///Get bounding box of data in layer for coordinate transformation in User SRS
                ///TODO: currently the extents are showing odd results that don't seem to be shifting properly
                double[] extMinPTUser = new double[3] {
                    extMinSource.X, extMinSource.Y, extMinSource.Z
                };
                double[] extMaxPTUser = new double[3] {
                    extMaxSource.X, extMaxSource.Y, extMaxSource.Z
                };

                ///Transform corners of extents from Source to userSRS
                coordTransformSourceToUser.TransformPoint(extMinPTUser);
                coordTransformSourceToUser.TransformPoint(extMaxPTUser);

                ///Get extents in userSRS
                Point3d     extPTminUser = new Point3d(extMinPTUser[0], extMinPTUser[1], extMinPTUser[2]);
                Point3d     extPTmaxUser = new Point3d(extMaxPTUser[0], extMaxPTUser[1], extMaxPTUser[2]);
                Rectangle3d recUser      = new Rectangle3d(Plane.WorldXY, Heron.Convert.UserSRSToXYZ(extPTminUser, userSRSToModel), Heron.Convert.UserSRSToXYZ(extPTmaxUser, userSRSToModel));
                recsUser.Append(new GH_Rectangle(recUser), new GH_Path(iLayer));


                ///Loop through input boundaries
                for (int i = 0; i < boundary.Count; i++)
                {
                    OSGeo.OGR.FeatureDefn def = layer.GetLayerDefn();

                    ///Get the field names
                    List <string> fieldnames = new List <string>();
                    for (int iAttr = 0; iAttr < def.GetFieldCount(); iAttr++)
                    {
                        OSGeo.OGR.FieldDefn fdef = def.GetFieldDefn(iAttr);
                        fnames.Append(new GH_String(fdef.GetNameRef()), new GH_Path(i, iLayer));
                    }

                    ///Check if boundary is contained in extent
                    if (!rec.IsValid || ((rec.Height == 0) && (rec.Width == 0)))
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "One or more vector datasource bounds are not valid.");
                        OSGeo.OGR.Feature feat;
                        int m = 0;

                        while ((feat = layer.GetNextFeature()) != null)
                        {
                            ///Loop through field values
                            for (int iField = 0; iField < feat.GetFieldCount(); iField++)
                            {
                                OSGeo.OGR.FieldDefn fdef = def.GetFieldDefn(iField);
                                fset.Append(new GH_String(feat.GetFieldAsString(iField)), new GH_Path(i, iLayer, m));
                                fdef.Dispose();
                            }
                            m++;
                            feat.Dispose();
                        }
                    }


                    else if (boundary[i] == null)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Clipping boundary " + i + " not set.");
                    }

                    else if (!boundary[i].IsValid)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Clipping boundary " + i + "  is not valid.");
                    }

                    else if (rec.IsValid && Curve.PlanarClosedCurveRelationship(rec.ToNurbsCurve(), boundary[i], Plane.WorldXY, Rhino.RhinoDoc.ActiveDoc.ModelAbsoluteTolerance) == RegionContainment.Disjoint)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "One or more boundaries may be outside the bounds of the vector datasource.");
                    }

                    else
                    {
                        ///Create bounding box for clipping geometry
                        Point3d  min   = Heron.Convert.XYZToWGS(boundary[i].GetBoundingBox(true).Min);
                        Point3d  max   = Heron.Convert.XYZToWGS(boundary[i].GetBoundingBox(true).Max);
                        double[] minpT = new double[3];
                        double[] maxpT = new double[3];

                        minpT[0] = min.X;
                        minpT[1] = min.Y;
                        minpT[2] = min.Z;
                        maxpT[0] = max.X;
                        maxpT[1] = max.Y;
                        maxpT[2] = max.Z;

                        revTransformRhinoToSource.TransformPoint(minpT);
                        revTransformRhinoToSource.TransformPoint(maxpT);

                        ///TODO: allow boundary to be converted to userSRS
                        //revTransformUserToRhino.TransformPoint(minpT);
                        //revTransformUserToRhino.TransformPoint(maxpT);

                        ///Convert to OGR geometry
                        ///TODO: add conversion from GH geometry to OGR to Convert class
                        OSGeo.OGR.Geometry ebbox = OSGeo.OGR.Geometry.CreateFromWkt("POLYGON((" + minpT[0] + " " + minpT[1] + ", " + minpT[0] + " " + maxpT[1] + ", " + maxpT[0] + " " + maxpT[1] + ", " + maxpT[0] + " " + minpT[1] + ", " + minpT[0] + " " + minpT[1] + "))");

                        ///Clip Shapefile
                        ///http://pcjericks.github.io/py-gdalogr-cookbook/vector_layers.html
                        ///TODO: allow for polyline/curve as clipper, not just bounding box
                        OSGeo.OGR.Layer clipped_layer = layer;

                        if (cropIt)
                        {
                            clipped_layer.SetSpatialFilter(ebbox);
                        }

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

                        int m = 0;
                        while ((feat = clipped_layer.GetNextFeature()) != null)
                        {
                            OSGeo.OGR.Geometry geom = feat.GetGeometryRef();
                            OSGeo.OGR.Geometry sub_geom;

                            OSGeo.OGR.Geometry geomUser = feat.GetGeometryRef().Clone();// geom.Clone();
                            OSGeo.OGR.Geometry sub_geomUser;

                            ///reproject geometry to WGS84
                            ///TODO: look into using the SetCRS global variable here
                            geom.Transform(coordTransformSourceToRhino);

                            geomUser.Transform(coordTransformSourceToUser);

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

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

                                    gset.Append(new GH_Point(Heron.Convert.WGSToXYZ(pt3D)), new GH_Path(i, iLayer, m));

                                    ///Loop through geometry points for User SRS
                                    double[] pTUser = new double[3];
                                    pTUser[0] = geomUser.GetX(gpc);
                                    pTUser[1] = geomUser.GetY(gpc);
                                    pTUser[2] = geomUser.GetZ(gpc);
                                    if (Double.IsNaN(geomUser.GetZ(gpc)))
                                    {
                                        pTUser[2] = 0;
                                    }

                                    Point3d pt3DUser = new Point3d();
                                    pt3DUser.X = pTUser[0];
                                    pt3DUser.Y = pTUser[1];
                                    pt3DUser.Z = pTUser[2];

                                    if ((userSRS.IsProjected() == 0) && (userSRS.IsLocal() == 0))
                                    {
                                        gsetUser.Append(new GH_Point(Heron.Convert.WGSToXYZ(pt3DUser)), new GH_Path(i, iLayer, m));
                                    }
                                    else
                                    {
                                        gsetUser.Append(new GH_Point(userSRSToModel * pt3DUser), new GH_Path(i, iLayer, m));
                                    }
                                    ///End loop through geometry points


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



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

                                    sub_geomUser = geomUser.GetGeometryRef(gi);
                                    OSGeo.OGR.Geometry subsub_geomUser;

                                    if (sub_geom.GetGeometryCount() > 0)
                                    {
                                        for (int n = 0; n < sub_geom.GetGeometryCount(); n++)
                                        {
                                            subsub_geom     = sub_geom.GetGeometryRef(n);
                                            subsub_geomUser = sub_geomUser.GetGeometryRef(n);

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

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

                                                gset.Append(new GH_Point(Heron.Convert.WGSToXYZ(pt3D)), new GH_Path(i, iLayer, m, gi, n));


                                                double[] pTUser = new double[3];
                                                pTUser[0] = subsub_geomUser.GetX(ptnum);
                                                pTUser[1] = subsub_geomUser.GetY(ptnum);
                                                pTUser[2] = subsub_geomUser.GetZ(ptnum);

                                                Point3d pt3DUser = new Point3d();
                                                pt3DUser.X = pTUser[0];
                                                pt3DUser.Y = pTUser[1];
                                                pt3DUser.Z = pTUser[2];

                                                if ((userSRS.IsProjected() == 0) && (userSRS.IsLocal() == 0))
                                                {
                                                    gsetUser.Append(new GH_Point(Heron.Convert.WGSToXYZ(pt3DUser)), new GH_Path(i, iLayer, m, gi, n));
                                                }
                                                else
                                                {
                                                    gsetUser.Append(new GH_Point(userSRSToModel * pt3DUser), new GH_Path(i, iLayer, m, gi, n));
                                                }

                                                ///End loop through geometry points
                                            }
                                            subsub_geom.Dispose();
                                            subsub_geomUser.Dispose();
                                        }
                                    }

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

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

                                            gset.Append(new GH_Point(Heron.Convert.WGSToXYZ(pt3D)), new GH_Path(i, iLayer, m, gi));


                                            double[] pTUser = new double[3];
                                            pTUser[0] = sub_geomUser.GetX(ptnum);
                                            pTUser[1] = sub_geomUser.GetY(ptnum);
                                            pTUser[2] = sub_geomUser.GetZ(ptnum);

                                            Point3d pt3DUser = new Point3d();
                                            pt3DUser.X = pTUser[0];
                                            pt3DUser.Y = pTUser[1];
                                            pt3DUser.Z = pTUser[2];

                                            if ((userSRS.IsProjected() == 0) && (userSRS.IsLocal() == 0))
                                            {
                                                gsetUser.Append(new GH_Point(Heron.Convert.WGSToXYZ(pt3DUser)), new GH_Path(i, iLayer, m, gi));
                                            }
                                            else
                                            {
                                                gsetUser.Append(new GH_Point(userSRSToModel * pt3DUser), new GH_Path(i, iLayer, m, gi));
                                            }
                                            ///End loop through geometry points
                                        }
                                    }

                                    sub_geom.Dispose();
                                    sub_geomUser.Dispose();


                                    /// Get Feature Values
                                    if (fset.PathExists(new GH_Path(i, iLayer, m)))
                                    {
                                        fset.get_Branch(new GH_Path(i, iLayer, m)).Clear();
                                    }
                                    for (int iField = 0; iField < feat.GetFieldCount(); iField++)
                                    {
                                        OSGeo.OGR.FieldDefn fdef = def.GetFieldDefn(iField);
                                        if (feat.IsFieldSet(iField))
                                        {
                                            fset.Append(new GH_String(feat.GetFieldAsString(iField)), new GH_Path(i, iLayer, m));
                                        }
                                        else
                                        {
                                            fset.Append(new GH_String("null"), new GH_Path(i, iLayer, m));
                                        }
                                    }
                                    ///End Get Feature Values
                                }
                                //m++;
                            }
                            m++;
                            geom.Dispose();
                            geomUser.Dispose();
                            feat.Dispose();
                        } ///end while loop through features
                    }
                }         //end loop through boundaries

                layer.Dispose();
            }///end loop through layers

            ds.Dispose();

            DA.SetDataTree(0, layname);
            DA.SetDataTree(1, fcs);
            DA.SetDataTree(2, recs);
            DA.SetDataTree(3, sRefs);
            DA.SetDataTree(4, fnames);
            DA.SetDataTree(5, fset);
            DA.SetDataTree(6, gset);

            DA.SetDataTree(7, gsetUser);
            DA.SetDataTree(8, recsUser);
        }
Esempio n. 24
0
 /// <summary>
 /// Method to get a layer based on a private copy of the data source
 /// </summary>
 /// <param name="layerIndex">The layer index</param>
 /// <param name="ogrDataSource">The data source</param>
 /// <returns></returns>
 private OgrLayer GetLayer(int layerIndex, out OgrDataSource ogrDataSource)
 {
     ogrDataSource = OgrOgr.OpenShared(Filename, 0);
     return(ogrDataSource.GetLayerByIndex(layerIndex));
 }
Esempio n. 25
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <Curve> boundary = new List <Curve>();

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

            string URL = string.Empty;

            DA.GetData <string>("REST URL", ref URL);
            if (!URL.EndsWith("/"))
            {
                URL = URL + "/";
            }

            string userSRStext = string.Empty;

            DA.GetData <string>("User Spatial Reference System", ref userSRStext);

            bool run = false;

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

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

            ///TODO: implement SetCRS here.
            ///Option to set CRS here to user-defined.  Needs a SetCRS global variable.

            OSGeo.OSR.SpatialReference userSRS = new OSGeo.OSR.SpatialReference("");
            userSRS.SetFromUserInput(userSRStext);
            int userSRSInt = Int16.Parse(userSRS.GetAuthorityCode(null));

            ///Set transform from input spatial reference to Rhino spatial reference
            OSGeo.OSR.SpatialReference rhinoSRS = new OSGeo.OSR.SpatialReference("");
            rhinoSRS.SetWellKnownGeogCS("WGS84");

            ///This transform moves and scales the points required in going from userSRS to XYZ and vice versa
            Transform userSRSToModelTransform = Heron.Convert.GetUserSRSToModelTransform(userSRS);
            Transform modelToUserSRSTransform = Heron.Convert.GetModelToUserSRSTransform(userSRS);

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

            GH_Structure <GH_Point>         gsetUser   = new GH_Structure <GH_Point>();
            GH_Structure <IGH_GeometricGoo> gGoo       = new GH_Structure <IGH_GeometricGoo>();
            GH_Structure <GH_String>        fset       = new GH_Structure <GH_String>();
            GH_Structure <GH_String>        fieldnames = new GH_Structure <GH_String>();


            for (int i = 0; i < boundary.Count; i++)
            {
                GH_Path     cpath = new GH_Path(i);
                BoundingBox bbox  = boundary[i].GetBoundingBox(false);
                bbox.Transform(modelToUserSRSTransform);

                string restquery = URL +
                                   "query?where=&text=&objectIds=&time=&geometry=" + bbox.Min.X + "%2C" + bbox.Min.Y + "%2C" + bbox.Max.X + "%2C" + bbox.Max.Y +
                                   "&geometryType=esriGeometryEnvelope&inSR=" + userSRSInt +
                                   "&spatialRel=esriSpatialRelIntersects" +
                                   "&relationParam=&outFields=*" +
                                   "&returnGeometry=true" +
                                   "&maxAllowableOffset=" +
                                   "&geometryPrecision=" +
                                   "&outSR=" + userSRSInt +
                                   "&returnIdsOnly=false" +
                                   "&returnCountOnly=false" +
                                   "&orderByFields=" +
                                   "&groupByFieldsForStatistics=&outStatistics=" +
                                   "&returnZ=true" +
                                   "&returnM=false" +
                                   "&gdbVersion=" +
                                   "&returnDistinctValues=false" +
                                   "&f=json";

                mapquery.Append(new GH_String(restquery), cpath);

                if (run)
                {
                    //string result = Heron.Convert.HttpToJson(restquery);

                    OSGeo.OGR.DataSource dataSource = OSGeo.OGR.Ogr.Open("ESRIJSON:" + restquery, 0);

                    if (dataSource == null)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "The vector datasource was unreadable by this component. It may not a valid file type for this component or otherwise null/empty.");
                    }


                    ///Loop through each layer. Likely not any layers in a REST service
                    for (int iLayer = 0; iLayer < dataSource.GetLayerCount(); iLayer++)
                    {
                        OSGeo.OGR.Layer ogrLayer = dataSource.GetLayerByIndex(iLayer);

                        if (ogrLayer == null)
                        {
                            Console.WriteLine($"Couldn't fetch advertised layer {iLayer}");
                            System.Environment.Exit(-1);
                        }

                        long count        = ogrLayer.GetFeatureCount(1);
                        int  featureCount = System.Convert.ToInt32(count);
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, $"Layer #{iLayer} {ogrLayer.GetName()} has {featureCount} features");

                        OSGeo.OGR.FeatureDefn def = ogrLayer.GetLayerDefn();

                        ///Get the field names
                        for (int iAttr = 0; iAttr < def.GetFieldCount(); iAttr++)
                        {
                            ///TODO: Look into GetAlternativeNameRef() for field aliases (more readable) available in GDAL 3.2
                            OSGeo.OGR.FieldDefn fdef = def.GetFieldDefn(iAttr);
                            fieldnames.Append(new GH_String(fdef.GetNameRef()), new GH_Path(i, iLayer));
                        }

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

                        int m = 0;
                        while ((feat = ogrLayer.GetNextFeature()) != null)
                        {
                            OSGeo.OGR.Geometry geomUser = feat.GetGeometryRef().Clone();
                            OSGeo.OGR.Geometry sub_geomUser;

                            ///reproject geometry to WGS84 and userSRS
                            ///TODO: look into using the SetCRS global variable here
                            if (geomUser.GetSpatialReference() == null)
                            {
                                geomUser.AssignSpatialReference(userSRS);
                            }

                            geomUser.TransformTo(userSRS);

                            if (feat.GetGeometryRef() != null)
                            {
                                if (!pointsOnly)
                                {
                                    ///Convert GDAL geometries to IGH_GeometricGoo
                                    gGoo.AppendRange(Heron.Convert.OgrGeomToGHGoo(geomUser, userSRSToModelTransform), new GH_Path(i, iLayer, m));

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

                                else
                                {
                                    ///Start get points if open polylines and points
                                    for (int gpc = 0; gpc < geomUser.GetPointCount(); gpc++)
                                    {
                                        ///Loop through geometry points for User SRS
                                        double[] ogrPtUser = new double[3];
                                        geomUser.GetPoint(gpc, ogrPtUser);
                                        Point3d pt3DUser = new Point3d(ogrPtUser[0], ogrPtUser[1], ogrPtUser[2]);
                                        pt3DUser.Transform(userSRSToModelTransform);

                                        gGoo.Append(new GH_Point(pt3DUser), new GH_Path(i, iLayer, m));
                                        ///End loop through geometry points


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


                                    ///Start getting points if closed polylines and multipolygons
                                    for (int gi = 0; gi < geomUser.GetGeometryCount(); gi++)
                                    {
                                        sub_geomUser = geomUser.GetGeometryRef(gi);
                                        OSGeo.OGR.Geometry subsub_geomUser;

                                        if (sub_geomUser.GetGeometryCount() > 0)
                                        {
                                            for (int n = 0; n < sub_geomUser.GetGeometryCount(); n++)
                                            {
                                                subsub_geomUser = sub_geomUser.GetGeometryRef(n);

                                                for (int ptnum = 0; ptnum < subsub_geomUser.GetPointCount(); ptnum++)
                                                {
                                                    ///Loop through geometry points for User SRS
                                                    double[] ogrPtUser = new double[3];
                                                    subsub_geomUser.GetPoint(ptnum, ogrPtUser);
                                                    Point3d pt3DUser = new Point3d(ogrPtUser[0], ogrPtUser[1], ogrPtUser[2]);
                                                    pt3DUser.Transform(userSRSToModelTransform);

                                                    gGoo.Append(new GH_Point(pt3DUser), new GH_Path(i, iLayer, m, gi, n));
                                                    ///End loop through geometry points
                                                }
                                                subsub_geomUser.Dispose();
                                            }
                                        }

                                        else
                                        {
                                            for (int ptnum = 0; ptnum < sub_geomUser.GetPointCount(); ptnum++)
                                            {
                                                ///Loop through geometry points for User SRS
                                                double[] ogrPtUser = new double[3];
                                                sub_geomUser.GetPoint(ptnum, ogrPtUser);
                                                Point3d pt3DUser = new Point3d(ogrPtUser[0], ogrPtUser[1], ogrPtUser[2]);
                                                pt3DUser.Transform(userSRSToModelTransform);

                                                gGoo.Append(new GH_Point(pt3DUser), new GH_Path(i, iLayer, m, gi));

                                                ///End loop through geometry points
                                            }
                                        }

                                        sub_geomUser.Dispose();

                                        /// Get Feature Values
                                        if (fset.PathExists(new GH_Path(i, iLayer, m)))
                                        {
                                            fset.get_Branch(new GH_Path(i, iLayer, m)).Clear();
                                        }
                                        for (int iField = 0; iField < feat.GetFieldCount(); iField++)
                                        {
                                            OSGeo.OGR.FieldDefn fdef = def.GetFieldDefn(iField);
                                            if (feat.IsFieldSet(iField))
                                            {
                                                fset.Append(new GH_String(feat.GetFieldAsString(iField)), new GH_Path(i, iLayer, m));
                                            }
                                            else
                                            {
                                                fset.Append(new GH_String("null"), new GH_Path(i, iLayer, m));
                                            }
                                        }
                                        ///End Get Feature Values
                                    } ///End closed polygons and multipolygons
                                }     ///End points only
                            }
                            m++;
                            geomUser.Dispose();
                            feat.Dispose();
                        }///end while loop through features
                    }
                    dataSource.Dispose();
                }
            }

            ///Not the most elegant way of setting outputs only on run
            if (run)
            {
                DA.SetDataList(0, fieldnames.get_Branch(0));
                DA.SetDataTree(1, fset);
                DA.SetDataTree(2, gGoo);
            }
            DA.SetDataTree(3, mapquery);
        }
Esempio n. 26
0
        /// <summary>
        /// Loads a Ogr datasource with the specified layer
        /// </summary>
        /// <param name="filename">datasource</param>
        /// <param name="layerNum">number of layer</param>
        public Ogr(string filename, int layerNum)
        {
            Filename = filename;

            _ogrDataSource = OgrOgr.Open(filename, 0);
            _ogrLayer = _ogrDataSource.GetLayerByIndex(layerNum);
            OsrSpatialReference spatialReference = _ogrLayer.GetSpatialRef();
            if (spatialReference != null)
                SRID = spatialReference.AutoIdentifyEPSG();
        }
Esempio n. 27
0
        public Ogr(string filename, string layerName)
        {
            Filename = filename;

            _ogrDataSource = OgrOgr.Open(filename, 1);
            _ogrLayer = _ogrDataSource.GetLayerByName(layerName);
            OsrSpatialReference spatialReference = _ogrLayer.GetSpatialRef();
            if (spatialReference != null)
                _srid = spatialReference.AutoIdentifyEPSG();
        }
Esempio n. 28
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)
        {
            ///Setup location
            Point3d location = new Point3d();

            DA.GetData(0, ref location);
            double lat = Heron.Convert.XYZToWGS(location).Y;
            double lon = Heron.Convert.XYZToWGS(location).X;

            ///Setup contour style and unit type
            List <double> contourNums = new List <double>();

            DA.GetDataList <double>(1, contourNums);
            string contourType    = String.Empty;
            double unitConversion = Rhino.RhinoMath.UnitScale(Rhino.RhinoDoc.ActiveDoc.ModelUnitSystem, Rhino.UnitSystem.Meters);

            contourNums.Sort();
            for (int i = 0; i < contourNums.Count; i++)
            {
                double contourNum = contourNums[i];
                if (contourNum < 0.0)
                {
                    contourNum = 0.0;
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Minimum countour must be greater than 0.");
                }

                if (MinutesOrMeters == "Distance")
                {
                    contourType = "contours_meters=";
                    contourNum  = Math.Round(contourNum * unitConversion, 0);
                    if (contourNum < 1)
                    {
                        contourNum = 1;
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Minimum distance contour must be greater than the Rhino unit equivalent of 1 meter.");
                    }
                    if (contourNum > 100000)
                    {
                        contourNum = 100000;
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Maximum distance contour must be less than the Rhino unit equivalent of 1,000km.");
                    }
                }
                else
                {
                    contourType = "contours_minutes=";
                    if (contourNum > 60)
                    {
                        contourNum = 60;
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Maximum minute contour is 60.  Contour value reduced to 60.");
                    }
                }

                contourNums[i] = contourNum;
            }

            ///Setup denoise and make sure Denoise is between 0..1
            double?denoiseNum = null;

            DA.GetData(2, ref denoiseNum);
            if (denoiseNum < 0.0)
            {
                denoiseNum = 0.0;
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Denoise must be greater than 0.");
            }
            if (denoiseNum > 1.0)
            {
                denoiseNum = 1.0;
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Denoise must be less than 1.0");
            }

            ///Setup generalize and make sure it's greater than 0
            double?generalize = null;

            DA.GetData(3, ref generalize);
            double?generalizeNum = generalize * unitConversion;

            if (generalizeNum < 0.0)
            {
                generalizeNum = 0.0;
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Generalize must be greater than 0");
            }

            ///Setup Mapbox token
            string apiKey = string.Empty;

            DA.GetData(4, ref apiKey);
            string mbToken = apiKey;

            if (mbToken == "")
            {
                string hmbToken = System.Environment.GetEnvironmentVariable("HERONMAPBOXTOKEN");
                if (hmbToken != null)
                {
                    mbToken = hmbToken;
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Using Mapbox token stored in Environment Variable HERONMAPBOXTOKEN.");
                }
                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No Mapbox token is specified.  Please get a valid token from mapbox.com");
                    return;
                }
            }

            ///Setup run
            bool run = false;

            DA.GetData(5, ref run);


            ///Outputs
            List <IGH_GeometricGoo> isochrones = new List <IGH_GeometricGoo>();
            List <string>           urls       = new List <string>();

            ///GDAL setup
            RESTful.GdalConfiguration.ConfigureOgr();
            OSGeo.OGR.Ogr.RegisterAll();

            ///Set transform from input spatial reference to Rhino spatial reference
            OSGeo.OSR.SpatialReference rhinoSRS = new OSGeo.OSR.SpatialReference("");
            rhinoSRS.SetWellKnownGeogCS("WGS84");

            ///TODO: use this as override of global SetSRS
            OSGeo.OSR.SpatialReference userSRS = new OSGeo.OSR.SpatialReference("");
            //userSRS.SetFromUserInput(userSRStext);
            userSRS.SetFromUserInput("WGS84");

            ///These transforms move and scale in order to go from userSRS to XYZ and vice versa
            Transform userSRSToModelTransform = Heron.Convert.GetUserSRSToModelTransform(userSRS);


            ///Construct URL query string
            int increment = 0;

            while (increment < contourNums.Count)
            {
                string contourString = contourNums[increment].ToString();

                if (increment + 1 < contourNums.Count)
                {
                    contourString = contourString + "%2C" + contourNums[increment + 1];
                }
                if (increment + 2 < contourNums.Count)
                {
                    contourString = contourString + "%2C" + contourNums[increment + 2];
                }
                if (increment + 3 < contourNums.Count)
                {
                    contourString = contourString + "%2C" + contourNums[increment + 3];
                }

                string url = @"https://api.mapbox.com/isochrone/v1/mapbox/";
                if (!String.IsNullOrEmpty(Profile))
                {
                    url = url + Profile.ToLower() + "/";
                }
                if (lon > -180.0 && lon <= 180.0)
                {
                    url = url + lon + "%2C";
                }
                if (lat > -90.0 && lat <= 90.0)
                {
                    url = url + lat + "?";
                }
                if (!String.IsNullOrEmpty(contourType))
                {
                    url = url + contourType.ToLower();
                }
                if (contourString != null)
                {
                    url = url + contourString;
                }
                if (polygons == "Meshes")
                {
                    url = url + "&polygons=true";
                }
                else
                {
                    url = url + "&polygons=false";
                }
                if (denoiseNum != null)
                {
                    url = url + "&denoise=" + denoiseNum;
                }
                if (generalizeNum != null)
                {
                    url = url + "&generalize=" + generalizeNum;
                }
                if (mbToken != "")
                {
                    url = url + "&access_token=" + mbToken;
                }

                urls.Add(url);
                increment = increment + 4;
            }


            if (run)
            {
                foreach (string u in urls)
                {
                    List <IGH_GeometricGoo> gGoo       = new List <IGH_GeometricGoo>();
                    OSGeo.OGR.DataSource    dataSource = OSGeo.OGR.Ogr.Open(u, 0);

                    if (dataSource == null)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Mapbox returned an invalid response.");
                        return;
                    }

                    ///Only interested in geometry, not fields or values
                    OSGeo.OGR.Layer   ogrLayer = dataSource.GetLayerByIndex(0);
                    OSGeo.OGR.Feature feat;

                    while ((feat = ogrLayer.GetNextFeature()) != null)
                    {
                        if (feat.GetGeometryRef() == null)
                        {
                            AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Isochrone may be too small or otherwise degenerate.");
                            continue;
                        }
                        OSGeo.OGR.Geometry geomUser = feat.GetGeometryRef().Clone();
                        ///reproject geometry to WGS84 and userSRS
                        ///TODO: look into using the SetCRS global variable here
                        if (geomUser.GetSpatialReference() == null)
                        {
                            geomUser.AssignSpatialReference(userSRS);
                        }

                        geomUser.TransformTo(userSRS);
                        if (feat.GetGeometryRef() != null)
                        {
                            isochrones.AddRange(Heron.Convert.OgrGeomToGHGoo(geomUser, userSRSToModelTransform));
                        }
                    }
                    ///Garbage cleanup
                    ogrLayer.Dispose();
                    dataSource.Dispose();
                }
            }

            List <string> mbAtts = new List <string> {
                "© Mapbox, © OpenStreetMap", "https://www.mapbox.com/about/maps/", "http://www.openstreetmap.org/copyright"
            };

            DA.SetDataList(0, isochrones);
            DA.SetDataList(1, urls);
            DA.SetDataList(2, mbAtts);
        }
Esempio n. 29
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());
        }
Esempio n. 30
0
        private void pdfToolStripMenuItem_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < mapBox1.Map.Layers.Count; i++)
            {
                if (mapBox1.Map.Layers[i].LayerName == SelectedLayer)
                {
                    var layer = mapBox1.Map.Layers[i] as VectorLayer;

                    var dataSource = layer.DataSource as GeometryFeatureProvider;

                    OSGeo.OGR.Driver driverSH = OSGeo.OGR.Ogr.GetDriverByName("PDF");



                    var referance = new SpatialReference("PROJCS[\"WGS 84 / Pseudo-Mercator\",GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS 84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],AUTHORITY[\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],UNIT[\"degree\",0.0174532925199433,AUTHORITY[\"EPSG\",\"9122\"]],AUTHORITY[\"EPSG\",\"4326\"]],PROJECTION[\"Mercator_1SP\"],PARAMETER[\"central_meridian\",0],PARAMETER[\"scale_factor\",1],PARAMETER[\"false_easting\",0],PARAMETER[\"false_northing\",0],UNIT[\"metre\",1,AUTHORITY[\"EPSG\",\"9001\"]],AXIS[\"X\",EAST],AXIS[\"Y\",NORTH],EXTENSION[\"PROJ4\",\"+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext  +no_defs\"],AUTHORITY[\"EPSG\",\"3857\"]]");


                    OSGeo.OGR.DataSource dataSourceSH = driverSH.CreateDataSource(Application.StartupPath + "\\" + SelectedLayer + ".pdf", new string[] { "ENCODING=UTF-16" });


                    var layerSH = dataSourceSH.CreateLayer("PointLayer", referance, OSGeo.OGR.wkbGeometryType.wkbPoint, new string[] { "ENCODING=UTF-16" });


                    layerSH.StartTransaction();

                    for (int k = 0; k < dataSource.Features.Columns.Count; k++)
                    {
                        OSGeo.OGR.FieldDefn field = new OSGeo.OGR.FieldDefn(dataSource.Features.Columns[k].Caption, OSGeo.OGR.FieldType.OFTString);


                        layerSH.CreateField(field, 1);
                    }

                    for (int k = 0; k < dataSource.Features.Rows.Count; k++)
                    {
                        OSGeo.OGR.Feature feature = new OSGeo.OGR.Feature(layerSH.GetLayerDefn());

                        if (!string.IsNullOrEmpty(dataSource.Features.Rows[k]["geom_wkt"].ToString()))
                        {
                            OSGeo.OGR.Geometry geom = OSGeo.OGR.Geometry.CreateFromWkt(dataSource.Features.Rows[k]["geom_wkt"].ToString());
                            feature.SetGeometry(geom);
                        }

                        for (int x = 0; x < dataSource.Features.Columns.Count; x++)
                        {
                            var data = dataSource.Features.Rows[k][x].ToString();

                            feature.SetField(dataSource.Features.Columns[x].Caption, data);
                        }
                        try
                        {
                            layerSH.CreateFeature(feature);
                            feature.Dispose();
                        }
                        catch (Exception)
                        {
                        }
                    }
                    layerSH.CommitTransaction();
                    layerSH.SyncToDisk();
                    layerSH.Dispose();

                    dataSourceSH.FlushCache();
                    dataSourceSH.Dispose();

                    driverSH.Dispose();
                }
            }
        }
Esempio n. 31
0
 public OGRWorkspace(OSGeo.OGR.DataSource ds, string connString)
 {
     m_connString = connString;
     m_datasource = ds;
 }