Exemplo n.º 1
0
        public void AddValueToField(PointFeature featureData)
        {
            OSGeo.OGR.Feature feature = new OSGeo.OGR.Feature(_ogrLayer.GetLayerDefn());

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

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

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

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

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

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

            feature.SetGeometry(geometry);

            _ogrLayer.CreateFeature(feature);
        }
Exemplo n.º 2
0
 async static void getDoubFeat(string filePath, int s, int ss)
 {
     await Task.Run(() =>
     {
         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 layer     = ds.GetLayerByIndex(0);
         OSGeo.OGR.Feature oriFeat = layer.GetFeature(s);
         for (int i = s + 1; i < ss; i++)
         {
             OSGeo.OGR.Feature nextFeat = layer.GetFeature(i);
             if (StaticTools.isSame(oriFeat, nextFeat, 1))
             {
                 ids.Add(s);
                 break;
             }
             nextFeat.Dispose();
         }
         oriFeat.Dispose();
         layer.Dispose();
         ds.Dispose();
         tickTime++;
     }
                    );
 }
Exemplo n.º 3
0
        async static void subAdd(Feature poiFeat, string dzx, Layer newLayer)
        {
            await Task.Run(() =>
            {
                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);
                int dzxCount = dzxLayer.GetFeatureCount(0);
                OSGeo.OGR.Geometry poiGeom = poiFeat.GetGeometryRef();
                for (int i = 0; i < dzxLayer.GetFeatureCount(0); i++)
                {
                    OSGeo.OGR.Feature dzxFeat  = dzxLayer.GetFeature(i);
                    OSGeo.OGR.Geometry dzxGeom = dzxFeat.GetGeometryRef();

                    if (poiGeom.Within(dzxGeom))
                    {
                        newLayer.CreateFeature(dzxFeat);
                    }
                    dzxGeom.Dispose();
                    dzxFeat.Dispose();
                }
                poiFeat.Dispose();
                dzxDS.Dispose();
                tickTime++;
            });
        }
Exemplo n.º 4
0
        /// <summary>
        /// 整合坡度多边形(Polygon),并清除重叠部份
        /// </summary>
        /// <param name="subPdx"></param>
        /// <returns></returns>
        public static string zhengHePdx(List <string> subPdx)
        {
            OSGeo.OGR.Ogr.RegisterAll();
            OSGeo.OGR.Driver dr  = OSGeo.OGR.Ogr.GetDriverByName("ESRI shapefile");
            string           res = StaticTools.tempFilePath("shp", "整合");

            OSGeo.OGR.DataSource newDS = dr.CreateDataSource(res, null);                                              //////////////待关闭1  has
            Layer newLayer             = newDS.CreateLayer("podu", null, OSGeo.OGR.wkbGeometryType.wkbPolygon, null); //////////////待关闭2

            for (int i = 0; i < subPdx.Count; i++)
            {
                OSGeo.OGR.DataSource ds = dr.Open(subPdx[i], 0);//////////////待关闭3   has
                Layer layer             = ds.GetLayerByIndex(0);
                for (int j = 0; j < layer.GetFeatureCount(0); j++)
                {
                    OSGeo.OGR.Feature  subFeat  = layer.GetFeature(j);
                    OSGeo.OGR.Geometry subGeom  = subFeat.GetGeometryRef();
                    double             thisArea = subGeom.GetArea();
                    // 清理过小Featuer
                    if (thisArea > 200)
                    {
                        newLayer.CreateFeature(layer.GetFeature(j));
                    }
                }
                ds.Dispose();
                Console.WriteLine("完成整合{0}/{1}", i + 1, subPdx.Count);
            }
            newDS.Dispose();
            cleanPdx(res);
            return(res);
        }
Exemplo n.º 5
0
        private void CreateShp(string outpath, Dictionary <Point2d, Geometry> geoList, OSGeo.OSR.SpatialReference srt)
        {
            //注册ogr库
            string pszDriverName = "ESRI Shapefile";

            OSGeo.OGR.Ogr.RegisterAll();

            //调用对shape文件读写的Driver接口
            OSGeo.OGR.Driver poDriver = OSGeo.OGR.Ogr.GetDriverByName(pszDriverName);
            if (poDriver == null)
            {
                MessageBox.Show("驱动错误!");
            }
            //创建河网shp
            string shpPath = outpath;

            OSGeo.OGR.DataSource poDs;
            poDs = ShpHelp.GetShpDriver().CreateDataSource(shpPath, null);

            //创建图层
            OSGeo.OGR.Layer poLayer;
            //OSGeo.OSR.SpatialReference srt = new OSGeo.OSR.SpatialReference(Const.WGS84);
            poLayer = poDs.CreateLayer("rivernetline.shp", srt, wkbGeometryType.wkbLineString, null);
            //创建一个Feature
            OSGeo.OGR.Feature feature = new OSGeo.OGR.Feature(poLayer.GetLayerDefn());
            foreach (var geo in geoList)
            {
                feature.SetGeometry(geo.Value);
                poLayer.CreateFeature(feature);
            }
            feature.Dispose();
            poDs.Dispose();
        }
Exemplo n.º 6
0
        /// <summary>
        /// 通过是否相交和面积差,获得最小面积差相交要素的ID数组--------多线OK
        /// </summary>
        /// <param name="dzx"></param>
        /// <param name="pdx"></param>
        /// <returns></returns>
        private static int[] getMinIdGroupM(string dzx, string pdx)
        {
            Console.WriteLine("起用多线程提取轮廓线ID....");

            OSGeo.OGR.Ogr.RegisterAll();
            OSGeo.OGR.Driver     dr      = OSGeo.OGR.Ogr.GetDriverByName("ESRI shapefile");
            OSGeo.OGR.DataSource pdDS    = dr.Open(pdx, 0);
            OSGeo.OGR.Layer      pdLayer = pdDS.GetLayerByIndex(0);

            int pdCount = pdLayer.GetFeatureCount(0);

            for (int pdi = 0; pdi < pdCount; pdi++)
            {
                OSGeo.OGR.Feature pdFeat = pdLayer.GetFeature(pdi);
                select(pdFeat, dzx);
            }

            while (tickTime < pdCount)
            {
                Console.WriteLine("第{0}个完成,共{1}个", tickTime, pdCount);
                Thread.Sleep(2000);
            }

            pdLayer.Dispose();
            pdDS.Dispose();
            Console.WriteLine("多线程提取ID完成.....");
            return(minIdG.ToArray());
        }
Exemplo n.º 7
0
        /*************************************  点角式  *****************************************/
        /// <summary>
        /// 清理等后生成新的文件
        ///
        /// </summary>
        public static void claenPoint(string filePath, string savefile, double jiaodu, int cishu)
        {
            OSGeo.OGR.Ogr.RegisterAll();
            OSGeo.OGR.Driver dr = OSGeo.OGR.Ogr.GetDriverByName("ESRI shapefile");
            //进来的Layer
            OSGeo.OGR.DataSource oriDs    = dr.Open(filePath, 0);
            OSGeo.OGR.Layer      oriLayer = oriDs.GetLayerByIndex(0);
            //出去的Layer
            if (System.IO.File.Exists(savefile))
            {
                savefile.deleteFiles();
            }
            OSGeo.OGR.DataSource targDs    = dr.CreateDataSource(savefile, null);
            OSGeo.OGR.Layer      targLayer = targDs.CreateLayer("targ", null, OSGeo.OGR.wkbGeometryType.wkbPolygon, null);

            int featCount = oriLayer.GetFeatureCount(0);

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

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

                ///调选点方法,得到一个新的Featuer
                Geometry newGeom = null;
                if (aFeat.Length > cishu * 3)
                {
                    newGeom = JID(aFeat, jiaodu, cishu);
                }
                else
                {
                    oriFeat.Dispose();
                    continue;
                }
                if (newGeom != null)
                {
                    Feature temp = new Feature(new FeatureDefn(""));
                    temp.SetGeometry(newGeom);
                    targLayer.CreateFeature(temp);
                    temp.Dispose();
                }
                oriFeat.Dispose();
                Console.WriteLine("已完成{0}/{1}", i, featCount);
            }
            oriDs.Dispose();
            targDs.Dispose();
        }
Exemplo n.º 8
0
        public object get_mapped_value(OSGeo.OGR.Feature feature, int esriFieldsIndex)
        {
            // get the ESRI Field
            ESRI.ArcGIS.Geodatabase.IField pField = m_fields.get_Field(esriFieldsIndex);

            if (esriFieldsIndex == m_oidFieldIndex)
            {
                return(feature.GetFID());
            }

            if (esriFieldsIndex == m_geometryFieldIndex)
            {
                System.Diagnostics.Debug.Assert(false);
                return(null); // this should never be called for geometries
            }

            int ogrIndex = (int)m_fieldMapping[esriFieldsIndex];

            if (!feature.IsFieldSet(ogrIndex))
            {
                return(null);
            }

            switch (feature.GetFieldType(ogrIndex))
            {
            // must be kept in sync with utilities library

            case OSGeo.OGR.FieldType.OFTInteger:
                return(feature.GetFieldAsInteger(ogrIndex));

            case OSGeo.OGR.FieldType.OFTReal:
                return(feature.GetFieldAsDouble(ogrIndex));

            case OSGeo.OGR.FieldType.OFTString:
                return(feature.GetFieldAsString(ogrIndex));

            case OSGeo.OGR.FieldType.OFTBinary:

                // WTF, the C# bindings don't have a blob retrieval until this ticket gets solved
                // http://trac.osgeo.org/gdal/ticket/4457#comment:2

                return(null);

            case OSGeo.OGR.FieldType.OFTDateTime:
            {
                int year, month, day, hour, minute, second, flag;
                feature.GetFieldAsDateTime(ogrIndex, out year, out month, out day, out hour, out minute, out second, out flag);

                DateTime date = new DateTime(year, month, day, hour, minute, second);
                return(date);
            }


            default:
                return(feature.GetFieldAsString(ogrIndex));    //most things coerce as strings
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// Gets the features geometry as Wkb.
        /// </summary>
        /// <param name="feature">Feature whose geometry is returned.</param>
        /// <returns>The features geometry.</returns>
        private static byte[] GetGeometry(OgrFeature feature)
        {
            Geometry ogrGeometry = feature.GetGeometryRef();

            ogrGeometry.FlattenTo2D();
            byte[] wkbGeometry = new byte[ogrGeometry.WkbSize()];
            ogrGeometry.ExportToWkb(wkbGeometry, wkbByteOrder.wkbXDR);

            return(wkbGeometry);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="OgrDataReader"/> class.
        /// </summary>
        /// <param name="sDataSource">The path of the data source file.</param>
        /// <param name="sLayer">Name of the layer.</param>
        public OgrDataReader(string sDataSource, string sLayer)
        {
            _ogrDataSource = Ogr.Open(sDataSource, 0);
            _ogrLayer      = sLayer != null?_ogrDataSource.GetLayerByName(sLayer) : _ogrDataSource.GetLayerByIndex(0);

            _ogrFeatureDefinition = _ogrLayer.GetLayerDefn();
            _iFieldCount          = _ogrFeatureDefinition.GetFieldCount();
            BuildSchemaTable();
            _currentFeature = null;
            IsClosed        = false;
        }
Exemplo n.º 11
0
 public static HandleRef getCPtrAndSetReference(Feature obj, object parent) {
   if (obj != null)
   {
     obj.swigParentRef = parent;
     return obj.swigCPtr;
   }
   else
   {
     return new HandleRef(null, IntPtr.Zero);
   }
 }
Exemplo n.º 12
0
 public static HandleRef getCPtrAndDisown(Feature obj, object parent) {
   if (obj != null)
   {
     obj.swigCMemOwn = false;
     obj.swigParentRef = parent;
     return obj.swigCPtr;
   }
   else
   {
     return new HandleRef(null, IntPtr.Zero);
   }
 }
Exemplo n.º 13
0
        /// <summary>
        /// 子线程提取轮廓线ID
        /// </summary>
        /// <param name="pdFeat"></param>
        /// <param name="dzx"></param>
        async static void select(Feature pdFeat, string dzx)
        {
            await Task.Run(() =>
            {
                double afterCha = -1;
                int yesID       = -1;

                OSGeo.OGR.Ogr.RegisterAll();
                OSGeo.OGR.Driver dr       = OSGeo.OGR.Ogr.GetDriverByName("ESRI shapefile");
                OSGeo.OGR.DataSource dzDS = dr.Open(dzx, 0);
                OSGeo.OGR.Layer dzxLayer  = dzDS.GetLayerByIndex(0);

                OSGeo.OGR.Geometry pdGeom = pdFeat.GetGeometryRef();

                int dzCount = dzxLayer.GetFeatureCount(0);

                for (int dzi = 0; dzi < dzCount; dzi++)
                {
                    OSGeo.OGR.Feature dzFeat  = dzxLayer.GetFeature(dzi);
                    OSGeo.OGR.Geometry dzGeom = dzFeat.GetGeometryRef();

                    if (pdGeom.Intersect(dzGeom))
                    {
                        double cha = Math.Abs(dzGeom.GetArea() - pdGeom.GetArea());
                        if (afterCha == -1)
                        {
                            afterCha = cha;
                            yesID    = dzi;
                        }
                        else if (cha < afterCha)
                        {
                            afterCha = cha;
                            yesID    = dzi;
                        }
                    }

                    dzGeom.Dispose();
                    dzFeat.Dispose();
                }

                if (yesID != -1)
                {
                    minIdG.Add(yesID);
                }
                dzDS.Dispose();
                dzxLayer.Dispose();
                pdGeom.Dispose();
                pdFeat.Dispose();
                tickTime++;
            });
        }
Exemplo n.º 14
0
        /// <summary>
        /// This method tries to read another value and returns false if it fails.
        /// </summary>
        /// <returns>Boolean</returns>
        public bool Read()
        {
            if (_iFeatureIndex < _iFeatureCount)
            {
                _currentFeature = _ogrLayer.GetFeature(_iFeatureIndex);
                _iFeatureIndex++;

                return(_iFeatureIndex <= _iFeatureCount);
            }
            else
            {
                return(false);
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Returns geometry Object IDs whose bounding box intersects 'bbox'
        /// </summary>
        /// <param name="bbox"></param>
        /// <returns></returns>
        public Collection <uint> GetObjectIDsInView(SharpMap.Geometries.BoundingBox bbox)
        {
            _OgrLayer.SetSpatialFilterRect(bbox.Min.X, bbox.Min.Y, bbox.Max.X, bbox.Max.Y);
            OSGeo.OGR.Feature _OgrFeature = null;
            _OgrLayer.ResetReading();

            Collection <uint> _ObjectIDs = new Collection <uint>();

            while ((_OgrFeature = _OgrLayer.GetNextFeature()) != null)
            {
                _ObjectIDs.Add((uint)_OgrFeature.GetFID());
                _OgrFeature.Dispose();
            }
            return(_ObjectIDs);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Returns geometry Object IDs whose bounding box intersects 'bbox'
        /// </summary>
        /// <param name="bbox"></param>
        /// <returns></returns>
        public Collection <uint> GetObjectIDsInView(IEnvelope bbox)
        {
            _OgrLayer.SetSpatialFilterRect(bbox.MinX, bbox.MinY, bbox.MaxX, bbox.MaxY);
            OSGeo.OGR.Feature _OgrFeature = null;
            _OgrLayer.ResetReading();

            Collection <uint> _ObjectIDs = new Collection <uint>();

            while ((_OgrFeature = _OgrLayer.GetNextFeature()) != null)
            {
                _ObjectIDs.Add((uint)_OgrFeature.GetFID());
                _OgrFeature.Dispose();
            }
            return(_ObjectIDs);
        }
Exemplo n.º 17
0
        /// <summary>
        /// Returns geometries within the specified bounding box
        /// </summary>
        /// <param name="bbox"></param>
        /// <returns></returns>
        public Collection <IGeometry> GetGeometriesInView(IEnvelope bbox)
        {
            Collection <IGeometry> geoms = new Collection <IGeometry>();

            _OgrLayer.SetSpatialFilterRect(bbox.MinX, bbox.MinY, bbox.MaxX, bbox.MaxY);
            OSGeo.OGR.Feature _OgrFeature = null;

            _OgrLayer.ResetReading();
            while ((_OgrFeature = _OgrLayer.GetNextFeature()) != null)
            {
                geoms.Add(this.ParseOgrGeometry(_OgrFeature.GetGeometryRef()));
                _OgrFeature.Dispose();
            }

            return(geoms);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Returns geometries within the specified bounding box
        /// </summary>
        /// <param name="bbox"></param>
        /// <returns></returns>
        public Collection <SharpMap.Geometries.Geometry> GetGeometriesInView(SharpMap.Geometries.BoundingBox bbox)
        {
            Collection <SharpMap.Geometries.Geometry> geoms = new Collection <SharpMap.Geometries.Geometry>();

            _OgrLayer.SetSpatialFilterRect(bbox.Left, bbox.Bottom, bbox.Right, bbox.Top);
            OSGeo.OGR.Feature _OgrFeature = null;

            _OgrLayer.ResetReading();
            while ((_OgrFeature = _OgrLayer.GetNextFeature()) != null)
            {
                geoms.Add(this.ParseOgrGeometry(_OgrFeature.GetGeometryRef()));
                _OgrFeature.Dispose();
            }

            return(geoms);
        }
Exemplo n.º 19
0
        public static void selectFromPoint(string point, string slopPoly)
        {
            OSGeo.OGR.Ogr.RegisterAll();
            OSGeo.OGR.Driver     dr        = OSGeo.OGR.Ogr.GetDriverByName("ESRI shapefile");
            OSGeo.OGR.DataSource poiDS     = dr.Open(point, 0);
            OSGeo.OGR.DataSource slopDS    = dr.Open(slopPoly, 1);
            OSGeo.OGR.Layer      poiLayer  = poiDS.GetLayerByIndex(0);
            OSGeo.OGR.Layer      slopLayer = slopDS.GetLayerByIndex(0);

            List <int> staIds    = new List <int>();
            int        poiCount  = WorkFlow.pointIds.Count;
            int        slopCount = slopLayer.GetFeatureCount(0);

            for (int i = 0; i < poiCount; i++)
            {
                OSGeo.OGR.Feature  poiFeat = poiLayer.GetFeature(WorkFlow.pointIds[i]);
                OSGeo.OGR.Geometry poiGeom = poiFeat.GetGeometryRef();
                for (int t = 0; t < slopCount; t++)
                {
                    OSGeo.OGR.Feature  slopFeat = slopLayer.GetFeature(t);
                    OSGeo.OGR.Geometry slopGeom = slopFeat.GetGeometryRef();
                    if (poiGeom.Within(slopGeom))
                    {
                        staIds.Add(t);
                        WorkFlow.pointIds[i] = -1;
                    }
                    slopFeat.Dispose();
                }
                poiFeat.Dispose();
            }
            Console.WriteLine("【本次提取到{0}个要素】", staIds.Count);
            while (WorkFlow.pointIds.IndexOf(-1) > -1)
            {
                WorkFlow.pointIds.Remove(-1);
            }

            for (int i = 0; i < slopCount; i++)
            {
                if (staIds.IndexOf(i) == -1)
                {
                    slopLayer.DeleteFeature(i);
                }
            }
            slopDS.deleteFeatUpdate();
            slopDS.Dispose();
            poiDS.Dispose();
        }
Exemplo n.º 20
0
        public OgrDataReader(string sDataSource, string sLayer)
        {
            //wkbReader = new DotSpatial.Data.WKBReader();

            _ogrDataSource = Ogr.Open(sDataSource, 0);

            _ogrLayer = _ogrDataSource.GetLayerByName(sLayer);

            _iFeatureCount        = _ogrLayer.GetFeatureCount(1);
            _ogrFeatureDefinition = _ogrLayer.GetLayerDefn();
            _iFieldCount          = _ogrFeatureDefinition.GetFieldCount();

            BuildSchemaTable();

            _currentFeature = null;
            bClosed         = false;
        }
Exemplo n.º 21
0
        public OgrDataReader(string sDataSource)
        {
            //wkbReader = new DotSpatial.Data.WKBReader();

            _ogrDataSource = Ogr.Open(sDataSource, 0);

            _ogrLayer = _ogrDataSource.GetLayerByIndex(0);

            _iFeatureCount = _ogrLayer.GetFeatureCount(1);
            _ogrFeatureDefinition = _ogrLayer.GetLayerDefn();
            _iFieldCount = _ogrFeatureDefinition.GetFieldCount();

            BuildSchemaTable();

            _currentFeature = null;
            bClosed = false;
        }
Exemplo n.º 22
0
        /// <summary>
        /// 清理原文件
        /// </summary>
        /// <param name="filePath"></param>
        public static void claenPoint(string filePath, double jiaodu, int cishu)
        {
            OSGeo.OGR.Ogr.RegisterAll();
            OSGeo.OGR.Driver     dr       = OSGeo.OGR.Ogr.GetDriverByName("ESRI shapefile");
            OSGeo.OGR.DataSource oriDs    = dr.Open(filePath, 1);
            OSGeo.OGR.Layer      oriLayer = oriDs.GetLayerByIndex(0);

            int featCount = oriLayer.GetFeatureCount(0);

            for (int i = 0; i < featCount; i++)
            {
                OSGeo.OGR.Feature  oriFeat = oriLayer.GetFeature(i);
                OSGeo.OGR.Geometry oriGeom = oriFeat.GetGeometryRef();
                OSGeo.OGR.Geometry subGeom = oriGeom.GetGeometryRef(0);

                int pointCount = subGeom.GetPointCount();

                Point[] aFeat = new Point[pointCount];

                for (int c = 0; c < pointCount; c++)
                {
                    aFeat[c].X = subGeom.GetX(c);
                    aFeat[c].Y = subGeom.GetY(c);
                    aFeat[c].Z = subGeom.GetZ(c);
                }

                OSGeo.OGR.Geometry newGeom = null;
                if (aFeat.Length > cishu * 3)
                {
                    newGeom = JID(aFeat, jiaodu, cishu);
                }
                else
                {
                    oriFeat.Dispose();
                    continue;
                }
                if (newGeom != null)
                {
                    oriFeat.SetGeometry(newGeom);
                    oriLayer.SetFeature(oriFeat);
                }
                Console.WriteLine("cleanPoint已完成{0}/{1}", i, featCount);
                oriFeat.Dispose();
            }
            oriDs.Dispose();
        }
Exemplo n.º 23
0
        public void AddValueToField(PolygonFeature featureData)
        {
            OSGeo.OGR.Feature feature = new OSGeo.OGR.Feature(_ogrLayer.GetLayerDefn());
            feature.SetField(nameof(featureData.SampleId), featureData.SampleId);
            feature.SetField(nameof(featureData.Area), featureData.Area);
            feature.SetField(nameof(featureData.LandCover), featureData.LandCover);
            feature.SetField(nameof(featureData.CropType1), featureData.CropType1);
            feature.SetField(nameof(featureData.CropType2), featureData.CropType2);
            feature.SetField(nameof(featureData.Irrigation1), featureData.Irrigation1);
            feature.SetField(nameof(featureData.Irrigation2), featureData.Irrigation2);
            feature.SetField(nameof(featureData.Irrigation3), featureData.Irrigation3);
            feature.SetField(nameof(featureData.ExtendedData), featureData.ExtendedData);
            feature.SetField(nameof(featureData.ValidityTime),
                             featureData.ValidityTime != null ? featureData.ValidityTime.Value.ToString("yyyy-MM-dd") : "");
            Geometry geometry = Geometry.CreateFromWkt($"POLYGON (({GetCoordinateString(featureData.Geometry)}))");

            feature.SetGeometry(geometry);

            _ogrLayer.CreateFeature(feature);
        }
Exemplo n.º 24
0
        public static void selectDZXFromPoint(string point, string dzx, string savePath)
        {
            OSGeo.OGR.Ogr.RegisterAll();
            OSGeo.OGR.Driver     dr    = OSGeo.OGR.Ogr.GetDriverByName("ESRI shapefile");
            OSGeo.OGR.DataSource poiDS = dr.Open(point, 0);
            OSGeo.OGR.DataSource dzxDS = dr.Open(dzx, 0);
            if (File.Exists(savePath))
            {
                File.Delete(savePath);
            }
            OSGeo.OGR.DataSource newDS    = dr.CreateDataSource(savePath, null);
            OSGeo.OGR.Layer      poiLayer = poiDS.GetLayerByIndex(0);
            OSGeo.OGR.Layer      dzxLayer = dzxDS.GetLayerByIndex(0);
            OSGeo.OGR.Layer      newLayer = newDS.CreateLayer("", dzxLayer.GetSpatialRef(), dzxLayer.GetGeomType(), null);

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

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

                    if (poiGeom.Within(dzxGeom))
                    {
                        newLayer.CreateFeature(dzxFeat);
                    }
                    dzxFeat.Dispose();
                    Console.WriteLine("getFeatureByPoint:{0}/{1}", i, poiCount);
                }
                poiFeat.Dispose();
            }
            Console.WriteLine("【本次提取到{0}个要素】", newLayer.GetFeatureCount(0));
            newDS.Dispose();
            dzxDS.Dispose();
            poiDS.Dispose();
        }
Exemplo n.º 25
0
        /// <summary>
        /// Gets the value of the field.
        /// </summary>
        /// <param name="i">Index of the field.</param>
        /// <param name="schema">Schema that contains the field type.</param>
        /// <param name="feature">The feature whose value gets returned.</param>
        /// <returns>The field value as object.</returns>
        private static object GetValue(int i, IList <Column> schema, OgrFeature feature)
        {
            switch (schema[i].FieldType)
            {
            case FieldType.OFTString:
                return(feature.GetFieldAsString(i));

            case FieldType.OFTInteger:
                return(feature.GetFieldAsInteger(i));

            case FieldType.OFTDateTime:
            {
                int year;
                int month;
                int day;

                int   h;
                int   m;
                float s;
                int   flag;

                feature.GetFieldAsDateTime(i, out year, out month, out day, out h, out m, out s, out flag);
                try
                {
                    return(new DateTime(year, month, day, h, m, (int)s));
                }
                catch (ArgumentOutOfRangeException)
                {
                    return(DateTime.MinValue);
                }
            }

            case FieldType.OFTReal:
                return(feature.GetFieldAsDouble(i));

            default: return(null);
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// Adds the features for the dxf files.
        /// </summary>
        /// <param name="fs">The list of featuresets the features get added to.</param>
        /// <param name="styles">The list of lists the styles get added to.</param>
        /// <param name="layer">The layer to get the features from.</param>
        /// <param name="fieldCount">The number of field contained in the features datarow.</param>
        /// <param name="schema">The list of columns used to fill the datarow.</param>
        private static void AddFeatures(Dictionary <FeatureType, IFeatureSet> fs, Dictionary <FeatureType, List <string> > styles, Layer layer, int fieldCount, IList <Column> schema)
        {
            var        wkbReader  = new WKBReader();
            OgrFeature ogrFeature = layer.GetNextFeature();

            while (ogrFeature != null)
            {
                var wkbGeometry = GetGeometry(ogrFeature);
                var geometry    = wkbReader.Read(wkbGeometry);

                if (geometry != null && geometry.IsValid && !geometry.IsEmpty)
                {
                    IFeature feature = new Feature(geometry);
                    if (feature.FeatureType != FeatureType.Unspecified)
                    {
                        fs[feature.FeatureType].Features.Add(feature);
                        for (int i = 0; i < fieldCount; i++)
                        {
                            feature.DataRow[i] = GetValue(i, schema, ogrFeature) ?? DBNull.Value;
                        }

                        var str = ogrFeature.GetStyleString();
                        if (!string.IsNullOrWhiteSpace(str))
                        {
                            str = RemoveText(str);
                            feature.DataRow["style"] = str;
                            if (!styles[feature.FeatureType].Contains(str))
                            {
                                // add the style to the layer
                                styles[feature.FeatureType].Add(str);
                            }
                        }
                    }
                }

                ogrFeature = layer.GetNextFeature();
            }
        }
Exemplo n.º 27
0
        /// <summary>
        /// Adds the features for the other file types.
        /// </summary>
        /// <param name="fs">The featureset the features get added to.</param>
        /// <param name="styles">The list the styles get added to.</param>
        /// <param name="layer">The layer to get the features from.</param>
        /// <param name="ogrFeatureDefinition">The feature definition that contains the field count.</param>
        /// <param name="schema">The list of columns used to fill the datarow.</param>
        private static void AddFeatures(IFeatureSet fs, IList <string> styles, Layer layer, FeatureDefn ogrFeatureDefinition, IList <Column> schema)
        {
            var        wkbReader  = new WKBReader();
            OgrFeature ogrFeature = layer.GetNextFeature();

            var fieldCount = ogrFeatureDefinition.GetFieldCount();

            while (ogrFeature != null)
            {
                var wkbGeometry = GetGeometry(ogrFeature);
                var geometry    = wkbReader.Read(wkbGeometry);

                if (geometry != null && geometry.IsValid && !geometry.IsEmpty)
                {
                    IFeature feature = new Feature(geometry);
                    if (fs.Features.Count == 0 || feature.FeatureType == fs.FeatureType)
                    {
                        fs.Features.Add(feature);
                        for (int i = 0; i < fieldCount; i++)
                        {
                            feature.DataRow[i] = GetValue(i, schema, ogrFeature) ?? DBNull.Value;
                        }

                        var str = ogrFeature.GetStyleString();

                        feature.DataRow["style"] = str;
                        if (!styles.Contains(str))
                        {
                            // add the style to the layer
                            styles.Add(str);
                        }
                    }
                }

                ogrFeature = layer.GetNextFeature();
            }
        }
Exemplo n.º 28
0
        /************************************* 判断两个Featuer是否重复 *************************************************/
        /// <summary>
        /// 判断两个Featuer是否重复,ori 当前Feat,next 目标Feat
        /// </summary>
        /// <param name="ori"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public static bool isSame(OSGeo.OGR.Feature ori, OSGeo.OGR.Feature next, double fanWei = 0.1)
        {
            OSGeo.OGR.Ogr.RegisterAll();
            OSGeo.OGR.Geometry oriGeom = ori.GetGeometryRef();
            OSGeo.OGR.Envelope oriEnve = new OSGeo.OGR.Envelope();
            oriGeom.GetEnvelope(oriEnve);
            OSGeo.OGR.Geometry nextGeom = next.GetGeometryRef();
            OSGeo.OGR.Envelope nextEnve = new OSGeo.OGR.Envelope();
            nextGeom.GetEnvelope(nextEnve);
            double oriArea  = oriGeom.GetArea();
            double nextArea = nextGeom.GetArea();
            bool   res      =
                Math.Abs(oriEnve.MaxX - nextEnve.MaxX) < fanWei && //外接矩形差
                Math.Abs(oriEnve.MaxY - nextEnve.MaxY) < fanWei &&
                Math.Abs(oriEnve.MinX - nextEnve.MinX) < fanWei &&
                Math.Abs(oriEnve.MinY - nextEnve.MinY) < fanWei;

            //面积?    && Math.Abs(oriArea - nextArea) < 0.1;
            oriGeom.Dispose();
            oriEnve.Dispose();
            nextGeom.Dispose();
            nextEnve.Dispose();
            return(res);
        }
Exemplo n.º 29
0
        static void WritePacket(JsonTextWriter writer, Feature feat, string name, DatedElectionResult[] results, DatedTPPResult[] tppResults)
        {
            Console.WriteLine($"Writing CZML packets for electorate: {name} ");
            
            writer.WriteStartObject(); // {
            {
                // "id": "Electorate/<electorate>"
                writer.WritePropertyName("id");
                writer.WriteValue($"Electorate/{name}");
                // "name": "<electorate>"
                writer.WritePropertyName("name");
                writer.WriteValue(name);
            }
            writer.WriteEndObject(); // }

            var geom = feat.GetGeometryRef();
            string geomName = geom.GetGeometryName();
            if (geomName == "MULTIPOLYGON")
            {
                var subGeomCount = geom.GetGeometryCount();
                foreach (int idx in Enumerable.Range(0, subGeomCount - 1))
                {
                    var subGeom = geom.GetGeometryRef(idx);
                    WriteComponentGeometryFragment(writer, subGeom, name, results, tppResults, idx);
                    Console.Write(".");
                }
                Console.WriteLine();
            }
            else if (geomName == "POLYGON")
            {
                WriteComponentGeometryFragment(writer, geom, name, results, tppResults);
            }
        }
Exemplo n.º 30
0
 /// <summary>
 /// This method tries to read another value and returns false if it fails.
 /// </summary>
 /// <returns>Boolean</returns>
 public bool Read()
 {
     _currentFeature = _ogrLayer.GetNextFeature();
     return(_currentFeature != null);
 }
Exemplo n.º 31
0
 public FeatureWrapper(OSGeo.OGR.Feature feature)
 {
     Value = feature;
 }
Exemplo n.º 32
0
        /// <summary>
        /// This method tries to read another value and returns false if it fails.
        /// </summary>
        /// <returns>Boolean</returns>
        public bool Read()
        {
            if (_iFeatureIndex < _iFeatureCount)
            {
                _currentFeature = _ogrLayer.GetFeature(_iFeatureIndex);
                _iFeatureIndex++;

                return _iFeatureIndex <= _iFeatureCount;
            }
            else
            {
                return false;
            }
        }
Exemplo n.º 33
0
        //将内存中一个图层的数据另存为在文件中
        private Boolean SaveAsToFile(String name, String path)
        {
            Ogr.RegisterAll();
            //to support chinese path
            OSGeo.GDAL.Gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "NO");
            //to support chinese field name
            OSGeo.GDAL.Gdal.SetConfigOption("SHAPE_ENCODING", "");
            string strDriverName = "ESRI Shapefile";
            Driver oDriver       = Ogr.GetDriverByName(strDriverName);

            if (oDriver == null)
            {
                //说明driver不可用
                return(false);
            }
            String pathPrefix  = System.IO.Path.GetDirectoryName(path);
            String pathPostfix = System.Guid.NewGuid().ToString();

            if (File.Exists(pathPrefix + "\\" + pathPostfix))
            {
                File.Delete(pathPrefix + "\\" + pathPostfix);
            }

            //create a datasource, if successfully, a shp file would be created
            DataSource oDs       = oDriver.CreateDataSource(pathPrefix + "\\" + pathPostfix, null);
            Schema     tmpSchema = this.featureSources[name].schema;
            Layer      layer     = oDs.CreateLayer(name, tmpSchema.rs.spetialReference, tmpSchema.geometryType, null);

            //insert all the fields to layer
            //use index instead of field name to avoid the error caused by chinese words
            int fieldcount = tmpSchema.fields.Count;

            for (int i = 0; i < fieldcount; ++i)
            {
                layer.CreateField(tmpSchema.fields.ElementAt(i).Value, 1);
            }
            FeatureDefn fdef = layer.GetLayerDefn();

            FeatureCollection fc = this.featureSources[name].features;
            int fcount           = fc.count;

            for (int i = 0; i < fcount; ++i)
            {
                GisSmartTools.Data.Feature tmpFeature = fc.featureList[i];
                if (!tmpFeature.visible)
                {
                    continue;
                }
                //create a new feature
                OSGeo.OGR.Feature newFeature = new OSGeo.OGR.Feature(fdef);

                //set attribute
                newFeature.SetFID(tmpFeature.featureID);
                for (int j = 0; j < fieldcount; ++j)
                {
                    String    fieldname = tmpSchema.fields.ElementAt(j).Key;
                    FieldType ft        = tmpSchema.fields[fieldname].GetFieldType();
                    try{
                        switch (ft)
                        {
                        case FieldType.OFTString:
                            newFeature.SetField(j, (String)tmpFeature.attributes[fieldname]);
                            break;

                        case FieldType.OFTInteger:
                            newFeature.SetField(j, (int)tmpFeature.attributes[fieldname]);
                            break;

                        case FieldType.OFTReal:
                            newFeature.SetField(j, (double)tmpFeature.attributes[fieldname]);
                            break;

                        case FieldType.OFTWideString:
                            newFeature.SetField(j, (String)tmpFeature.attributes[fieldname]);
                            break;

                        default:
                            newFeature.SetField(j, (String)tmpFeature.attributes[fieldname]);
                            break;
                        }
                    }catch (Exception e)
                    {
                    }
                }

                //get geometry
                OSGeo.OGR.wkbGeometryType featType = tmpFeature.geometry.geometryType;
                OSGeo.OGR.Geometry        geo      = new OSGeo.OGR.Geometry(featType);
                if (geo != null)
                {
                    switch (featType)
                    {
                    case OSGeo.OGR.wkbGeometryType.wkbPoint:
                        GisSmartTools.Geometry.PointD tmpPoint = (GisSmartTools.Geometry.PointD)tmpFeature.geometry;
                        geo.AddPoint(tmpPoint.X, tmpPoint.Y, 0.00);
                        break;

                    case OSGeo.OGR.wkbGeometryType.wkbLineString:
                        GisSmartTools.Geometry.SimplePolyline tmpLine = (GisSmartTools.Geometry.SimplePolyline)tmpFeature.geometry;
                        foreach (GisSmartTools.Geometry.PointD po in tmpLine.points)
                        {
                            geo.AddPoint(po.X, po.Y, 0.00);
                        }
                        break;

                    case wkbGeometryType.wkbMultiLineString:
                        GisSmartTools.Geometry.Polyline lines = (GisSmartTools.Geometry.Polyline)tmpFeature.geometry;
                        foreach (SimplePolyline line in lines.childPolylines)
                        {
                            OSGeo.OGR.Geometry tmpgeo = new OSGeo.OGR.Geometry(OSGeo.OGR.wkbGeometryType.wkbLineString);
                            foreach (GisSmartTools.Geometry.PointD point in line.points)
                            {
                                tmpgeo.AddPoint(point.X, point.Y, 0.00);
                            }
                            geo.AddGeometryDirectly(tmpgeo);
                        }
                        break;

                    case OSGeo.OGR.wkbGeometryType.wkbPolygon:
                        GisSmartTools.Geometry.SimplePolygon gon = (GisSmartTools.Geometry.SimplePolygon)tmpFeature.geometry;
                        foreach (SimplePolyline ring7 in gon.rings)
                        {
                            OSGeo.OGR.Geometry tmpgeo = new OSGeo.OGR.Geometry(OSGeo.OGR.wkbGeometryType.wkbLinearRing);
                            foreach (GisSmartTools.Geometry.PointD point in ring7.points)
                            {
                                tmpgeo.AddPoint(point.X, point.Y, 0.00);
                            }
                            geo.AddGeometryDirectly(tmpgeo);
                        }
                        break;

                    case wkbGeometryType.wkbMultiPolygon:
                        GisSmartTools.Geometry.Polygon gons = (GisSmartTools.Geometry.Polygon)tmpFeature.geometry;
                        foreach (GisSmartTools.Geometry.SimplePolygon cgon in gons.childPolygons)
                        {
                            OSGeo.OGR.Geometry geogon = new OSGeo.OGR.Geometry(OSGeo.OGR.wkbGeometryType.wkbPolygon);
                            foreach (GisSmartTools.Geometry.SimplePolyline ring6 in cgon.rings)
                            {
                                OSGeo.OGR.Geometry geoline = new OSGeo.OGR.Geometry(OSGeo.OGR.wkbGeometryType.wkbLinearRing);
                                foreach (GisSmartTools.Geometry.PointD point6 in ring6.points)
                                {
                                    geoline.AddPoint(point6.X, point6.Y, 0.00);
                                }
                                geogon.AddGeometryDirectly(geoline);
                            }
                            geo.AddGeometryDirectly(geogon);
                        }
                        break;

                    default:
                        break;
                    }
                }

                //set feature
                newFeature.SetGeometry(geo);
                //add to layer
                layer.CreateFeature(newFeature);
            }

            //call Dispose method to save to file
            oDs.Dispose();
            DataSource tds;

            if (this.iDses.TryGetValue(path, out tds))
            {
                tds.Dispose();
                this.iDses.Remove(path);
            }

            //enumerate all the files in the temp file directory and move them to the output directory
            string[] tmpName = System.IO.Directory.GetFiles(pathPrefix + "\\" + pathPostfix);
            foreach (string file in tmpName)
            {
                string decFile = pathPrefix + "\\" + Path.GetFileName(file);
                if (File.Exists(decFile))
                {
                    File.Delete(decFile);
                }
                File.Move(file, decFile);
            }
            Directory.Delete(pathPrefix + "\\" + pathPostfix, true);
            return(true);
        }
Exemplo n.º 34
0
 public int SetFrom(Feature other, int forgiving)
 {
     int ret = OgrPINVOKE.Feature_SetFrom(swigCPtr, Feature.getCPtr(other), forgiving);
     if (OgrPINVOKE.SWIGPendingException.Pending) throw OgrPINVOKE.SWIGPendingException.Retrieve();
     return ret;
 }
Exemplo n.º 35
0
 public bool Equal(Feature feature)
 {
     bool ret = OgrPINVOKE.Feature_Equal(swigCPtr, Feature.getCPtr(feature));
     if (OgrPINVOKE.SWIGPendingException.Pending) throw OgrPINVOKE.SWIGPendingException.Retrieve();
     return ret;
 }
Exemplo n.º 36
0
 public int CreateFeature(Feature feature)
 {
     int ret = OgrPINVOKE.Layer_CreateFeature(swigCPtr, Feature.getCPtr(feature));
     if (OgrPINVOKE.SWIGPendingException.Pending) throw OgrPINVOKE.SWIGPendingException.Retrieve();
     return ret;
 }
Exemplo n.º 37
0
 /// <summary>
 /// Returns the geometry corresponding to the Object ID
 /// </summary>
 /// <param name="oid">Object ID</param>
 /// <returns>geometry</returns>
 public SharpMap.Geometries.Geometry GetGeometryByID(uint oid)
 {
     using (OSGeo.OGR.Feature _OgrFeature = _OgrLayer.GetFeature((int)oid))
         return(this.ParseOgrGeometry(_OgrFeature.GetGeometryRef()));
 }
Exemplo n.º 38
0
        /// <summary>
        /// Opens the specified file
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public IFeatureSet Open(string fileName)
        {
            WkbReader wkbReader = new WkbReader();

            OgrDataReader reader = new OgrDataReader(fileName);
            IFeatureSet fs = new FeatureSet();
            fs.Name = Path.GetFileNameWithoutExtension(fileName);
            fs.Filename = fileName;
            // skip the geometry column which is always column 0
            for (int i = 1; i < reader.FieldCount; i++)
            {
                string sFieldName = reader.GetName(i);
                Type type = reader.GetFieldType(i);

                int uniqueNumber = 1;
                string uniqueName = sFieldName;
                while (fs.DataTable.Columns.Contains(uniqueName))
                {
                    uniqueName = sFieldName + uniqueNumber;
                    uniqueNumber++;
                }
                fs.DataTable.Columns.Add(new DataColumn(uniqueName, type));
            }
            while (reader.Read())
            {
                byte[] wkbGeometry = (byte[])reader["Geometry"];

                IGeometry geometry = wkbReader.Read(wkbGeometry);

                IFeature feature = new Feature(geometry);
                feature.DataRow = fs.DataTable.NewRow();
                for (int i = 1; i < reader.FieldCount; i++)
                {
                    object value = reader[i];
                    if (value == null)
                    {
                        value = DBNull.Value;
                    }
                    feature.DataRow[i - 1] = value;
                }
                fs.Features.Add(feature);
            }

            try
            {
                fs.Projection = reader.GetProj4ProjectionInfo();
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex);
            }

            return fs;
        }
Exemplo n.º 39
0
 public static HandleRef getCPtr(Feature obj)
 {
     return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
 }
Exemplo n.º 40
0
 public int SetFromWithMap(Feature other, int forgiving, int nList, int[] pList)
 {
     int ret = OgrPINVOKE.Feature_SetFromWithMap(swigCPtr, Feature.getCPtr(other), forgiving, nList, pList);
     if (OgrPINVOKE.SWIGPendingException.Pending) throw OgrPINVOKE.SWIGPendingException.Retrieve();
     return ret;
 }
Exemplo n.º 41
0
/*        public virtual FeatureDataSet ExecuteQuery(string query)
        {
            return ExecuteQuery(query, null);
        }*/

/*
        public virtual FeatureDataSet ExecuteQuery(string query, Geometry filter)
        {
            try
            {
                var featureDataSet = new FeatureDataSet();
                featureDataTable.Clear();

                using (Layer ogrLayer = ogrDataSource.ExecuteSQL(query, filter, ""))
                {
                    ogrLayer.ResetReading();
  
                    int featureCount = ogrLayer.GetFeatureCount(1);

                    for (int i = 0; i < featureCount;i++ )
                    {
                        using (var ogrFeature = ogrLayer.GetNextFeature())
                        {
                            FeatureDataRow feature = featureDataTable.NewRow();
                            feature.Id = ogrFeature.GetFID();
                            SetFeatureValuesInRow(featureDataTable, ogrFeature, feature);

                            using (var geometry = ogrFeature.GetGeometryRef())
                            {
                                feature.Geometry = ParseOgrGeometry(geometry);
                            }

                            featureDataTable.AddRow(feature);
                            ogrFeature.Dispose();//release memory, do not wait for gc to do this!

                        }
                    }
                    featureDataSet.Tables.Add(featureDataTable);
                    ogrDataSource.ReleaseResultSet(ogrLayer);

                    return featureDataSet;
                }
            }
            catch (Exception exception)
            {
                log.Error("Error while reading features", exception);
                return new FeatureDataSet();
            }
        }
*/

        private static void SetFeatureValuesInRow(FeatureDataTable featureDataTable, Feature ogrFeature,
                                                  FeatureDataRow feature)
        {
            for (int iField = 0; iField < ogrFeature.GetFieldCount(); iField++)
            {
                if (featureDataTable.Columns[iField].DataType == Type.GetType("System.String"))
                {
                    feature[iField] = ogrFeature.GetFieldAsString(iField);
                }
                else if (featureDataTable.Columns[iField].DataType == Type.GetType("System.Int32"))
                {
                    feature[iField] = ogrFeature.GetFieldAsInteger(iField);
                }
                else if (featureDataTable.Columns[iField].DataType == Type.GetType("System.Double"))
                {
                    feature[iField] = ogrFeature.GetFieldAsDouble(iField);
                }
                else if (featureDataTable.Columns[iField].DataType == Type.GetType("System.DateTime"))
                {
                    int year;
                    int month;
                    int day;
                    int hour;
                    int minute;
                    int second;
                    int TZflag;
                    ogrFeature.GetFieldAsDateTime(iField, out year, out month, out day, out hour, out minute, out second,
                                                  out TZflag);
                    if (year == 0 || month == 0 || day == 0)
                    {
                        feature[iField] = DBNull.Value;
                    }
                    else
                    {
                        feature[iField] = new DateTime(year, month, day, hour, minute, second);
                    }

                }
                else
                {
                    feature[iField] = ogrFeature.GetFieldAsString(iField);
                }
            }
        }
Exemplo n.º 42
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            GH_Structure <IGH_GeometricGoo> gGoo = new GH_Structure <IGH_GeometricGoo>();

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

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

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

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

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

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

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

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

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

            var branchPaths = gGoo.Paths;

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

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

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

                else
                {
                    geomType = "Mixed";
                }

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


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

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

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

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

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

                int quadsecs = 10;

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

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

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

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

                    break;

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

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

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

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

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

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


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

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

            DA.SetDataTree(0, gGooBuffered);
        }