Esempio n. 1
0
        private void Extract(IRasterLayer pRasterLayer, IFeatureLayer pFeatureLayer)
        {
            try
            {
                IRaster       pRaster       = pRasterLayer.Raster;
                IFeatureClass pFeatureClass = pFeatureLayer.FeatureClass;

                ToggleSA(true);

                IExtractionOp2 pExtractionOp = new RasterExtractionOpClass();

                IGeoDataset pOutGeoDS = pExtractionOp.ExtractValuesToPoints(pFeatureClass as IGeoDataset, pRaster as IGeoDataset, false);

                IFeatureLayer player = new FeatureLayerClass();
                player.FeatureClass = pOutGeoDS as IFeatureClass;
                player.Name         = "Raster2Points";

                string g = System.IO.Path.GetDirectoryName(strSaveFile);
                if (System.IO.File.Exists(strSaveFile))
                {
                    System.IO.File.Delete(strSaveFile);
                }
                ITable ptable = player.FeatureClass as ITable;
                ExportTable2DBF(ptable, System.IO.Path.GetDirectoryName(strSaveFile), System.IO.Path.GetFileName(strSaveFile));
                AddTable(System.IO.Path.GetDirectoryName(strSaveFile), System.IO.Path.GetFileName(strSaveFile));
                ArcMap.Document.ActiveView.FocusMap.AddLayer(player);
                ToggleSA(false);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                MessageBox.Show(ex.StackTrace);
            }
        }
Esempio n. 2
0
        private void sure_Click(object sender, EventArgs e)
        {
            string layer_name = layers1.Text;
            ILayer choose     = null;
            double @base      = double.Parse(basenumber.Text);
            double interval   = double.Parse(dis.Text);


            ILayer temp_lay;

            for (int i = 0; i < m_hookHelper.FocusMap.LayerCount; i++)
            {
                temp_lay = m_hookHelper.FocusMap.get_Layer(i);
                if (temp_lay.Name == layer_name)
                {
                    choose = temp_lay;
                }
            }

            IRasterLayer chooseras = choose as IRasterLayer;


            ISurfaceOp2 pSurfaceOp = default(ISurfaceOp2);

            pSurfaceOp = new RasterSurfaceOp() as ISurfaceOp2;
            IGeoDataset       pRasterDataset       = chooseras as IGeoDataset;
            IWorkspace        pShpWS               = default(IWorkspace);
            IWorkspaceFactory pShpWorkspaceFactory =
                new  ESRI.ArcGIS.DataSourcesFile.ShapefileWorkspaceFactory();

            pShpWS     = pShpWorkspaceFactory.OpenFromFile(FilePath, 0);
            pSurfaceOp = new RasterSurfaceOp() as ISurfaceOp2;
            IRasterAnalysisEnvironment pRasterAEnv =
                (IRasterAnalysisEnvironment)pSurfaceOp;

            pRasterAEnv.OutWorkspace = pShpWS;
            IGeoDataset   pOutput       = default(IGeoDataset);
            IFeatureClass pFeatureClass = default(IFeatureClass);
            IFeatureLayer pFLayer       = default(IFeatureLayer);



            object tmpbase;

            tmpbase = (object)@base;
            object tmpmy = 1;

            pOutput = pSurfaceOp.Contour(pRasterDataset, interval,
                                         ref tmpbase, ref tmpmy);
            pFeatureClass        = (IFeatureClass)pOutput;
            pFLayer              = new FeatureLayer();
            pFLayer.FeatureClass = pFeatureClass;
            IGeoFeatureLayer pGeoFL = default(IGeoFeatureLayer);

            pGeoFL = (IGeoFeatureLayer)pFLayer;
            pGeoFL.DisplayAnnotation = false;
            pGeoFL.DisplayField      = "CONTOUR";
            pGeoFL.Name = "CONTOUR";
            m_hookHelper.FocusMap.AddLayer(pGeoFL);
        }
Esempio n. 3
0
        internal static Dictionary <string, double> SummariseRasterStatistically(IGeoDataset pRasterGeoDataset)
        {
            IRasterBandCollection tClippedAsBandCollection = pRasterGeoDataset as IRasterBandCollection;
            IRasterBand           tClippedBand             = tClippedAsBandCollection.Item(0);

            logger.LogMessage(ServerLogger.msgType.debug, "SummariseContinuousRaster", 99, "Continuous raster clipped, checking stats...");
            bool tHasStatistics;

            tClippedBand.HasStatistics(out tHasStatistics);
            // what on earth? why not just have a bool return type to the HasStatistics method??!
            if (!tHasStatistics)
            {
                tClippedBand.ComputeStatsAndHist();
            }
            IRasterStatistics tClippedStats = tClippedBand.Statistics;

            //tClippedStats.Recalculate();
            logger.LogMessage(ServerLogger.msgType.debug, "SummariseContinuousRaster", 99, "Continuous raster stats made, recording info...");
            Dictionary <string, double> tResults = new Dictionary <string, double>();

            tResults["Mean"] = tClippedStats.Mean;
            tResults["Max"]  = tClippedStats.Maximum;
            tResults["Min"]  = tClippedStats.Minimum;
            //NB Median isn't available with floating data. (Neither are majority,minority,variety). Would need
            //to e.g. convert to int by multiplying raster first.
            //tResults["Median"] = tClippedStats.Median;
            return(tResults);
        }
Esempio n. 4
0
        private void btnImport_Click(object sender, EventArgs e)
        {
            ESRI.ArcGIS.SystemUI.ICommand command = new ControlsAddDataCommandClass();
            command.OnCreate(pMapControlSpacial);
            command.OnClick();
            //在此添加空间参考的详细信息
            if (pMapControlSpacial.Map != null)
            {
                for (int i = 0; i < pMapControlSpacial.Map.LayerCount; i++)
                {
                    ILayer pLayer = pMapControlSpacial.Map.get_Layer(i);

                    if (pLayer is IFeatureLayer)
                    {
                        IFeatureLayer     pFeatureLayer     = pLayer as IFeatureLayer;
                        IGeoDataset       pGeoDataset       = pFeatureLayer as IGeoDataset;
                        ISpatialReference pSpatialReference = pGeoDataset.SpatialReference;

                        richTextReference.Text = ClsGDBDataCommon.GetReferenceString(pSpatialReference);
                        pSpaReference          = pSpatialReference;
                    }
                    if (pLayer is IRasterLayer)
                    {
                        IRasterLayer      pRasterLayer      = pLayer as IRasterLayer;
                        IRaster           pRaster           = pRasterLayer.Raster;
                        IRasterProps      pRasterProps      = pRaster as IRasterProps;
                        ISpatialReference pSpatialReference = pRasterProps.SpatialReference;

                        richTextReference.Text = ClsGDBDataCommon.GetReferenceString(pSpatialReference);
                        pSpaReference          = pSpatialReference;
                    }
                }
                pMapControlSpacial.Map.ClearLayers();
            }
        }
Esempio n. 5
0
        /// <summary>
        /// 创建Tin文件
        /// </summary>
        /// <param name="pFeatureClass">要素类</param>
        private void CreateTinFromFeature(IFeatureClass pFeatureClass)
        {
            try
            {
                IGeoDataset pGeoDataset = pFeatureClass as IGeoDataset;
                ESRI.ArcGIS.Geometry.IEnvelope pExtent = pGeoDataset.Extent;
                pExtent.SpatialReference = pGeoDataset.SpatialReference;

                //获得高程值
                IFields pFields = pFeatureClass.Fields;
                IField  pHeightField;
                pHeightField = pFields.get_Field(3);

                ITinEdit pTinEdit = new TinClass();
                pTinEdit.InitNew(pExtent);
                object Missing     = Type.Missing;
                object pbUseShapeZ = Missing;
                object pOverWrite  = Missing;

                pTinEdit.AddFromFeatureClass(pFeatureClass, null, pHeightField, null, esriTinSurfaceType.esriTinMassPoint, ref pbUseShapeZ);

                pTinEdit.SaveAs(Application.StartupPath + "\\Convert\\TemTIN\\" + this.Random, ref pOverWrite);
                pTinEdit.StopEditing(false);
                CreateContourData(Application.StartupPath + "\\Convert\\TemTIN");
            }
            catch (Exception)
            {
            }
        }
Esempio n. 6
0
        /// <summary>
        /// 执行矢量转栅格
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FtoR_backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            //设置CancellationPending可以退出任务线程
            if (worker.CancellationPending == true)
            {
                e.Cancel = true;
            }
            else
            {
                try
                {
                    FileInfo inputinfo  = new FileInfo(featuretoraster_inputcombox.Text);
                    FileInfo outputinfo = new FileInfo(featuretoraster_output.Text);


                    IWorkspaceFactory outputworkspaceFactory = new RasterWorkspaceFactoryClass();
                    IWorkspace        outputworkspaceop      = outputworkspaceFactory.OpenFromFile(outputinfo.DirectoryName, 0);//创建输出工作空间

                    IWorkspaceFactory       workspacefactory       = new ShapefileWorkspaceFactoryClass();
                    IFeatureWorkspace       featureworkspace       = workspacefactory.OpenFromFile(inputinfo.DirectoryName, 0) as IFeatureWorkspace;
                    IFeatureClass           featureclass           = featureworkspace.OpenFeatureClass(inputinfo.Name);
                    IFeatureClassDescriptor featureClassDescriptor = new FeatureClassDescriptorClass();
                    featureClassDescriptor.Create(featureclass, null, featuretoraster_fieldcombox.Text);
                    IGeoDataset geodatasetop = featureClassDescriptor as IGeoDataset;

                    IConversionOp conversionOp = new RasterConversionOpClass();
                    //转换设置
                    IRasterAnalysisEnvironment rasterAnalysisEnvironment = conversionOp as IRasterAnalysisEnvironment;
                    //栅格的大小
                    double dCellSize = Convert.ToDouble(featuretoraster_cellsize.Text);
                    object oCellSize = dCellSize as object;
                    //设置栅格大小
                    rasterAnalysisEnvironment.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, ref oCellSize);
                    string format = "";
                    if (outputinfo.Extension == ".tif")
                    {
                        format = "TIFF";
                    }
                    else if (outputinfo.Extension == ".img")
                    {
                        format = "IMAGINE Image";
                    }
                    else
                    {
                        format = "GRID";
                    }
                    //启动预处理计时
                    watch = new Stopwatch();
                    watch.Start();
                    //执行转换
                    conversionOp.ToRasterDataset(geodatasetop, format, outputworkspaceop, outputinfo.Name);
                }
                catch (Exception erro)
                {
                    MessageBox.Show(erro.Message, "错误");
                }
            }
        }
Esempio n. 7
0
        public void CreateFeatureClass()
        {
            string Barycentre    = "Barycentre";
            string GravityVector = "GravityVector";
            string Arrow         = "Arrow";

            string[] Enclose = new string[VectorModel.TinCount];
            Ctxt = new StreamWriter(Cpath);
            Vtxt = new StreamWriter(Vpath);


            //传递坐标系
            IGeoDataset       geoDataset       = tinD as IGeoDataset;
            ISpatialReference spatialReference = geoDataset.SpatialReference;

            //创建要素类
            BarycentreFields       = CreateFieldsCollectionForFeatueClass(spatialReference, esriGeometryType.esriGeometryPoint);
            BarycentreFeatureClass = CreateStandaloneFeatureClass(Workspace, Barycentre, BarycentreFields);

            GravityVectorFields       = CreateFieldsCollectionForFeatueClass(spatialReference, esriGeometryType.esriGeometryPolyline);
            GravityVectorFeatureClass = CreateStandaloneFeatureClass(Workspace, GravityVector, GravityVectorFields);

            ArrowFields       = CreateFieldsCollectionForFeatueClass(spatialReference, esriGeometryType.esriGeometryMultiPatch);
            ArrowFeatureClass = CreateStandaloneFeatureClass(Workspace, Arrow, ArrowFields);

            EncloseFields = CreateFieldsCollectionForFeatueClass(spatialReference, esriGeometryType.esriGeometryMultiPatch);
            for (int i = 0; i < VectorModel.TinCount; i++)
            {
                Enclose[i]             = "Enclose" + i;
                EncloseFeatureClass[i] = CreateStandaloneFeatureClass(Workspace, Enclose[i], EncloseFields);
            }
        }
Esempio n. 8
0
        public void TransferMapDataWithinExtents_Test(string subDirectory, string mapDocumentFilename, string dataframeName, string outputShapefileDirectory)
        {
            string temp   = System.IO.Path.Combine(_dataDirectory, subDirectory);
            string mapDoc = System.IO.Path.Combine(temp, mapDocumentFilename);

            IMapDocument mapDocument = new MapDocumentClass();

            mapDocument.Open(mapDoc, null);

            IMap map = GeodatabaseUtil.GetMap(mapDocument, dataframeName);
            List <IFeatureLayer> layers     = GeodatabaseUtil.GetFeatureLayers(map);
            IDataset             dataset    = (IDataset)layers[0].FeatureClass;
            IGeoDataset          geoDataset = (IGeoDataset)layers[0].FeatureClass;

            string destination = System.IO.Path.Combine(temp, outputShapefileDirectory);

            if (Directory.Exists(destination))
            {
                Directory.Delete(destination, true);
            }
            Directory.CreateDirectory(destination);

            IWorkspace        outWorkspace        = GeodatabaseUtil.GetShapefileWorkspace(destination);
            IFeatureWorkspace outFeatureWorkspace = (IFeatureWorkspace)outWorkspace;
            IWorkspaceName    outWorkspaceName    = GeodatabaseUtil.GetWorkspaceName(outWorkspace);
            IFeatureClassName outFeatureclassName = GeodatabaseUtil.GetFeatureClassName(outWorkspaceName, dataset.Name);

            //ESRI.ArcGIS.ADF.Web.Geometry.Envelope envelope = new ESRI.ArcGIS.ADF.Web.Geometry.Envelope(227884.141, 4167884.377, 602406.528, 4470244.455);
            ESRI.ArcGIS.ADF.Web.Geometry.Envelope envelope = new ESRI.ArcGIS.ADF.Web.Geometry.Envelope(445092.693, 4360557.744, 541068.565, 4418287.592);

            Dictionary <int, KeyValuePair <string, IEnumInvalidObject> > invalidObjects = GeodatabaseUtil.TransferMapDataWithinExtents(map, outFeatureWorkspace, null, envelope, geoDataset.SpatialReference);
        }
        public static ISpatialReference GetSpatialReference(IFeatureClass pFeatureClass)
        {
            IGeoDataset       pGeoDataset       = pFeatureClass as IGeoDataset;
            ISpatialReference pSpatialReference = pGeoDataset.SpatialReference;

            return(pSpatialReference);
        }
Esempio n. 10
0
        private void frmProperties2_Load(object sender, EventArgs e)
        {
            try
            {
                //mForm = System.Windows.Forms.Application.OpenForms["MainForm"] as MainForm;
                //m_mapControl = (IMapControl3)mForm.axMapControl1.Object;
                //mlayer = (ILayer)m_mapControl.CustomProperty;
                //m_pSnippet = new clsSnippet();
                m_fLayer  = (IFeatureLayer)mlayer;
                m_pFClass = (IFeatureClass)m_fLayer.FeatureClass;

                IGeoDataset       GeoDataset             = (IGeoDataset)m_pFClass;
                ISpatialReference pSpatialReference      = GeoDataset.SpatialReference;
                ESRI.ArcGIS.Geodatabase.IDataset dataset = (ESRI.ArcGIS.Geodatabase.IDataset)(m_fLayer);


                this.Text               = mlayer.Name + " Properties";
                lblLayerName.Text       = mlayer.Name;
                lblLayerProjection.Text = pSpatialReference.Name;
                txtFilePath.Text        = dataset.Workspace.PathName;
            }
            catch (Exception ex)
            {
                frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog();
                return;
            }
        }
Esempio n. 11
0
        public ISpatialReference getSpatialRef(string catalogpath)
        {
            object            dtype    = "";
            ISpatialReference spRef    = null;
            IDataElement      dtE      = gp.GetDataElement(catalogpath, ref dtype);
            string            datatype = dtE.Type.ToLower();

            Console.WriteLine(datatype);
            try
            {
                if (datatype.IndexOf("raster") > -1)
                {
                    IGeoDataset rstd = (IGeoDataset)getRasterDataset(catalogpath);
                    spRef = rstd.SpatialReference;
                }
                else
                {
                    IGeoDataset ftrs = (IGeoDataset)getFeatureClass(catalogpath);
                    spRef = ftrs.SpatialReference;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.ToString());
            }
            return(spRef);
        }
Esempio n. 12
0
        private void FrmCoordinateSystem_Load(object sender, EventArgs e)
        {
            switch (startPosition)
            {
            case "startFromMap":
                DirectoryInfo CoordDirInfo = new DirectoryInfo(ClsGDBDataCommon.GetParentPathofExe() + @"Resource\Coordinate Systems");
                LoadDirectories(advTreeCoord.Nodes[0], CoordDirInfo);

                richTextReference.Text = ClsGDBDataCommon.GetReferenceString(pMapControl.SpatialReference);
                IEngineEditor pEngineEdit = new EngineEditorClass();
                if (pEngineEdit.Map == pMapControl.Map)
                {
                    advTreeCoord.Enabled = false;
                    MessageBox.Show("该图层处在编辑状态不能修改坐标系统", "提示", MessageBoxButtons.YesNo);
                }
                break;

            case "startFromLayer":
                DirectoryInfo CoordDirInfoLayer = new DirectoryInfo(ClsGDBDataCommon.GetParentPathofExe() + @"Resource\Coordinate Systems");
                LoadDirectories(advTreeCoord.Nodes[0], CoordDirInfoLayer);
                IGeoDataset       geoDataset = pLayer as IGeoDataset;
                ISpatialReference reference  = geoDataset.SpatialReference;

                richTextReference.Text = ClsGDBDataCommon.GetReferenceString(reference);
                break;
            }
        }
Esempio n. 13
0
        private void IDWInterpolation(IFeatureClass pointFeature, IRaster refRaster, string name)
        {
            IFeatureClassDescriptor pointDescript = new FeatureClassDescriptorClass();

            pointDescript.Create(pointFeature, null, name);
            object                     extend   = (refRaster as IGeoDataset).Extent;
            IRasterProps               refProps = refRaster as IRasterProps;
            object                     cell     = refProps.MeanCellSize().X;
            IInterpolationOp           interpla = new RasterInterpolationOpClass();
            IRasterAnalysisEnvironment IDWEnv   = interpla as IRasterAnalysisEnvironment;

            IDWEnv.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, ref cell);
            IDWEnv.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvValue, ref extend);
            IGeoDataset   output = interpla.IDW((IGeoDataset)pointDescript, 2, null, null);
            IGeoDataset   input  = refRaster as IGeoDataset;
            IExtractionOp op     = new RasterExtractionOpClass();

            output = op.Raster(output, input);
            var               clipRaster   = (IRaster)output;
            ISaveAs           pSaveAs      = clipRaster as ISaveAs;
            IWorkspaceFactory workspaceFac = new RasterWorkspaceFactoryClass();
            var               groups       = Regex.Match(name, @"^(\d+)_(\d+)_(\d+)$").Groups;

            name = string.Format("{0:D2}{1:D2}", int.Parse(groups[2].Value), int.Parse(groups[3].Value));
            IDataset outDataset = pSaveAs.SaveAs(fileName + name + ".img", workspaceFac.OpenFromFile(filePath, 0), "IMAGINE Image");

            System.Runtime.InteropServices.Marshal.ReleaseComObject(outDataset);
        }
Esempio n. 14
0
        private void _CalculateFlowDir()
        {
            OnProgress("Filling DEM...");

            // - Fill & calculate flow direction
            IHydrologyOp   hydroOp         = new RasterHydrologyOpClass();
            IRasterMakerOp rasterMaker     = new RasterMakerOpClass();
            ILogicalOp     logicalOp       = new RasterMathOpsClass();
            IConditionalOp conditionalOp   = new RasterConditionalOpClass();
            IGeoDataset    fillTemp        = null;
            IGeoDataset    flowTemp        = null;
            IGeoDataset    flowTemp2       = null;
            IGeoDataset    demNulls        = null;
            IGeoDataset    zeroRaster      = null;
            IWorkspace     resultWorkspace = null;

            try
            {
                SetAnalysisEnvironment((IRasterAnalysisEnvironment)hydroOp);
                SetAnalysisEnvironment((IRasterAnalysisEnvironment)rasterMaker);
                SetAnalysisEnvironment((IRasterAnalysisEnvironment)conditionalOp);
                SetAnalysisEnvironment((IRasterAnalysisEnvironment)logicalOp);

                object zLimit = null;
                fillTemp = hydroOp.Fill((IGeoDataset)_punchedDEM, ref zLimit);

                //Make output permanent
                resultWorkspace = GetResultRasterWorkspace();
                ITemporaryDataset tempFillDataset = ((IRasterAnalysisProps)fillTemp).RasterDataset as ITemporaryDataset;
                string            fillPath        = CreateTempFileName(_GetResultDir(), "filldem", "");
                string            fillFileName    = System.IO.Path.GetFileName(fillPath);
                tempFillDataset.MakePermanentAs(fillFileName, resultWorkspace, "GRID");
                _filledDEM = ((IRasterWorkspace)resultWorkspace).OpenRasterDataset(fillFileName).CreateDefaultRaster() as IRaster;

                OnProgress("Calculating flow direction...");
                flowTemp = hydroOp.FlowDirection((IGeoDataset)fillTemp, false, true);

                //Set holes to flowdir of 0
                object boxedFlowTemp = flowTemp;
                zeroRaster = rasterMaker.MakeConstant(0.0, true);
                flowTemp2  = conditionalOp.Con(logicalOp.IsNull((IGeoDataset)fillTemp), zeroRaster, ref boxedFlowTemp);
                demNulls   = logicalOp.IsNull((IGeoDataset)_dem);
                string flowPath = CreateTempFileName(_GetResultDir(), "flowdir", "");
                _flowDir = GeoprocessingTools.SetNull((IRaster)demNulls, (IRaster)flowTemp2, flowPath);
            }
            finally
            {
                UrbanDelineationExtension.ReleaseComObject(flowTemp);
                UrbanDelineationExtension.ReleaseComObject(flowTemp2);
                UrbanDelineationExtension.ReleaseComObject(demNulls);
                UrbanDelineationExtension.ReleaseComObject(zeroRaster);
                UrbanDelineationExtension.ReleaseComObject(conditionalOp);
                UrbanDelineationExtension.ReleaseComObject(logicalOp);
                UrbanDelineationExtension.ReleaseComObject(rasterMaker);
                UrbanDelineationExtension.ReleaseComObject(hydroOp);
                UrbanDelineationExtension.ReleaseComObject(resultWorkspace);
            }

            OnProgress("Flow direction calculated.");
        }
Esempio n. 15
0
        /// <summary>
        /// 矢量点转栅格
        /// </summary>
        /// <param name="xjFeatureLayer">矢量图层</param>
        /// <param name="RasterPath">栅格绝对路径</param>
        /// <param name="CellSize">栅格边长</param>
        /// <param name="SecletctedField">所选字段(高程等)</param>
        /// <returns>返回栅格图层</returns>
        private ILayer xjShpPointToRaster(IFeatureLayer xjFeatureLayer, string RasterPath, double CellSize, string SecletctedField)
        {
            IFeatureClass           xjFeatureClass           = xjFeatureLayer.FeatureClass;
            IFeatureClassDescriptor xjFeatureClassDescriptor = new FeatureClassDescriptorClass();//using ESRI.ArcGIS.GeoAnalyst;

            xjFeatureClassDescriptor.Create(xjFeatureClass, null, SecletctedField);
            IGeoDataset xjGeoDataset = xjFeatureClassDescriptor as IGeoDataset;

            IWorkspaceFactory          xjwsf          = new RasterWorkspaceFactoryClass(); //using ESRI.ArcGIS.DataSourcesRaster;
            string                     xjRasterFolder = System.IO.Path.GetDirectoryName(RasterPath);
            IWorkspace                 xjws           = xjwsf.OpenFromFile(xjRasterFolder, 0);
            IConversionOp              xjConversionOp = new RasterConversionOpClass();
            IRasterAnalysisEnvironment xjRasteren     = xjConversionOp as IRasterAnalysisEnvironment;

            object xjCellSize = CellSize as object;

            xjRasteren.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, ref xjCellSize);

            string         xjFileName = System.IO.Path.GetFileName(RasterPath);
            IRasterDataset xjdaset2   = xjConversionOp.ToRasterDataset(xjGeoDataset, "TIFF", xjws, xjFileName);

            IRasterLayer xjRasterLayer = new RasterLayerClass();

            xjRasterLayer.CreateFromDataset(xjdaset2);
            ILayer xjLayer = xjRasterLayer;

            xjRasterLayer.Name = xjFileName;

            return(xjLayer);
        }
Esempio n. 16
0
 /// <summary>
 /// 把图层添加到地图中
 /// </summary>
 /// <param name="basicMap"></param>
 /// <param name="addedLayer"></param>
 public static void AddLyrToBasicMap(IBasicMap basicMap, ILayer addedLayer)
 {
     try
     {
         //判断空间参考是否一致
         IDataset dataSet = addedLayer as IDataset;
         if (dataSet is IGeoDataset)
         {
             IGeoDataset geoDataset = dataSet as IGeoDataset;
             if (geoDataset.SpatialReference != null && basicMap.SpatialReference != null)
             {
                 //这里只是通过名称进行下比较  如果说想要比较的严格的话 可以通过克隆的方法进行
                 if (blnEditMapSpatial == true && geoDataset.SpatialReference.Name != basicMap.SpatialReference.Name)
                 {
                     if (MessageBox.Show("当前加载图层的空间参考与地图空间参考不一致,是否更改地图空间参考?",
                                         "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                     {
                         basicMap.SpatialReference = geoDataset.SpatialReference;
                     }
                     else
                     {
                         //不进行比较了
                         blnEditMapSpatial = false;
                     }
                 }
             }
             basicMap.AddLayer(addedLayer);
         }
     }
     catch (Exception ex)
     {
         System.Diagnostics.Trace.WriteLine(ex.Message);
     }
 }
Esempio n. 17
0
        public IGeoDataset SetNull(string inRaster, int excludeValue)
        {
            IMapAlgebraOp pRSalgebra  = null;
            IGeoDataset   pGeoDataset = null;

            try
            {
                pGeoDataset = EngineAPI.OpenRasterFile(inRaster) as IGeoDataset;
                string expression = "SetNull([InRaster] != " + excludeValue + ",[InRaster])";
                pRSalgebra = new RasterMapAlgebraOpClass();
                pRSalgebra.BindRaster(pGeoDataset, "InRaster");
                IGeoDataset resDataset = pRSalgebra.Execute(expression);
                return(resDataset);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (pRSalgebra != null)
                {
                    Marshal.ReleaseComObject(pRSalgebra);
                }
                if (pGeoDataset != null)
                {
                    Marshal.ReleaseComObject(pGeoDataset);
                }
            }
        }
		/// <summary>
		/// Call the OD cost matrix solver and display the results
		/// </summary>
		/// <param name="sender">Sender of the event</param>
		/// <param name="e">Event</param>
		private void cmdSolve_Click(object sender, EventArgs e)
		{
            IGPMessages gpMessages = new GPMessagesClass();
            try
			{
				lstOutput.Items.Clear();
				cmdSolve.Text = "Solving...";

				SetSolverSettings();

				// Solve
				if (!m_NAContext.Solver.Solve(m_NAContext, gpMessages, null))
					lstOutput.Items.Add("Partial Result");

				DisplayOutput();

				// Zoom to the extent of the route
				IGeoDataset gDataset = m_NAContext.NAClasses.get_ItemByName("ODLines") as IGeoDataset;
				IEnvelope envelope = gDataset.Extent;
				if (!envelope.IsEmpty)
				{
					envelope.Expand(1.1, 1.1, true);
					axMapControl.Extent = envelope;
				}

				axMapControl.Refresh();
			}
			catch (Exception ex)
			{
                lstOutput.Items.Add("Failure: " + ex.Message);
            }

            lstOutput.Items.Add(GetGPMessagesAsString(gpMessages));
            cmdSolve.Text = "Find OD Cost Matrix";
		}
Esempio n. 19
0
        /// <summary>
        /// 复制featureclass图形和属性的方法
        /// </summary>
        /// <param name="name">待创建要素类的名称</param>
        /// <param name="target_FeatureClass">需要写入图形和属性的空要素</param>
        /// <param name="CADFeatureClass">需要复制的CAD要素类</param>
        public void CreateFeatureClassByAtt(string name, IFeatureClass target_FeatureClass, IFeatureClass CADFeatureClass)
        {
            List <string>  AttList      = new List <string>();
            IQueryFilter   pQueryFilter = new QueryFilterClass();
            IFeatureCursor pFeaCursor;
            IFeature       pFeature;
            IFeatureBuffer pFeaBuffer = null;

            AttList = getUniqueValue(CADFeatureClass, "Layer");
            pQueryFilter.WhereClause = "Layer = '" + name.Substring(name.IndexOf('-') + 1) + "'";
            pFeaCursor = CADFeatureClass.Search(pQueryFilter, false);
            //用IFeatureBuffer提高运算速度
            IFeatureCursor targetCursor = target_FeatureClass.Insert(true);

            while ((pFeature = pFeaCursor.NextFeature()) != null)
            {
                pFeaBuffer = target_FeatureClass.CreateFeatureBuffer();
                IGeoDataset pGeoDataset = pFeature.Class as IGeoDataset;
                pFeaBuffer.Shape = pFeature.Shape;
                for (int j = 2; j < CADFeatureClass.Fields.FieldCount; j++)
                {
                    try
                    {
                        pFeaBuffer.set_Value(j, pFeature.Value[CADFeatureClass.FindField(target_FeatureClass.Fields.Field[j].Name)]);
                    }catch
                    {
                        continue;
                    }
                }
                targetCursor.InsertFeature(pFeaBuffer);
                targetCursor.Flush();
            }
        }
Esempio n. 20
0
        private IRasterDataset CopyRasterToWorkspace(IMap map, ILayer layer, IWorkspace wksDst, bool bLayerSpatial)
        {
            if (layer is IRasterLayer)
            {
                IRasterLayer rasterLayer = layer as IRasterLayer;
                if (rasterLayer.Raster == null)
                {
                    return(null);
                }

                IRaster rasterSrc = rasterLayer.Raster;
                //设置空间参考
                ISpatialReference spatialRef;
                if (bLayerSpatial)
                {
                    IGeoDataset pGeo = (IGeoDataset)rasterLayer;
                    spatialRef = pGeo.SpatialReference;
                }
                else
                {
                    spatialRef = map.SpatialReference;
                }

                ClsGDBDataCommon cls = new ClsGDBDataCommon();
                return(cls.ExportRasterToWorkspace(rasterSrc, wksDst, layer.Name, spatialRef));
            }
            return(null);
        }
Esempio n. 21
0
        public IGeoDataset GetIDW(IFeatureClass _pFeatureClass, string _pFieldName, double _pDistance, double _pCell, int _pPower)
        {
            IGeoDataset             Geo              = _pFeatureClass as IGeoDataset;
            object                  pExtent          = Geo.Extent;
            object                  o                = Type.Missing;
            IFeatureClassDescriptor pFeatureClassDes = new FeatureClassDescriptorClass();

            pFeatureClassDes.Create(_pFeatureClass, null, _pFieldName);
            IInterpolationOp           pInterOp    = new RasterInterpolationOpClass();
            IRasterAnalysisEnvironment pRasterAEnv = pInterOp as IRasterAnalysisEnvironment;

            // pRasterAEnv.Mask = Geo;
            pRasterAEnv.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvValue, ref pExtent, ref o);

            object pCellSize = _pCell;//可以根据不同的点图层进行设置

            pRasterAEnv.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, ref pCellSize);

            IRasterRadius pRasterrad = new RasterRadiusClass();
            object        obj        = Type.Missing;

            // pRasterrad.SetFixed(_pDistance, ref obj);
            pRasterrad.SetVariable(12);

            object pBar = Type.Missing;

            IGeoDataset pGeoIDW = pInterOp.IDW(pFeatureClassDes as IGeoDataset, _pPower, pRasterrad, ref pBar);

            return(pGeoIDW);
        }
        /// <summary>
        /// 创建要素
        /// </summary>
        /// <param name="pGeometry"></param>
        private void CreateFeature(IGeometry pGeometry)
        {
            try
            {
                if (m_EngineEditLayers == null)
                {
                    return;
                }
                IFeatureLayer pFeatLyr = m_EngineEditLayers.TargetLayer;
                if (pFeatLyr == null)
                {
                    return;
                }
                IFeatureClass pFeatCls = pFeatLyr.FeatureClass;
                if (pFeatCls == null)
                {
                    return;
                }
                if (m_EngineEditor == null)
                {
                    return;
                }
                if (pGeometry == null)
                {
                    return;
                }
                ITopologicalOperator pTop = pGeometry as ITopologicalOperator;
                pTop.Simplify();
                IGeoDataset pGeoDataset = pFeatCls as IGeoDataset;
                if (pGeoDataset.SpatialReference != null)
                {
                    pGeometry.Project(pGeoDataset.SpatialReference);
                }
                m_EngineEditor.StartOperation();
                IFeature pFeature = null;
                pFeature = pFeatCls.CreateFeature();

                IZAware ipZAware = pGeometry as IZAware;
                if (ipZAware.ZAware == true)
                {
                    ipZAware.ZAware = false;
                }
                if (pGeometry.GeometryType == esriGeometryType.esriGeometryPoint)
                {
                    pFeature.Shape = pGeometry;
                }
                else
                {
                    pFeature.Shape = SupportZMFeatureClass.ModifyGeomtryZMValue(pFeatCls, pGeometry);
                }
                pFeature.Store();
                m_EngineEditor.StopOperation("添加要素");
                m_Map.SelectFeature(pFeatLyr, pFeature);
                m_activeView.Refresh();
            }
            catch (Exception ex)
            {
                //SysLogHelper.WriteOperationLog("要素添加错误", ex.Source, "数据编辑");
            }
        }
Esempio n. 23
0
        /// <summary>
        /// 创建TIN
        /// </summary>
        private void CreateDelaunay()
        {
            //创建TIN
            IFeatureLayer featureLayer = m_dataInfo.GetInputLayer() as IFeatureLayer;
            IFeatureClass featureClass = featureLayer.FeatureClass;
            IField        pField       = featureClass.Fields.get_Field(0);

            if (pField == null)
            {
                MessageBox.Show("创建Delaunay三角网失败");
                return;
            }

            IGeoDataset pGeoDataset = featureClass as IGeoDataset;
            IEnvelope   pEnvelope   = pGeoDataset.Extent;

            pEnvelope.SpatialReference = pGeoDataset.SpatialReference;

            ITinEdit pTinEdit = new TinClass();

            pTinEdit.InitNew(pEnvelope);
            object obj = Type.Missing;

            pTinEdit.AddFromFeatureClass(featureClass, null, pField, null, esriTinSurfaceType.esriTinMassPoint, ref obj);
            m_DT = pTinEdit as ITin;

            //将所有点标识为噪声点
            ITinAdvanced tinAdvanced = m_DT as ITinAdvanced;

            for (int i = 0; i < tinAdvanced.NodeCount; i++)
            {
                m_nodeFlag.Add(-1);
            }
        }
Esempio n. 24
0
        public static bool ValideFeatureClass(IGeoDataset igeoDataset_0)
        {
            IEnvelope extent = igeoDataset_0.Extent;
            bool      result;

            if (extent.IsEmpty)
            {
                result = true;
            }
            else
            {
                if (igeoDataset_0 is IFeatureClass)
                {
                    if (!CommonHelper.FeatureClassHasData(igeoDataset_0 as IFeatureClass))
                    {
                        result = true;
                        return(result);
                    }
                }
                else if (igeoDataset_0 is IFeatureLayer && !CommonHelper.LayerHasData(igeoDataset_0 as IFeatureLayer))
                {
                    result = true;
                    return(result);
                }
                ISpatialReference spatialReference = igeoDataset_0.SpatialReference;
                if (spatialReference is IProjectedCoordinateSystem)
                {
                    double falseEasting  = (spatialReference as IProjectedCoordinateSystem).FalseEasting;
                    double falseNorthing = (spatialReference as IProjectedCoordinateSystem).FalseNorthing;
                    if (falseEasting > 0.0 && extent.XMin < falseEasting - 500000.0)
                    {
                        result = false;
                        return(result);
                    }
                    ILinearUnit coordinateUnit = (spatialReference as IProjectedCoordinateSystem).CoordinateUnit;
                    double      num            = -10001858.0 / coordinateUnit.MetersPerUnit + falseNorthing;
                    double      num2           = 10001858.0 / coordinateUnit.MetersPerUnit + falseNorthing;
                    if (extent.YMin < num || extent.YMax > num2)
                    {
                        result = false;
                        return(result);
                    }
                }
                else if (spatialReference is IGeographicCoordinateSystem)
                {
                    if (extent.XMin < -360.0 || extent.XMax > 360.0)
                    {
                        result = false;
                        return(result);
                    }
                    if (extent.YMin < -100.0 || extent.YMax > 100.0)
                    {
                        result = false;
                        return(result);
                    }
                }
                result = true;
            }
            return(result);
        }
Esempio n. 25
0
        private void Progarm()
        {
            IWorkspace workspace = ArcClass.GetmdbWorkspace(mdbFilePath);

            if (workspace == null)
            {
                return;
            }
            IFeatureDataset featureDataset = ArcClass.GetFeatureDataset(workspace, "WJL");
            ISchemaLock     schemalock     = featureDataset as ISchemaLock;

            try
            {
                schemalock.ChangeSchemaLock(esriSchemaLock.esriExclusiveSchemaLock);
                ITopologyContainer topologyContainer = featureDataset as ITopologyContainer;
                ITopology          topology          = topologyContainer.CreateTopology("ttt", topologyContainer.DefaultClusterTolerance, -1, "");
                IFeatureClass      featureClass      = ArcClass.GetFeatureClass(workspace, "PARK");

                AddRuleToTopology(topology, esriTopologyRuleType.esriTRTAreaNoOverlap, "NO Block OverLap", featureClass);

                IGeoDataset geoDataset = topology as IGeoDataset;
                IEnvelope   envelop    = geoDataset.Extent;
                ValidateTopology(topology, envelop);
            }catch (COMException)
            {
            }
        }
Esempio n. 26
0
        public NetworkDataset(string configXML, IDataset osmDataset, string ndsName, IGPMessages messages, ITrackCancel trackCancel)
        {
            _xml = new NetworkDatasetXML(configXML, RESMGR);

            _osmDataset  = osmDataset;
            _ndsName     = ndsName;
            _messages    = messages;
            _trackCancel = trackCancel;

            IDataElement deOSM = GPUtil.MakeDataElementFromNameObject(_osmDataset.FullName);

            _dsPath = deOSM.CatalogPath;

            _osmLineName  = _osmDataset.Name + "_osm_ln";
            _osmLinePath  = _dsPath + "\\" + _osmLineName;
            _osmPointName = _osmDataset.Name + "_osm_pt";
            _osmPointPath = _dsPath + "\\" + _osmPointName;

            // Get the extent from the point feature class
            // NOTE: the feature dataset is not used for this because exceptions occur (SDE only)
            //       if a feature class was recently deleted from the feature dataset.
            IFeatureClass fcPoint = ((IFeatureWorkspace)_osmDataset.Workspace).OpenFeatureClass(_osmPointName);
            IGeoDataset   gds     = (IGeoDataset)fcPoint;

            _extent           = gds.Extent;
            _spatialReference = gds.SpatialReference;
        }
Esempio n. 27
0
        /// <summary>
        /// 转换
        /// </summary>
        /// <param name="pFeatureClass">要素类</param>
        /// <param name="fieldName">栅格采用的字段</param>
        /// <param name="rasterWorkSpace">输出栅格的工作空间</param>
        /// <param name="newRasterName">新的栅格名称</param>
        public void Convert(IFeatureClass pFeatureClass,
                            string fieldName,
                            string rasterWorkSpace,
                            string newRasterName)
        {
            FileHelper.DeleteFile(rasterWorkSpace, newRasterName, ".tif", ".tfw", ".tif.aux");
            IFeatureClassDescriptor featureClassDescriptor = new FeatureClassDescriptorClass();

            featureClassDescriptor.Create(pFeatureClass, null, fieldName);
            IGeoDataset                geoDataset                = (IGeoDataset)featureClassDescriptor;
            IWorkspaceFactory          workspaceFactory          = new RasterWorkspaceFactoryClass();
            IWorkspace                 workspace                 = workspaceFactory.OpenFromFile(rasterWorkSpace, 0);
            IConversionOp              conversionOp              = new RasterConversionOpClass();
            IRasterAnalysisEnvironment rasterAnalysisEnvironment = (IRasterAnalysisEnvironment)conversionOp;

            rasterAnalysisEnvironment.OutWorkspace = workspace;


            //set cell size
            rasterAnalysisEnvironment.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, ref _cellSize);
            //set output extent
            object objectMissing = Type.Missing;

            rasterAnalysisEnvironment.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvValue, ref _extentEnvelope, ref objectMissing);
            //set output spatial reference
            rasterAnalysisEnvironment.OutSpatialReference = ((IGeoDataset)pFeatureClass).SpatialReference;
            //convertion
            conversionOp.ToRasterDataset(geoDataset, _rasterType, workspace, newRasterName);
        }
Esempio n. 28
0
        private void btnImport_Click(object sender, EventArgs e)
        {
            frmOpenFile file = new frmOpenFile();

            file.AddFilter(new MyGxFilterDatasets(), true);
            file.AllowMultiSelect = false;
            if (file.ShowDialog() == DialogResult.OK)
            {
                IGxDataset dataset = file.Items.get_Element(0) as IGxDataset;
                if (dataset != null)
                {
                    IGeoDataset dataset2 = dataset.Dataset as IGeoDataset;
                    if (dataset2 != null)
                    {
                        this.ispatialReference_0 = dataset2.SpatialReference;
                        TreeNode node = new TreeNode(this.ispatialReference_0.Name, 2, 2)
                        {
                            Tag = this.ispatialReference_0
                        };
                        this.treeNode_0.Nodes.Add(node);
                        this.method_4(this.ispatialReference_0);
                        this.method_6();
                    }
                }
            }
        }
Esempio n. 29
0
        private void CreateDEM()
        {
            IWorkspaceFactory pWsF    = new AccessWorkspaceFactory();
            IFeatureWorkspace pWs     = pWsF.OpenFromFile(textEdit1.Text, 0) as IFeatureWorkspace;
            IFeatureDataset   pFDs    = pWs.OpenFeatureDataset("GCD");
            IFeatureClass     pFc     = pFDs as IFeatureClass;
            double            power   = 1;
            object            Missing = Type.Missing;


            IFields pFields = pFc.Fields;
            int     index   = pFields.FindFieldByAliasName("高程");
            string  z       = pFields.get_Field(index).Name;


            IFeatureClassDescriptor feaDes = new FeatureClassDescriptorClass();

            feaDes.Create(pFc, null, z);
            IGeoDataset inGeoDs = feaDes as IGeoDataset;

            IRasterAnalysisEnvironment rasterEnv = new RasterInterpolationOpClass();
            double cellSize    = 20;
            object cellSizeObj = cellSize;

            rasterEnv.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, ref cellSizeObj);

            IRasterRadius radius = new RasterRadiusClass();

            radius.SetVariable(12, Missing);

            IInterpolationOp2 interOp  = rasterEnv as IInterpolationOp2;
            IGeoDataset       outGeoDs = interOp.IDW(inGeoDs, power, radius, ref Missing);

            pWs = pWsF.OpenFromFile(textEdit2.Text, 0) as IFeatureWorkspace;
        }
Esempio n. 30
0
        //缩放至图层
        private void ctMenuTFZoomToLayer_Click(object sender, EventArgs e)
        {
            IGeoDataset pGeoDataset = null;

            if (this.TOCRightLayer is IFeatureLayer)
            {
                IFeatureClass pFeatureClass = ((IFeatureLayer)this.TOCRightLayer).FeatureClass;
                pGeoDataset = pFeatureClass as IGeoDataset;
            }
            else if (this.TOCRightLayer is IRasterLayer)
            {
                IRasterLayer pRaterLayer = this.TOCRightLayer as IRasterLayer;
                pGeoDataset = pRaterLayer.Raster as IGeoDataset;
            }
            else if (this.TOCRightLayer is ITinLayer)
            {
                ITinLayer pTinLayer = this.TOCRightLayer as ITinLayer;
                pGeoDataset = pTinLayer.Dataset as IGeoDataset;
            }
            else
            {
                return;
            }
            this.axMapControl1.Extent = pGeoDataset.Extent;
            this.axMapControl1.Refresh();
        }
Esempio n. 31
0
 public ExtractionLayerConfig(int id,string LayerName,string LayerDescription,
     ExtractionTypes extractiontype, string paramname,
     int CategoryFieldId,int ValueFieldId, int MeasureFieldId, IGeoDataset GeoDataset)
 {
     this.m_layerID = id;
     this.m_layerName = LayerName;
     this.m_layerDescription = LayerDescription;
     this.m_extractionType = extractiontype;
     this.m_paramName = paramname;
     this.m_categoryField = CategoryFieldId;
     this.m_valueField = ValueFieldId;
     this.m_measureField = MeasureFieldId;
     this.m_LayerData = GeoDataset;
 }
Esempio n. 32
0
        /// <summary>
        /// add raster or featureclass to map as layer
        /// </summary>
        public static void AddDataToMapAsLayer(IGeoDataset RasterDSOrFeatureClass, string LayerName)
        {
            ILayer ThisLayer = null;

            if (RasterDSOrFeatureClass is IRasterDataset)
            {
                //add rasterdataset as raster layer
                ThisLayer = new RasterLayerClass() as ILayer;
                ((IRasterLayer)ThisLayer).CreateFromDataset(RasterDSOrFeatureClass as IRasterDataset);
            }

            if (RasterDSOrFeatureClass is IFeatureClass)
            {
                //add feature class to a feature layer
                ThisLayer = new FeatureLayerClass() as ILayer;
                ((IFeatureLayer)ThisLayer).FeatureClass = RasterDSOrFeatureClass as IFeatureClass;
            }

            ThisLayer.Name = LayerName;

            //Add the raster layer to ArcMap
            NPSGlobal.Instance.Document.FocusMap.AddLayer(ThisLayer);
            NPSGlobal.Instance.Document.ActiveView.Refresh();
        }
Esempio n. 33
0
        /// <summary>
        /// create a transect from a source point
        /// </summary>
        public static IPolyline CreateTransPolylineFromRandPoint(IPoint RandPoint, double MaxLineLength, double MinLineLength,
            IFeatureClass BndPolyFC, IFeatureClass ExclPolyFC, IFeatureClass FlatAreasPolyFC, int SurveyID, IGeoDataset npsDemDataset,
            int TransCreateAttempts, ref string TranType, ref string ErrorMessage)
        {
            bool IsInExcludedAreas, IsInBndPoly;
            IPointCollection NewLine = null, NewLine2 = null, pPolyline = null;
            IPoint npsToPoint;
            IPolyline npsGetPoint;
            double DrawnAngle = -1;
            object Missing = Type.Missing;
            TranType = "";

            //generate the first line in the transect
            NewLine = Util.TryCreateTransectSide(RandPoint, SurveyID, ref DrawnAngle, FlatAreasPolyFC,
                ExclPolyFC, BndPolyFC, MaxLineLength, MinLineLength, TransCreateAttempts) as IPointCollection;

            if (NewLine != null)
            {
                //generate the second line in the transect
                NewLine2 = Util.TryCreateTransectSide(RandPoint, SurveyID, ref DrawnAngle, FlatAreasPolyFC,
                    ExclPolyFC, BndPolyFC, MaxLineLength, MinLineLength, TransCreateAttempts) as IPointCollection;
            }

            //if we have both lines in the transect, create transect
            if (NewLine != null && NewLine2 != null)
            {

                pPolyline = new PolylineClass();
                npsToPoint = new PointClass();

                npsGetPoint = NewLine as IPolyline;
                npsGetPoint.QueryToPoint(npsToPoint);
                pPolyline.AddPoint(npsToPoint, ref Missing, ref Missing);

                pPolyline.AddPoint(RandPoint, ref Missing, ref Missing);

                npsGetPoint = NewLine2 as IPolyline;
                npsGetPoint.QueryToPoint(npsToPoint);
                pPolyline.AddPoint(npsToPoint, ref Missing, ref Missing);

                TranType = "straight";
            }

            //if transects could not be drawn (pPolyline is still nothing), get contour instead
            if (pPolyline == null)
            {

                //try to create a contour since straight lines failed
                pPolyline = Util.GetContourLineFromPoint(RandPoint, MaxLineLength, MinLineLength, npsDemDataset,
                    SurveyID, BndPolyFC, ExclPolyFC) as IPointCollection;

                if (pPolyline != null)
                {

                    //check if contour is within boundary
                    IsInBndPoly = Util.HasRelationshipWithFC(pPolyline as IGeometry, esriSpatialRelEnum.esriSpatialRelWithin,
                     BndPolyFC, "SurveyID=" + SurveyID);

                    //check if contour falls in excluded areas
                    IsInExcludedAreas = Util.HasRelationshipWithFC(pPolyline as IGeometry, esriSpatialRelEnum.esriSpatialRelCrosses,
                     ExclPolyFC, "SurveyID=" + SurveyID);

                    //if contour obtained falls in excluded areas, abandon poyline
                    if (IsInBndPoly == false || IsInExcludedAreas == true) pPolyline = null;

                }

                if (pPolyline != null) TranType = "contour";

            }

            GC.Collect();

            return pPolyline as IPolyline;
        }
Esempio n. 34
0
        public static void AddZValuesToPoints(int SurveyID, int NewBatchID, int TempBatchID,
            IGeoDataset ThisRasterDS, string ThisDEMUnits, ref string ErrorMessage)
        {
            ESRI.ArcGIS.Geoprocessing.IGeoProcessorResult GeoResult = null;
            ESRI.ArcGIS.Geoprocessing.IGeoProcessor ThisGeoProcessor = null;
            ESRI.ArcGIS.esriSystem.IVariantArray GPParams;
            IFeatureClass TempFCHolderFC = null, PointFC = null;
            string CopyRandFilter = "", TempElePoints, TempFCHolder, InternalError = "";
            NPSGlobal NPS;
            int GPLIndex = 0;

            NPS = NPSGlobal.Instance;
            TempFCHolder = "TempFCHolder";
            TempElePoints = "TempElePoints";

            ThisDEMUnits = ThisDEMUnits.ToLower();

            if (string.IsNullOrEmpty(ErrorMessage))
                PointFC = Util.GetFeatureClass(NPS.LYR_RANDOMPOINTS, ref ErrorMessage);

            if (string.IsNullOrEmpty(ErrorMessage) == false)
            {
                Util.SetProgressMessage("Deleting old temp files");

                //delete the temporary table if it already exists
                Util.DeleteDataset(TempElePoints, esriDatasetType.esriDTFeatureClass, ref InternalError);
                Util.DeleteDataset(TempElePoints + "_Tbl", esriDatasetType.esriDTTable, ref InternalError);
                Util.DeleteDataset(TempFCHolder, esriDatasetType.esriDTFeatureClass, ref InternalError);
                Util.DeleteDataset(TempFCHolder + "_Tbl", esriDatasetType.esriDTTable, ref InternalError);
            }

            if (string.IsNullOrEmpty(ErrorMessage))
            {
                try
                {
                    Util.SetProgressMessage("Copying random points to temp FeatureClass");

                    ThisGeoProcessor = new ESRI.ArcGIS.Geoprocessing.GeoProcessor();
                    GPParams = new ESRI.ArcGIS.esriSystem.VarArrayClass();

                    GPParams.Add(NPS.Workspace.PathName);
                    GPParams.Add(TempFCHolder);
                    GPParams.Add("POINT");
                    GPParams.Add(System.IO.Path.Combine(NPS.Workspace.PathName, ((IDataset)PointFC).Name));

                    GeoResult = ThisGeoProcessor.Execute("CreateFeatureClass_management", GPParams, null);
                }
                catch (Exception ex)
                {
                    ErrorMessage = string.Format("Geoprocessor error:\r\nTask:CreateFeatureClass_management\r\n"
                        + "Params:{0},{1},{2},{3}\r\nException:{4}", NPS.Workspace.PathName, TempFCHolder, "POINT",
                        System.IO.Path.Combine(NPS.Workspace.PathName, ((IDataset)PointFC).Name), ex.Message);
                }

                ThisGeoProcessor = null;
                Util.DeleteLayerFromMap(TempFCHolder);
            }

            if (string.IsNullOrEmpty(ErrorMessage))
            {
                CopyRandFilter = " SurveyID=" + SurveyID;
                if (TempBatchID != -1) CopyRandFilter += " And BATCH_ID=" + TempBatchID;

                //get the temp feature class and copy only surveyid points to it
                TempFCHolderFC = Util.GetFeatureClass(TempFCHolder, ref ErrorMessage);

                if (string.IsNullOrEmpty(ErrorMessage))
                    Util.CopyFeatures(PointFC, CopyRandFilter, TempFCHolderFC, null, ref ErrorMessage);

                int TestCount = FeatureCount(TempFCHolderFC, "");

            }

            if (string.IsNullOrEmpty(ErrorMessage))
            {
                try
                {
                    Util.SetProgressMessage("Extracting point elevation from DEM");

                    ThisGeoProcessor = new ESRI.ArcGIS.Geoprocessing.GeoProcessor();
                    GPParams = new ESRI.ArcGIS.esriSystem.VarArrayClass();

                    //GPParams.Add(TempFCHolderFC);
                    //GPParams.Add(ThisRasterDS);
                    //GPParams.Add(System.IO.Path.Combine(NPS.Workspace.PathName, TempElePoints));
                    //GeoResult = ThisGeoProcessor.Execute("ExtractValuesToPoints_sa", GPParams, null);

                    GPParams.Add(ThisRasterDS);
                    GPParams.Add(TempFCHolderFC);
                    GPParams.Add("Spot");   // field name to add
                    GPParams.Add(1);  // Z-Factor
                    GeoResult = ThisGeoProcessor.Execute("SurfaceSpot_3D", GPParams, null);
                }
                catch (Exception ex)
                {
                    ErrorMessage = string.Format("Geoprocessor error:\r\nTask:SurfaceSpot_3D\r\n"
                        + "Params:{0},{1},{2},{3}\r\nException:{4}", ((IDataset)ThisRasterDS).Name,
                        ((IDataset)TempFCHolderFC).Name, "Spot", 1, ex.Message);

                }

                ThisGeoProcessor = null;

                //delete GPL[index] layers created from SurfaceSpot geoprocessor call
                while (GPLIndex < 10)
                {
                    Util.DeleteLayerFromMap("GPL" + GPLIndex);
                    GPLIndex++;
                }
            }

            if (string.IsNullOrEmpty(ErrorMessage))
            {
                Util.SetProgressMessage("Importing updated random points");

                //delete all points for that survey
                Util.DeleteFeatures(PointFC, CopyRandFilter, ref ErrorMessage);

                //replace the points of that survey with these points
                Util.CopyFeaturesForPoints(TempFCHolderFC, "", PointFC, NewBatchID, ThisDEMUnits, ref ErrorMessage);
            }

            Util.SetProgressMessage("Cleaning up temp files");
            Util.DeleteDataset(TempElePoints, esriDatasetType.esriDTFeatureClass, ref InternalError);
            Util.DeleteDataset(TempElePoints + "_Tbl", esriDatasetType.esriDTTable, ref InternalError);
            Util.DeleteDataset(TempFCHolder, esriDatasetType.esriDTFeatureClass, ref InternalError);
            Util.DeleteDataset(TempFCHolder + "_Tbl", esriDatasetType.esriDTTable, ref InternalError);
        }
Esempio n. 35
0
 internal ExtractionResultCollection(string SearchId, IGeoDataset ClippingFeature,
     List<RasterExtractionResult> RasterResults,
     List<FeatureExtractionResult> FeatureResults
     )
 {
     this.m_searchId = SearchId;
     this.m_ClippingFeature = ClippingFeature;
     this.m_RasterResults = RasterResults;
     this.m_FeatureResults = FeatureResults;
     this.m_fieldsAdded = false;
     this.m_jsonBuilt = false;
     this.m_ResultsJson = new JsonObject();
 }
Esempio n. 36
0
        public void Construct(IPropertySet props)
        {
            try
            {
                logger.LogMessage(ServerLogger.msgType.infoDetailed, "Construct", 8000, "Watershed SOE constructor running");
                object tProperty = null;
                m_CanDoWatershed = true;
                // IPropertySet doesn't have anything like a trygetvalue method
                // so if we don't know if a property will be present we have to just try getting
                // it and if there is an exception assumes it wasn't there
                try {
                    tProperty = props.GetProperty("FlowAccLayer");
                    if (tProperty as string == "None")
                    {
                        logger.LogMessage(ServerLogger.msgType.infoStandard, "Construct", 8000, "WSH: Flow accumulation layer set to 'None'. No watershed functionality.");
                        m_CanDoWatershed = false;
                        //throw new ArgumentNullException();
                    }
                    else
                    {
                        m_FlowAccLayerName = tProperty as string;
                        logger.LogMessage(ServerLogger.msgType.infoStandard, "Construct", 8000, "WSH: found definition for Flow Accumulation layer: " + m_FlowAccLayerName);
                    }
                }
                catch{
                    logger.LogMessage(ServerLogger.msgType.infoStandard, "Construct", 8000, "WSH: Flow accumulation layer not set. No watershed functionality.");
                    m_CanDoWatershed = false;
                    //throw new ArgumentNullException();
                }
                try {
                    tProperty = props.GetProperty("FlowDirLayer");
                    if (tProperty as string == "None")
                    {
                        logger.LogMessage(ServerLogger.msgType.infoStandard, "Construct", 8000, "WSH: Flow direction layer set to 'None'. No watershed functionality.");
                        m_CanDoWatershed = false;
                    }
                    else
                    {
                        m_FlowDirLayerName = tProperty as string;
                        logger.LogMessage(ServerLogger.msgType.infoStandard, "Construct", 8000, "WSH: found definition for Flow direction layer: " + m_FlowDirLayerName);
                    }
                }
                catch {
                    logger.LogMessage(ServerLogger.msgType.infoStandard, "Construct", 8000, "WSH: Flow direction layer not set. No watershed functionality.");
                    m_CanDoWatershed = false;
                }
                try
                {
                    tProperty = props.GetProperty("ExtentFeatureLayer") as string;
                    if (tProperty as string =="None"){
                        logger.LogMessage(ServerLogger.msgType.debug, "Construct", 8000,
                            "WSH: No extent features configured. Extent may still be passed as input");
                    }
                    else
                    {
                        m_ExtentFeatureLayerName = tProperty as string;
                        logger.LogMessage(ServerLogger.msgType.infoStandard, "Construct", 8000, "WSH: found definition for Extent Feature layer: " + m_ExtentFeatureLayerName);
                    }
                }
                catch {
                    logger.LogMessage(ServerLogger.msgType.infoStandard, "Construct", 8000, "WSH: no definition for extent feature layers found. Extent may still be passed as input");
                }

                try
                {
                    tProperty = props.GetProperty("ReadConfigFromMap");
                    if (tProperty == null || tProperty as string != "False")
                    {
                        m_BuildLayerParamsFromMap = true;
                        logger.LogMessage(ServerLogger.msgType.infoStandard, "Construct", 8000, "WSH: layer parameters will be built from map document layers");
                    }

                    else
                    {
                        m_BuildLayerParamsFromMap = false;
                        logger.LogMessage(ServerLogger.msgType.infoStandard, "Construct", 8000, "WSH: layer parameters would be read from properties file but this is NOT IMPLEMENTED YET ");
                        // TODO: add code to read in LayerConfiguration parameter and parse it
                    }
                }
                catch
                {
                    m_BuildLayerParamsFromMap = true;
                    logger.LogMessage(ServerLogger.msgType.debug, "Construct", 8000,
                        "WSH: no property found for ReadConfigFromMap; "+
                        "layer parameters will be built from map document layers");
                }
            }
            catch (Exception e)
            {
                logger.LogMessage(ServerLogger.msgType.infoStandard, "Construct", 8000, "WSH: Properties constructor threw an exception");
                logger.LogMessage(ServerLogger.msgType.infoStandard, "Construct", 8000, e.Message);
                logger.LogMessage(ServerLogger.msgType.infoStandard, "Construct", 8000, e.ToString());
                logger.LogMessage(ServerLogger.msgType.infoStandard, "Construct", 8000, e.TargetSite.Name);
                logger.LogMessage(ServerLogger.msgType.infoStandard, "Construct", 8000, e.StackTrace);
            }

            try
            {
                // get the datasets associated with the configured inputs to watershed delineation.
                // Also note the other layers: we will make all others available for extraction
                // but need to note the data type and how the layer name should translate into a REST operation
                // parameter. This information will be stored in an ExtractionLayerConfig opbject for each layer
                // We only need to do this at startup not each time
                IMapServer3 mapServer = (IMapServer3)serverObjectHelper.ServerObject;
                string mapName = mapServer.DefaultMapName;
                IMapLayerInfo layerInfo;
                IMapLayerInfos layerInfos = mapServer.GetServerInfo(mapName).MapLayerInfos;
                ILayerDescriptions layerDescriptions = mapServer.GetServerInfo(mapName).DefaultMapDescription.LayerDescriptions;
                IMapServerDataAccess dataAccess = (IMapServerDataAccess)mapServer;

                int c = layerInfos.Count;
                int acc_layerIndex=0;
                int dir_layerIndex=0;
                int ext_layerIndex=0;
                //Dictionary<int,string> other_layerIndices = new Dictionary<int,string>();
                List<string> tAllParams = new List<string>();
                for (int i=0;i<c;i++)
                {
                    layerInfo = layerInfos.get_Element(i);
                    if(m_CanDoWatershed && layerInfo.Name == m_FlowAccLayerName)
                    {
                        acc_layerIndex = i;
                    }
                    else if (m_CanDoWatershed && layerInfo.Name == m_FlowDirLayerName)
                    {
                        dir_layerIndex = i;
                    }
                    else if (m_CanDoWatershed && m_ExtentFeatureLayerName != null && layerInfo.Name == m_ExtentFeatureLayerName)
                    {
                        ext_layerIndex = i;
                    }
                    else if (m_BuildLayerParamsFromMap)
                    // note the else if is deliberately arranged so that layers used for watershed extraction
                    // won't be exposed as extractable
                    {
                        // Types appear to be "Raster Layer", "Feature Layer", and "Group Layer"
                        logger.LogMessage(ServerLogger.msgType.debug,
                            "Construct", 8000,
                            "WSH: processing extractable map layer " + layerInfo.Name + " at ID " +
                            layerInfo.ID + " of type " + layerInfo.Type);

                        if (layerInfo.Type == "Raster Layer" || layerInfo.Type == "Feature Layer")
                        {
                            string tName = layerInfo.Name;
                            string tDesc = layerInfo.Description;
                            if (tName.IndexOf(':') == -1 && tDesc.IndexOf(':') == -1)
                            {
                                // fail if any of the map layers except the ones used for the catchment definition
                                // don't have a name or description starting with 6 or less characters followed by :
                                logger.LogMessage(ServerLogger.msgType.error, "Construct", 8000,
                                     " Watershed SOE warning: could determine output parameter string for layer " + tName +
                                     " and it will not be available for extraction. " +
                                     " Ensure that either the layer name or description starts with an ID for the " +
                                     " service parameter name to be exposed, max 6 characters and separated by ':'" +
                                     " e.g. 'LCM2K:Land Cover Map 2000'");
                                continue;
                            }
                            else if (tName.IndexOf(':') > 5 && tDesc.IndexOf(':') > 5)
                            {
                                logger.LogMessage(ServerLogger.msgType.error, "Construct", 8000,
                                     " Watershed SOE warning: read output parameter string for layer " + tName +
                                     " but it was too long." +
                                     " Ensure that either the layer name or description starts with an ID for the " +
                                     " service parameter name to be exposed, max 6 characters and separated by ':'" +
                                     " e.g. 'LCM2K:Land Cover Map 2000'. Layer will not be available for extraction.");
                                continue;
                            }
                            string tParamName;
                            string tProcessedName;
                            if (tName.IndexOf(':') != -1)
                            {
                                tParamName = tName.Substring(0, tName.IndexOf(':'));
                                tProcessedName = tName.Substring(tName.IndexOf(':')+1).Trim();
                            }
                            else
                            {
                                tParamName = tDesc.Substring(0, tDesc.IndexOf(':'));
                                tProcessedName = tName.Trim();
                            }
                            if (tAllParams.Contains(tParamName))
                            {
                                logger.LogMessage(ServerLogger.msgType.error,"Construct",800,
                                    "Watershed SOE warning: duplicate parameter name found for layer "+tName +
                                    "(parameter "+tParamName+" is set on another map layer). Layer will not be available"+
                                    " for extraction.");
                                continue;
                            }
                            else{
                                tAllParams.Add(tParamName);
                            }
                            string tDescription = "";
                            if (layerInfo.Description.Length > 0)
                            {
                                if (layerInfo.Description.IndexOf(':') == -1)
                                {
                                    tDescription = layerInfo.Description.Trim();
                                }
                                else if (layerInfo.Description.IndexOf(':') < 6)
                                {
                                    tDescription = layerInfo.Description.Substring(layerInfo.Description.IndexOf(':') + 1).Trim();
                                }
                                else
                                {
                                    tDescription = layerInfo.Description.Trim();
                                }
                            }

                            ExtractionTypes tExtractionType = ExtractionTypes.Ignore;
                            if (layerInfo.Type == "Raster Layer")
                            {
                                // determine whether we will summarise the raster layer "categorically"
                                // i.e. a count of each value, or "continuously" i.e. min/max/avg statistics
                                // based on how the raster is symbolised in the map and whether or not
                                // it is of integer type

                                // TODO : Also store the labels for classes in categorical rasters
                                // so that these can be returned by the SOE to the client
                                // Cast the renderer to ILegendInfo, get ILegendGroup from it and each
                                // ILegendClass from that to get the string Label

                                // Get renderer
                                // THIS ONLY WORKS WITH MXD SERVICES: WE CANNOT DO THIS ON AN MSD BASED SERVICE
                                IMapServerObjects3 tMapServerObjects = mapServer as IMapServerObjects3;
                                ILayer tLayer = tMapServerObjects.get_Layer(mapName, i);
                                IRasterLayer tRasterLayer = (IRasterLayer)tLayer;
                                IRasterRenderer tRasterRenderer = tRasterLayer.Renderer;
                                // Get raster data
                                IRaster tRaster = dataAccess.GetDataSource(mapName, i) as IRaster;
                                IRasterProps tRasterProps = tRaster as IRasterProps;
                                IGeoDataset tRasterGDS = tRaster as IGeoDataset;

                                bool tTreatAsCategorical = false;
                                if (tRasterRenderer is RasterUniqueValueRenderer)
                                {
                                    logger.LogMessage(ServerLogger.msgType.debug, "Construct", 800,
                                   "Raster layer " + tName +
                                   "is symbolised by unique values - treating layer as categorical");
                                    tTreatAsCategorical = tRasterProps.IsInteger;
                                }
                                else if (tRasterRenderer is RasterDiscreteColorRenderer)
                                {
                                    logger.LogMessage(ServerLogger.msgType.debug, "Construct", 800,
                                   "Raster layer " + tName +
                                   "is symbolised by discrete colours - treating layer as categorical");
                                    tTreatAsCategorical = tRasterProps.IsInteger;
                                }
                                else if (tRasterRenderer is RasterClassifyColorRampRenderer)
                                {
                                    // TODO - treat a classified colour ramp as categorical but categories
                                    // determined by classes rather than unique values... needs the summary
                                    // method to have access to the class breaks
                                    logger.LogMessage(ServerLogger.msgType.debug, "Construct", 800,
                                   "Raster layer " + tName +
                                   "is symbolised by classified groups - treating layer as continuous");
                                }
                                else if (tRasterRenderer is RasterStretchColorRampRenderer)
                                {
                                    logger.LogMessage(ServerLogger.msgType.debug, "Construct", 800,
                                   "Raster layer " + tName +
                                   "is symbolised by colour stretch - treating layer as continuous");
                                }
                                else
                                {
                                    logger.LogMessage(ServerLogger.msgType.debug, "Construct", 800,
                                   "Raster layer " + tName +
                                   "is symbolised with unsupported renderer - treating as continuous");
                                }
                                tExtractionType = tTreatAsCategorical?
                                    ExtractionTypes.CategoricalRaster:
                                    ExtractionTypes.ContinuousRaster;
                                ExtractionLayerConfig tLayerInfo = new ExtractionLayerConfig
                                    (i, tProcessedName,tDescription,tExtractionType, tParamName, -1, -1, -1,tRasterGDS);
                                m_ExtractableParams.Add(tLayerInfo);
                            }
                            else
                            {
                                // Feature class layer
                                // TODO - Get the category / values from the symbology (renderer) as for rasters

                                IFeatureClass tFC = dataAccess.GetDataSource(mapName, i) as IFeatureClass;
                                IGeoDataset tFeatureGDS = tFC as IGeoDataset;
                                esriGeometryType tFCType = tFC.ShapeType;
                                if (tFCType == esriGeometryType.esriGeometryPoint || tFCType == esriGeometryType.esriGeometryMultipoint)
                                {
                                    tExtractionType = ExtractionTypes.PointFeatures;
                                }
                                else if (tFCType == esriGeometryType.esriGeometryPolyline || tFCType == esriGeometryType.esriGeometryLine)
                                {
                                    tExtractionType = ExtractionTypes.LineFeatures;
                                }
                                else if (tFCType == esriGeometryType.esriGeometryPolygon)
                                {
                                    tExtractionType = ExtractionTypes.PolygonFeatures;
                                }
                                int tCategoryField = layerInfo.Fields.FindFieldByAliasName("CATEGORY");
                                int tValueField = layerInfo.Fields.FindFieldByAliasName("VALUE");
                                int tMeasureField = layerInfo.Fields.FindFieldByAliasName("MEASURE");
                                ExtractionLayerConfig tLayerInfo = new ExtractionLayerConfig
                                    (i,tProcessedName,tDescription, tExtractionType, tParamName, tCategoryField, tValueField, tMeasureField,tFeatureGDS);
                                m_ExtractableParams.Add(tLayerInfo);
                                // layers with any other geometry type will be ignored
                            }
                        }
                    }
                    else
                    {
                        logger.LogMessage(ServerLogger.msgType.infoStandard, "Construct", 8000,
                            "WSH: Code to build layer params from properties is not implemented. No extractable"+
                            "params will be available.");
                    }
                }
                IRaster tFDR = dataAccess.GetDataSource(mapName,dir_layerIndex) as IRaster;
                m_FlowDirDataset =  tFDR as IGeoDataset;
                IRaster tFAR = dataAccess.GetDataSource(mapName,acc_layerIndex) as IRaster;
                m_FlowAccDataset = tFAR as IGeoDataset;
                if(m_FlowDirDataset == null || m_FlowAccDataset == null)
                {
                    logger.LogMessage(ServerLogger.msgType.error,"Construct", 8000,"Watershed SOE Error: layer not found");
                    m_CanDoWatershed = false;
                   // return;
                }
                else
                {
                    m_CanDoWatershed = true;
                }
                if (ext_layerIndex != 0)
                {
                    m_ExtentFeatureDataset = dataAccess.GetDataSource(mapName, ext_layerIndex) as IGeoDataset;
                }
            }
            catch (Exception e)
            {
                logger.LogMessage(ServerLogger.msgType.error,"Construct",8000,"Watershed SOE error: could not get the datasets associated with configured map layers."+
                    "Exception: "+e.Message+e.Source+e.StackTrace+e.TargetSite);
            }
            try
            {
                reqHandler = new SoeRestImpl(soe_name, CreateRestSchema()) as IRESTRequestHandler;
            }
            catch (Exception e)
            {
                logger.LogMessage(ServerLogger.msgType.error, "Construct", 8000, "WSH: could not create REST schema. Exception: "+e.Message+ " "+e.Source+" "+e.StackTrace+" "+e.TargetSite);

            }
        }
Esempio n. 37
0
        private IGeoDataset ConvertAndUnionWatershed(IGeoDataset tWatershedGDS)
        {
            //Convert the raster IGeodataset into a Polygon IFeatureClass, in a memory-workspace
            IWorkspace inMemFeatWksp = CreateInMemoryWorkspace();
            //IWorkspaceFactory pWSF = new ShapefileWorkspaceFactory();
            //IWorkspace pWS = pWSF.OpenFromFile(out_folder,0);
            string current = GetTimeStamp(DateTime.Now);
            string outname = "resultWatershed" + current;
            IFeatureClass tWaterShedPolyFC;
            IGeoDataset tInitialPolygons;
            try
            {
                IConversionOp pConversionOp = new ESRI.ArcGIS.GeoAnalyst.RasterConversionOp() as IConversionOp;
                tInitialPolygons = pConversionOp.RasterDataToPolygonFeatureData(tWatershedGDS, inMemFeatWksp, outname, false);
                tWaterShedPolyFC = tInitialPolygons as IFeatureClass;
            }
            catch
            {
                logger.LogMessage(ServerLogger.msgType.debug, "convert and union wshed", 8000,
                        "Error in converting watershed to in-memory FC");
                tWaterShedPolyFC = null;
                tInitialPolygons = null;
            }

            // attempt to add a CATCH_AREA field to the feature class
            bool setAreaOk = false;
            try
            {
                //setAreaOk = AddAreaField(tWaterShedPolyFC);
                setAreaOk = AddAField(tWaterShedPolyFC, "Total_Area", esriFieldType.esriFieldTypeDouble);
            }
            catch
            {
                logger.LogMessage(ServerLogger.msgType.debug, "convert and union wshed", 8000,
                        "Error adding area field to output");
            }

            IFeature tWaterShedFeature;
            // if there is more than one feature in the FC then union them using geometrybag
            if (tWaterShedPolyFC.FeatureCount(null) > 1)
            {
                logger.LogMessage(ServerLogger.msgType.infoStandard, "convert and union wshed", 8000,
                        "Attempting to union multiple polygons...");

                // there is more than one polygon i.e. diagonally connected. merge them into a single feature
                // with multiple rings using a geometrybag
                IGeometryBag tGeometryBag = new GeometryBagClass();
                tGeometryBag.SpatialReference = tInitialPolygons.SpatialReference;
                IFeatureCursor tFCursor = tWaterShedPolyFC.Search(null, false);
                IGeometryCollection tGeomColl = tGeometryBag as IGeometryCollection;
                IFeature tCurrentFeature = tFCursor.NextFeature();
                ITable tTable = tCurrentFeature.Table;
                while (tCurrentFeature != null)
                {
                    object missing = Type.Missing;
                    tGeomColl.AddGeometry(tCurrentFeature.Shape, ref missing, ref missing);
                    tCurrentFeature = tFCursor.NextFeature();
                }
                ITopologicalOperator tUnioned = new PolygonClass();
                tUnioned.ConstructUnion(tGeometryBag as IEnumGeometry);
                logger.LogMessage(ServerLogger.msgType.infoStandard, "convert and union wshed", 8000,
                    "Done with ConstructUnion, doing area");
                try
                {
                    IArea tmpArea = tUnioned as IArea;
                    double tArea = tmpArea.Area;
                    // delete the previously existing rows from the table
                    tTable.DeleteSearchedRows(null);
                    // replace them with a new row representing the unioned feature
                    IRow tRow = tTable.CreateRow();
                    tRow.set_Value(tTable.FindField("SHAPE"), tUnioned);
                    tRow.set_Value(tTable.FindField("ID"), -1);
                    tRow.set_Value(tTable.FindField("GRIDCODE"), -1);
                    if (setAreaOk)
                    {
                        tRow.set_Value(tTable.FindField("Total_Area"), tArea);
                    }
                    tRow.Store();
                }
                catch (Exception ex)
                {
                    logger.LogMessage(ServerLogger.msgType.error, "store unioned polygon", 8000,
                       "Error setting fields of unioned polygon!" + ex.StackTrace + ex.Message);
                }
            }
            else
            {
                // There is only one polygon - i.e. there were not diagonally-disconnected bits
                // NB features are indexed starting at 1. Just for a laff.
                tWaterShedFeature = tWaterShedPolyFC.GetFeature(1);
                if (setAreaOk)
                {
                    try
                    {
                        int tAreaFieldIdx = tWaterShedFeature.Fields.FindField("Total_Area");
                        IArea tArea = tWaterShedFeature.Shape as IArea;
                        double tmpArea = tArea.Area;
                        tWaterShedFeature.set_Value(tAreaFieldIdx, tmpArea);
                        tWaterShedFeature.Store();
                        logger.LogMessage(ServerLogger.msgType.debug, "convert and union wshed", 8000,
                      "Done adding area to one polygon");
                    }
                    catch
                    {
                        logger.LogMessage(ServerLogger.msgType.debug, "convert and union wshed", 8000,
                        "Error adding area field to single polygon output");
                    }
                }
            }
            return (IGeoDataset)tWaterShedPolyFC;
        }
Esempio n. 38
0
        private ExtractionResultCollection ProcessExtractions(string pSearchId, IGeoDataset pInputPolygonGDS, IGeoDataset pInputRasterGDS, List<ExtractionLayerConfig> pExtractions)
        {
            logger.LogMessage(ServerLogger.msgType.debug, "ProcessExtractions", 99, "Starting processing: " + pExtractions.Count.ToString() + " extractions");
            if (pExtractions.Count == 0)
            {
                return new ExtractionResultCollection(pSearchId,pInputPolygonGDS,
                    new List<RasterExtractionResult>(),new List<FeatureExtractionResult>());
            }
            // represent the polygon geodataset as an IFeatureClass for adding fields and getting the
            // polygon feature to populate info into
            IFeatureClass tPolygonAsFC = (IFeatureClass)pInputPolygonGDS;
            IFeatureCursor tFeatureCursor = tPolygonAsFC.Search(null, false);
            IFeature tExtractionPolygonFeature = tFeatureCursor.NextFeature();
            IPolygon tExtractionPolygon = tExtractionPolygonFeature.ShapeCopy as IPolygon;
            List<RasterExtractionResult> tAllRasterResults = new List<RasterExtractionResult>();
            List<FeatureExtractionResult> tAllFeatureResults = new List<FeatureExtractionResult>();
            foreach (ExtractionLayerConfig tThisExtraction in pExtractions)
            {
                IGeoDataset tExtractionData = tThisExtraction.LayerDataset;
                switch (tThisExtraction.ExtractionType)
                {
                    case ExtractionTypes.CategoricalRaster:
                    case ExtractionTypes.ContinuousRaster:
                        RasterExtractionResult tRasterResults;
                        // use the raster mask / clipping geodataset if it's available (i.e. if this
                        // has been called from a watershed operation)
                        if (pInputRasterGDS != null)
                        {
                            tRasterResults =
                                WatershedDetailExtraction.SummariseRaster(pInputRasterGDS, tThisExtraction);
                            //WatershedDetailExtraction.SummariseCategoricalRaster(pInputRasterGDS, tCategoricalRaster);
                        }
                        // if not (this has been called from the ExtractByPolygon operation) just
                        // pass in the polygon geodataset and the clip function will handle converting to raster
                        else
                        {
                            tRasterResults =
                                WatershedDetailExtraction.SummariseRaster(pInputPolygonGDS, tThisExtraction);
                            //WatershedDetailExtraction.SummariseCategoricalRaster(pInputPolygonGDS, tCategoricalRaster);
                        }
                        tAllRasterResults.Add(tRasterResults);
                        logger.LogMessage(ServerLogger.msgType.debug, "ProcessExtractions", 99,
                            "Summary done ok");
                        break;
                    case ExtractionTypes.PointFeatures:
                    case ExtractionTypes.LineFeatures:
                    case ExtractionTypes.PolygonFeatures:
                        // it is a feature class
                        // summarise giving count features giving count and stats of the display field if it's float
                        // or count of each value if it's integer, or nothing if it's text etc
                        logger.LogMessage(ServerLogger.msgType.debug, "ProcessExtractions", 99,
                            "Layer is a feature layer");
                        IFeatureClass tFC = (IFeatureClass)tExtractionData;//tDataObj as IFeatureClass;
                        FeatureExtractionResult tResult = WatershedDetailExtraction.SummariseFeatures(
                            tExtractionPolygon, tThisExtraction);
                        logger.LogMessage(ServerLogger.msgType.debug, "ProcessExtractions", 99,
                            "Got extraction result - successful = " + tResult.ExtractionSuccessful.ToString());
                        tAllFeatureResults.Add(tResult);
                        logger.LogMessage(ServerLogger.msgType.debug, "ProcessExtractions", 99,
                            "Processed layer ok");
                        break;
                    // end of processing this extraction result switch statement
                }
                // end of loop going over extraction tasks, do the next one
            }
            // all extractions (if any) are now complete and we have a list of RasterExtractionResults and
            // a list of FeatureExtractionResults representing the results from every raster and FC extraction.
            logger.LogMessage(ServerLogger.msgType.debug, "ProcessExtractions", 99,
                            "All extractions done");

            return new ExtractionResultCollection(pSearchId, pInputPolygonGDS, tAllRasterResults, tAllFeatureResults);
        }
 internal static Dictionary<string, double> SummariseRasterCategorically(IGeoDataset pRasterGeoDataset)
 {
     // fiddle about to get to the extracted raster's attribute table
     IRasterBandCollection tClippedAsBandCollection = pRasterGeoDataset as IRasterBandCollection;
     IRasterBand tClippedBand = tClippedAsBandCollection.Item(0);
     ITable tClippedTable = tClippedBand.AttributeTable;
     // pass through the table once to get the total cell count
     ICursor tTableCursor = tClippedTable.Search(null, false);
     IRow tTableRow = tTableCursor.NextRow();
     double totalcount = 0.0; // store as a double so the percentage division results in a double later
     Dictionary<string, double> tResultsAsPct = new Dictionary<string, double>();
     Dictionary<string, int> tResultsCountIntermediate = new Dictionary<string, int>();
     int rowcount;
     int rowvalue;
     int countfield = tClippedTable.FindField("COUNT");
     int valfield = tClippedTable.FindField("VALUE");
     while (tTableRow != null)
     {
         rowcount = (int)tTableRow.get_Value(countfield);
         rowvalue = (int)tTableRow.get_Value(valfield);
         totalcount += rowcount;
         tResultsCountIntermediate[rowvalue.ToString()] = rowcount;
         tTableRow = tTableCursor.NextRow();
     }
     // tResultsAsPct is now actually a count of each value
     foreach (string key in tResultsCountIntermediate.Keys)
     {
         double countval = tResultsCountIntermediate[key];
         double tPercent = countval / totalcount *100;
         tResultsAsPct[key] = tPercent;
     }
     logger.LogMessage(ServerLogger.msgType.debug, "SummariseRasterCategorically", 99, "Counted total cells: " + totalcount.ToString()+
         "in "+tResultsAsPct.Count.ToString()+" categories");
     return tResultsAsPct;
 }
Esempio n. 40
0
        /// <summary>
        /// get a clip of a larger raster using the specified survey boundary as the cut out shape
        /// </summary>
        public static IGeoDataset ClipRasterByBndPoly(IGeoDataset RasterToClip, string SurveyID, ref string ErrorMessage)
        {
            IPolygon SurveyBoundary, SurveyEnvelopePoly, DEMEnvelopePoly;
            ESRI.ArcGIS.SpatialAnalyst.IExtractionOp ExtractOp;
            IGeoDataset ClippedRaster = null;

            SurveyBoundary = Util.GetSurveyBoundary(SurveyID, ref ErrorMessage);
            if (string.IsNullOrEmpty(ErrorMessage) == false) return null;

            SurveyEnvelopePoly = Util.EnvelopeToPolygon(SurveyBoundary.Envelope);
            DEMEnvelopePoly = Util.EnvelopeToPolygon(RasterToClip.Extent);

            if (((IRelationalOperator)DEMEnvelopePoly).Contains(SurveyEnvelopePoly) == false)
            {
                ErrorMessage = "The boundary polygon for SurveyID " + SurveyID
                    + " is out of range of the Raster extent.";
                return null;
            }

            try
            {
                ExtractOp = new ESRI.ArcGIS.SpatialAnalyst.RasterExtractionOpClass();
                ClippedRaster = ExtractOp.Polygon(RasterToClip, SurveyEnvelopePoly, true);
            }
            catch (Exception ex)
            {
                ErrorMessage = "Error occured while clipping raster to boundary of survey "
                    + SurveyID + ". " + ex.Message;
            }

            return ClippedRaster;
        }
Esempio n. 41
0
        /// <summary>
        /// 根据某一图层的范围,创建mdb文件中的featuredataset及其空间范围
        /// </summary>
        /// <param name="motherWs">要创建featuredataset的工作空间</param>
        /// <param name="pGeoDataset">featuredataset所要依据的空间参考和空间范围</param>
        /// 这个函数要改!!
        public static void CreateDatasetInWs(IWorkspace motherWs, IGeoDataset pGeoDataset,string datasetName)
        {
            try
            {
                ISpatialReference pSpatialRef = null;
                IFeatureDataset pFtDs = null;

                if (pGeoDataset != null)
                {
                    pSpatialRef = pGeoDataset.SpatialReference;

                    IControlPrecision2 controlPrecision2 = pSpatialRef as IControlPrecision2;
                    if (!controlPrecision2.IsHighPrecision)
                        controlPrecision2.IsHighPrecision = true;

                    IEnvelope pEnv = pGeoDataset.Extent;
                    pEnv.Expand(1.5, 1.5, true);
                    pSpatialRef.SetDomain(pEnv.XMin, pEnv.XMax, pEnv.YMin, pEnv.YMax);

                    ISpatialReferenceTolerance pSpatialTolerance = (ISpatialReferenceTolerance)pSpatialRef;
                    double dXYTolerance = pSpatialTolerance.XYTolerance;
                    double dZTolerance = pSpatialTolerance.ZTolerance;
                    ISpatialReferenceResolution pSpatialRefResolution = (ISpatialReferenceResolution)pSpatialRef;
                    pSpatialRefResolution.set_XYResolution(true, dXYTolerance * 0.1);
                    pSpatialRefResolution.set_ZResolution(true, dZTolerance * 0.1);
                    pSpatialRefResolution.MResolution = pSpatialTolerance.MTolerance * 0.1;

                    pFtDs = ((IFeatureWorkspace)motherWs).CreateFeatureDataset(datasetName, pSpatialRef);
                }
                else
                {
                    pSpatialRef = new UnknownCoordinateSystemClass();

                    ISpatialReferenceTolerance pSpatialTolerance = (ISpatialReferenceTolerance)pSpatialRef;
                    double dXYTolerance = pSpatialTolerance.XYTolerance;
                    double dZTolerance = pSpatialTolerance.ZTolerance;
                    ISpatialReferenceResolution pSpatialRefResolution = (ISpatialReferenceResolution)pSpatialRef;
                    pSpatialRefResolution.set_XYResolution(true, dXYTolerance * 0.1);
                    pSpatialRefResolution.set_ZResolution(true, dZTolerance * 0.1);
                    pSpatialRefResolution.MResolution = pSpatialTolerance.MTolerance * 0.1;

                    pFtDs = ((IFeatureWorkspace)motherWs).CreateFeatureDataset(datasetName, pSpatialRef);
                }
            }
            catch(Exception exp)
            {
                Hy.Common.Utility.Log.OperationalLogManager.AppendMessage(exp.ToString());

            }
        }
 internal static Dictionary<string, double> SummariseRasterStatistically(IGeoDataset pRasterGeoDataset)
 {
     IRasterBandCollection tClippedAsBandCollection = pRasterGeoDataset as IRasterBandCollection;
     IRasterBand tClippedBand = tClippedAsBandCollection.Item(0);
     logger.LogMessage(ServerLogger.msgType.debug, "SummariseContinuousRaster", 99, "Continuous raster clipped, checking stats...");
     bool tHasStatistics;
     tClippedBand.HasStatistics(out tHasStatistics);
     // what on earth? why not just have a bool return type to the HasStatistics method??!
     if (!tHasStatistics)
     {
         tClippedBand.ComputeStatsAndHist();
     }
     IRasterStatistics tClippedStats = tClippedBand.Statistics;
     //tClippedStats.Recalculate();
     logger.LogMessage(ServerLogger.msgType.debug, "SummariseContinuousRaster", 99, "Continuous raster stats made, recording info...");
     Dictionary<string, double> tResults = new Dictionary<string, double>();
     tResults["Mean"] = tClippedStats.Mean;
     tResults["Max"] = tClippedStats.Maximum;
     tResults["Min"] = tClippedStats.Minimum;
     //NB Median isn't available with floating data. (Neither are majority,minority,variety). Would need
     //to e.g. convert to int by multiplying raster first.
     //tResults["Median"] = tClippedStats.Median;
     return tResults;
 }
Esempio n. 43
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="_pGdsLocation"></param>
 /// <param name="_BandCol"></param>
 /// <returns></returns>
 private ITable ExportSample(IGeoDataset _pGdsLocation, IRasterBandCollection _BandCol)
 {
     //IRasterLayer pRastetLayer = pLayer as IRasterLayer;
     //IRasterBandCollection pRasterBandColection = pRastetLayer.Raster as IRasterBandCollection;
     //if (pRasterBandColection.Count == 1)
     //{
         //Create the RasterExtractionOp object
         IExtractionOp pExtractionOp = new RasterExtractionOpClass();
         ////Declare the input location raster object
         //IGeoDataset pGdsLocation=_pGdsLocation;
         ////Create a raster of multiple bands
         //IRasterBandCollection pBandCol=_BandCol;
         ////Declare the output table object
         ITable pOutputTable;
         //Calls the method
         pOutputTable = pExtractionOp.Sample(_pGdsLocation, _BandCol as IGeoDataset, esriGeoAnalysisResampleEnum.esriGeoAnalysisResampleNearest);
         return pOutputTable;
     //}
 }
Esempio n. 44
0
 private void Rater2Ascii(IGeoDataset mask,int cellsize,IGeoDataset inData,string ascFileName)
 {
     if (mask == null)
         return;
     if (inData == null)
         return;
     if (ascFileName.Trim() == "")
         return;
     IRasterExportOp rexp=new RasterConversionOpClass();
     IRasterAnalysisEnvironment pEnv = (IRasterAnalysisEnvironment)rexp;
     object dCellSize = cellsize;  //栅格大小
     pEnv.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, ref dCellSize);
     pEnv.Mask=mask;
     //cov1_0.0  con1_(land use type)_(simulation year)
     //string ascFile=this.txtProjectPath.Text="\\DLS\\DLS\\Input\\con1_0.0";
     //文件存在就删除
     FileInfo file = new FileInfo(ascFileName);
     if (file.Exists)
     {
         file.Delete();
     }
     rexp.ExportToASCII(inData, ascFileName);
     //IRasterextrac rexp = new RasterConversionOpClass();
 }
Esempio n. 45
0
        private void LoadAllFeatClass(TreeNode node1, string sDatasetName)
        {
            try
            {
                IFeatureDataset pFeatDS = m_pFeatureWorkspace.OpenFeatureDataset(sDatasetName);
                pGeoDataset = pFeatDS as IGeoDataset;
                IEnumDataset pEnumDataset = pFeatDS.Subsets;
                IDataset pDataset = pEnumDataset.Next();
                while (pDataset != null)
                {
                    if (pDataset.Type == esriDatasetType.esriDTFeatureClass)
                    {
                        node1.Nodes.Add(pDataset.Name);

                    }
                    pDataset = pEnumDataset.Next();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Esempio n. 46
0
 /// <summary>
 /// add elevation values from the specified batch of points for the specified survey
 /// </summary>
 public static void AddZValuesToPoints(int SurveyID, int NewBatchID, IGeoDataset ThisRasterDS, string ThisDEMUnits, ref string ErrorMessage)
 {
     Util.AddZValuesToPoints(SurveyID, NewBatchID, -1, ThisRasterDS, ThisDEMUnits, ref ErrorMessage);
 }
        internal static RasterExtractionResult SummariseRaster(IGeoDataset pClippingPolygon, ExtractionLayerConfig pExtractionLayerConfig)
        {
            // set the analysis extent to be that of the polygon
            ServerLogger logger = new ServerLogger();
            logger.LogMessage(ServerLogger.msgType.debug, "SummariseCategoricalRaster", 99, "Categorical raster clip beginning..");
            IEnvelope tAnalysisExtent = pClippingPolygon.Extent;

            bool pCategoricalSummary = pExtractionLayerConfig.ExtractionType==ExtractionTypes.CategoricalRaster;
            IGeoDataset pRasterToClip = pExtractionLayerConfig.LayerDataset;

            IRasterAnalysisEnvironment tRasterAnalysisEnvironment = new RasterAnalysisClass();
            object tAnalysisEnvelopeCastToObject = (System.Object)tAnalysisExtent;
               // object tAnotherBizarreMissingObject = Type.Missing;
            object tSnapObject = (System.Object)pRasterToClip;
            tRasterAnalysisEnvironment.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvValue,
                ref tAnalysisEnvelopeCastToObject, ref tSnapObject);
            tRasterAnalysisEnvironment.SetAsNewDefaultEnvironment();
            // extract the subset of the raster
            IExtractionOp2 tExtractionOp = new RasterExtractionOpClass();
            // note we want to base the extraction on a raster (in an IGeoDataset) rather than an IPolygon.
            // That's because the catchment polygon may be multipart, and the operation doesn't work with multipart.
            // Also the polygon has a max of 1000 vertices.
            // And raster mask extraction is probably faster since the
            // polygon is converted internally to a grid anyway.
            IGeoDataset tClipped;
            if (pRasterToClip as IRaster != null)
            {
                logger.LogMessage(ServerLogger.msgType.debug, "SummariseRaster", 99,
                    "Input was in raster form, using directly to clip...");
                tClipped = tExtractionOp.Raster(pRasterToClip, pClippingPolygon);
            }
            else
            {
                // POLYGON VERSION: tExtractionOp.Polygon(pClipRaster,pPolygon,true)
                // sometimes we need to be able to pass in a polygon but rather than using the polygon
                // method we'll manually convert to a mask raster to avoid the issues above
                // It would save work to do this once for each request rather than repeat the conversion
                // for each layer - but we might want a different environment (snap extent etc) for each.
                logger.LogMessage(ServerLogger.msgType.debug, "SummariseCategoricalRaster", 99,
                    "Converting input polygon to mask raster for clip...");
                IRasterConvertHelper tConvertPolygonToRaster = new RasterConvertHelperClass();
                // convert it to a raster with the same cell size as the input
                IRasterProps tRst = pRasterToClip as IRasterProps;
                IPnt tRstCellSize = tRst.MeanCellSize();
                double x = tRstCellSize.X;
                double y = tRstCellSize.Y;
                double cellSize = Math.Round(Math.Min(x, y), 0);
                object tCellSizeAsObjectForNoGoodReason = (System.Object)cellSize;
                tRasterAnalysisEnvironment.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue,
                    ref tCellSizeAsObjectForNoGoodReason);
                IGeoDataset tPolyAsRast =
                    tConvertPolygonToRaster.ToRaster1(pRasterToClip, "GRID", tRasterAnalysisEnvironment)
                as IGeoDataset;
                logger.LogMessage(ServerLogger.msgType.debug, "SummariseCategoricalRaster", 99,
                    "...done, proceeding with clip");
                tClipped = tExtractionOp.Raster(pRasterToClip, tPolyAsRast);
            }
            // now we have the clipped raster we need to summarise it differently depending on whether
            // we want a summary by category/value (for categorical rasters) or by stats (for float rasters)
            Dictionary<string, double> tResults;
            if (pCategoricalSummary)
            {
                tResults = WatershedDetailExtraction.SummariseRasterCategorically(tClipped);
                if (tResults.Count > 100)
                {
                    // sanity check: don't sum up more than 100 different values
                    tResults = WatershedDetailExtraction.SummariseRasterStatistically(tClipped);
                    pCategoricalSummary = false;
                }
            }
            else
            {
                tResults = WatershedDetailExtraction.SummariseRasterStatistically(tClipped);
            }
            tRasterAnalysisEnvironment.RestoreToPreviousDefaultEnvironment();
            return new RasterExtractionResult(pExtractionLayerConfig.ParamName, pCategoricalSummary, tResults);
            //return tResults;
        }
Esempio n. 48
0
        //
        //
        //
        public static IGeoDataset smoothRaster(IGeoDataset m_GeoIn)
        {
            INeighborhoodOp nbOp;
            IRasterAnalysisEnvironment pEnv;
            nbOp = (new RasterNeighborhoodOpClass()) as INeighborhoodOp;
            pEnv = nbOp as IRasterAnalysisEnvironment;

            IGeoDataset m_GeoOut = null;
            object Missing = Type.Missing;
            double cellSize = 1;
            //װ�����
            object objCellSize = cellSize;
            try
            {
                pEnv.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, ref objCellSize);
                pEnv.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvMaxOf, ref Missing, ref Missing);
                IRasterNeighborhood pNB = new RasterNeighborhoodClass();
                pNB.SetDefault();
                //pGeoOut = pop.FocalStatistics(m_GeoIn, esriGeoAnalysisStatsMean, pNB, True);
                m_GeoOut = nbOp.FocalStatistics(m_GeoIn, esriGeoAnalysisStatisticsEnum.esriGeoAnalysisStatsMean, pNB, true);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
            return m_GeoOut;
        }
Esempio n. 49
0
        /// <summary>
        /// get the units of a dataset
        /// </summary>
        public static string GetDatasetUnits(IGeoDataset npsGeoDataset, ref string ErrorMessage)
        {
            ISpatialReference npsSpatialReference;
            IProjectedCoordinateSystem npsPrjCoordSys;
            IGeographicCoordinateSystem npsGeoCoordSys;
            string UnitName;

            UnitName = "";

            try
            {

                npsSpatialReference = npsGeoDataset.SpatialReference;

                if (npsSpatialReference is IProjectedCoordinateSystem)
                {
                    npsPrjCoordSys = npsSpatialReference as IProjectedCoordinateSystem;
                    UnitName = npsPrjCoordSys.CoordinateUnit.Name;
                }

                if (npsSpatialReference is IGeographicCoordinateSystem)
                {
                    npsGeoCoordSys = npsSpatialReference as IGeographicCoordinateSystem;
                    UnitName = npsGeoCoordSys.CoordinateUnit.Name;
                }

                if (string.IsNullOrEmpty(UnitName))
                    ErrorMessage = "(Err) Units could not be obtained from dataset.";

            }
            catch (Exception ex)
            {
                ErrorMessage = "(Err) Error occured while trying to obtain Units from dataset." + ex.Message;
            }

            return UnitName;
        }
        public void LoadTempImportFC(int SurveyID, int BatchID, int NextTransectID, IFeatureCursor ImportFCursor,
            IFeatureClass TempImportFC, IGeoDataset ThisDEM, double TargetLength, ref List<int> NewOIDs,
            ref int TotalInExcluded, ref int TotalOutsideBndy, ref int TotalPassed,string ThisDEMUnits, ref string ErrorMessage)
        {
            IFeature ImportFeature;
            IFeatureCursor ImportToCursor = null;
            IFeatureBuffer ImportToBuffer = null;
            esriGeometryType FType;
            bool IsInExcludedAreas, IsInBndPoly;
            ESRI.ArcGIS.GeoAnalyst.ISurfaceOp2 npsSurfaceOp = null;
            int ThisFieldIndex;
            IPoint TempPoint;
            IPolyline NewTrnPolyline;
            double Elev;
            IPolyline CPolyline;
            IPoint centerPoint;
            IFeatureClass ExclPolyFC, BndPolyFC;

            ThisDEMUnits = ThisDEMUnits.ToLower();
            NewOIDs = new List<int>();
            TotalInExcluded = 0;
            TotalOutsideBndy = 0;
            TotalPassed = 0;

            ExclPolyFC = Util.GetFeatureClass(m_NPS.LYR_EXCLUDED_AREAS, ref ErrorMessage);
            if (string.IsNullOrEmpty(ErrorMessage) == false) return;

            BndPolyFC = Util.GetFeatureClass(m_NPS.LYR_SURVEY_BOUNDARY, ref ErrorMessage);
            if (string.IsNullOrEmpty(ErrorMessage) == false) return;

            FType = TempImportFC.ShapeType;

            //get insert cursor in the nps feature class we are going to insert into
            ImportToCursor = TempImportFC.Insert(true);
            ImportToBuffer = TempImportFC.CreateFeatureBuffer();

            if (FType == esriGeometryType.esriGeometryPolyline)
                npsSurfaceOp = new ESRI.ArcGIS.GeoAnalyst.RasterSurfaceOpClass();

            //loop through each import feature and import it to it's appropriate featureclass
            while ((ImportFeature = ImportFCursor.NextFeature()) != null)
            {
                //make sure the shape is valid
                if (ImportFeature.ShapeCopy == null)
                {
                    TotalOutsideBndy++;
                    continue;
                }

                if (FType == esriGeometryType.esriGeometryPoint)
                {

                    //check if rand point  falls in excluded areas
                    IsInExcludedAreas = Util.HasRelationshipWithFC(ImportFeature.ShapeCopy, esriSpatialRelEnum.esriSpatialRelWithin,
                        ExclPolyFC, "SurveyID=" + SurveyID);

                    //if point is in excluded areas, don't add
                    if (IsInExcludedAreas)
                    {
                        TotalInExcluded++;
                        continue;
                    }

                    //check if  rand point is within boundary
                    IsInBndPoly = Util.HasRelationshipWithFC(ImportFeature.ShapeCopy, esriSpatialRelEnum.esriSpatialRelWithin,
                        BndPolyFC, "SurveyID=" + SurveyID);

                    //if random point is not in boundary, dont add it
                    if (IsInBndPoly == false)
                    {
                        TotalOutsideBndy++;
                        continue;
                    }

                }

                if (FType == esriGeometryType.esriGeometryPolyline)
                {

                    //check if new line falls in excluded areas
                    IsInExcludedAreas = Util.HasRelationshipWithFC(ImportFeature.ShapeCopy, esriSpatialRelEnum.esriSpatialRelCrosses,
                         ExclPolyFC, "SurveyID=" + SurveyID);

                    //if point is in excluded areas, don't add
                    if (IsInExcludedAreas)
                    {
                        TotalInExcluded++;
                        continue;
                    }

                    //check if new line is within in boundary
                    IsInBndPoly = Util.HasRelationshipWithFC(ImportFeature.ShapeCopy, esriSpatialRelEnum.esriSpatialRelWithin,
                         BndPolyFC, "SurveyID=" + SurveyID);

                    //if random point is not in boundary, dont add it
                    if (IsInBndPoly == false)
                    {
                        TotalOutsideBndy++;
                        continue;
                    }

                }

                TotalPassed++;

                //add feature to temp feature class
                ImportToBuffer.Shape = ImportFeature.ShapeCopy;
                ImportToBuffer.set_Value(ImportToBuffer.Fields.FindField("SurveyID"), SurveyID);
                ImportToBuffer.set_Value(ImportToBuffer.Fields.FindField("BATCH_ID"), BatchID);

                if (FType == esriGeometryType.esriGeometryPolyline)
                {

                    ThisFieldIndex = ImportToBuffer.Fields.FindField("Flown");
                    if (ThisFieldIndex > -1) ImportToBuffer.set_Value(ImportToBuffer.Fields.FindField("Flown"), "N");

                    ThisFieldIndex = ImportToBuffer.Fields.FindField("TransectID");
                    if (ThisFieldIndex > -1) ImportToBuffer.set_Value(ImportToBuffer.Fields.FindField("TransectID"), NextTransectID);

                    NextTransectID++;

                    NewTrnPolyline = ImportToBuffer.Shape as IPolyline;

                    ThisFieldIndex = ImportToBuffer.Fields.FindField("LENGTH_MTR");
                    if (ThisFieldIndex > -1) ImportToBuffer.set_Value(ThisFieldIndex, NewTrnPolyline.Length);

                    //add the name of the default projection
                    ThisFieldIndex = ImportToBuffer.Fields.FindField("PROJECTION");
                    if (ThisFieldIndex > -1) ImportToBuffer.set_Value(ThisFieldIndex, NewTrnPolyline.SpatialReference.Name);

                    ThisFieldIndex = ImportToBuffer.Fields.FindField("TARGETLEN");
                    if (ThisFieldIndex > -1) ImportToBuffer.set_Value(ThisFieldIndex, TargetLength);

                    //clone from point
                    TempPoint = ((ESRI.ArcGIS.esriSystem.IClone)NewTrnPolyline.FromPoint).Clone() as IPoint;

                    //add from point projected coords
                    ThisFieldIndex = ImportToBuffer.Fields.FindField("PROJTD_X1");
                    if (ThisFieldIndex > -1) ImportToBuffer.set_Value(ThisFieldIndex, TempPoint.X);
                    ThisFieldIndex = ImportToBuffer.Fields.FindField("PROJTD_Y1");
                    if (ThisFieldIndex > -1) ImportToBuffer.set_Value(ThisFieldIndex, TempPoint.Y);

                    //add from point geo coords
                    ((IGeometry2)TempPoint).ProjectEx(Util.GetWGSSpatRef(), esriTransformDirection.esriTransformForward, null, false, 0, 0);
                    ThisFieldIndex = ImportToBuffer.Fields.FindField("DD_LONG1");
                    if (ThisFieldIndex > -1) ImportToBuffer.set_Value(ThisFieldIndex, TempPoint.X);
                    ThisFieldIndex = ImportToBuffer.Fields.FindField("DD_LAT1");
                    if (ThisFieldIndex > -1) ImportToBuffer.set_Value(ThisFieldIndex, TempPoint.Y);

                    //clone to point
                    TempPoint = ((ESRI.ArcGIS.esriSystem.IClone)NewTrnPolyline.ToPoint).Clone() as IPoint;

                    //add to point projected coords
                    ThisFieldIndex = ImportToBuffer.Fields.FindField("PROJTD_X2");
                    if (ThisFieldIndex > -1) ImportToBuffer.set_Value(ThisFieldIndex, TempPoint.X);
                    ThisFieldIndex = ImportToBuffer.Fields.FindField("PROJTD_Y2");
                    if (ThisFieldIndex > -1) ImportToBuffer.set_Value(ThisFieldIndex, TempPoint.Y);

                    //add to point geo coords
                    ((IGeometry2)TempPoint).ProjectEx(Util.GetWGSSpatRef(), esriTransformDirection.esriTransformForward, null, false, 0, 0);
                    ThisFieldIndex = ImportToBuffer.Fields.FindField("DD_LONG2");
                    if (ThisFieldIndex > -1) ImportToBuffer.set_Value(ThisFieldIndex, TempPoint.X);
                    ThisFieldIndex = ImportToBuffer.Fields.FindField("DD_LAT2");
                    if (ThisFieldIndex > -1) ImportToBuffer.set_Value(ThisFieldIndex, TempPoint.Y);

                    //get center point
                    centerPoint = new PointClass();
                    ((ICurve)NewTrnPolyline).QueryPoint(esriSegmentExtension.esriNoExtension, 0.5, true, centerPoint);

                    //get elevation for transect center
                    CPolyline = new PolylineClass();
                    npsSurfaceOp.ContourAsPolyline(ThisDEM, centerPoint, out CPolyline, out Elev);

                    //set elevation in meters
                    ThisFieldIndex = ImportToBuffer.Fields.FindField("ELEV_M");
                    if (ThisFieldIndex > -1)
                    {
                        if (ThisDEMUnits == "feet") ImportToBuffer.set_Value(ThisFieldIndex, 0.3048 * Elev);
                        if (ThisDEMUnits == "meters") ImportToBuffer.set_Value(ThisFieldIndex, Elev);

                    }

                    //get elevation in feet
                    ThisFieldIndex = ImportToBuffer.Fields.FindField("ELEVFT");
                    if (ThisFieldIndex > -1)
                    {
                        if (ThisDEMUnits == "feet") ImportToBuffer.set_Value(ThisFieldIndex, Elev);
                        if (ThisDEMUnits == "meters") ImportToBuffer.set_Value(ThisFieldIndex, Elev * 3.2808399);
                    }

                }

                NewOIDs.Add((int)Util.SafeConvert(ImportToCursor.InsertFeature(ImportToBuffer), typeof(int)));

            }

            ImportFCursor = null;
            ImportToCursor = null;
            ImportToBuffer = null;
        }
Esempio n. 51
0
        /// <summary>
        /// generate transects for spicified survey
        /// </summary>
        public static void GenerateTransectLines(int SurveyID, double MaxLineLength, double MinLineLength,
            IGeoDataset ClippedRasterDS, int TransCreateAttempts, int TransectTotal, double TargetLength,
            ref int ThisBatchID, ref int StraightCount, ref int ContourCount, ref int FailCount, ref string ErorrMessage)
        {
            NPSGlobal NPS;
            IFeatureClass RandPointsFC, TransectFC, BoundaryFC, ExcludedFC, FlatAreasFC;
            IFeature RandPntFeature;
            IFeatureCursor RandPntCursor;
            IFeatureCursor InsertCursor;
            IFeatureBuffer InsertBuffer;
            IQueryFilter ThisQueryFilter;
            int RandomPointOIDIndex, TransectIDFieldIndex, CorruptCount = 0,
                TransectCount = 0, ElevValFieldIndex, NewBatchID, NewTransectID,
                FlownFieldIndex, AcceptedFieldIndex, PT_IDFieldIndex, SurveyIDFieldIndex,
                BatchIDFieldIndex, TargetLengthFieldIndex, TrnsectElevValFieldIndex,
                TrnsectElevValFTFieldIndex, ElevValFTFieldIndex;
            IPolyline NewTrnPolyline;
            IPoint TempPoint;
            string TransType = "", ErrorMessage = "", DEMUnits = "";

            NPS = NPSGlobal.Instance;

            //get all necessary feature classes
            RandPointsFC = Util.GetFeatureClass(NPS.LYR_RANDOMPOINTS, ref ErorrMessage);
            if (string.IsNullOrEmpty(ErorrMessage) == false) return;

            TransectFC = Util.GetFeatureClass(NPS.LYR_GENERATED_TRANSECTS, ref ErorrMessage);
            if (string.IsNullOrEmpty(ErorrMessage) == false) return;

            BoundaryFC = Util.GetFeatureClass(NPS.LYR_SURVEY_BOUNDARY, ref ErorrMessage);
            if (string.IsNullOrEmpty(ErorrMessage) == false) return;

            ExcludedFC = Util.GetFeatureClass(NPS.LYR_EXCLUDED_AREAS, ref ErorrMessage);
            if (string.IsNullOrEmpty(ErorrMessage) == false) return;

            FlatAreasFC = Util.GetFeatureClass(NPS.LYR_FLAT_AREAS, ref ErorrMessage);
            if (string.IsNullOrEmpty(ErorrMessage) == false) return;

            DEMUnits = Util.GetDatasetUnits(ClippedRasterDS, ref ErorrMessage);

            //get next available batch id
            NewBatchID = Util.GetHighestFieldValue(NPS.LYR_GENERATED_TRANSECTS,
                "BATCH_ID", "SurveyID=" + SurveyID, ref ErrorMessage);
            if (string.IsNullOrEmpty(ErrorMessage) == false) return;
            NewBatchID++;

            ThisBatchID = NewBatchID;

            //get next available transect id
            NewTransectID = Util.GetHighestFieldValue(NPS.LYR_GENERATED_TRANSECTS,
                "TransectID", "SurveyID=" + SurveyID, ref ErrorMessage);
            if (string.IsNullOrEmpty(ErrorMessage) == false) return;
            NewTransectID++;

            //field indexes on transect fc
            TransectIDFieldIndex = TransectFC.FindField("TransectID");
            FlownFieldIndex = TransectFC.FindField("Flown");
            PT_IDFieldIndex = TransectFC.FindField("PT_ID");
            SurveyIDFieldIndex = TransectFC.FindField("SurveyID");
            BatchIDFieldIndex = TransectFC.FindField("BATCH_ID");
            TargetLengthFieldIndex = TransectFC.FindField("TARGETLEN");
            TrnsectElevValFieldIndex = TransectFC.FindField("ELEV_M");
            TrnsectElevValFTFieldIndex = TransectFC.FindField("ELEVFT");

            //rnd point indexes
            AcceptedFieldIndex = RandPointsFC.FindField("HASTRANS");
            RandomPointOIDIndex = RandPointsFC.FindField(RandPointsFC.OIDFieldName);
            ElevValFieldIndex = RandPointsFC.FindField("ELEV_M");
            ElevValFTFieldIndex = RandPointsFC.FindField("ELEV_FT");

            //open updatable reader to random points for this survey
            ThisQueryFilter = new QueryFilterClass();
            ThisQueryFilter.WhereClause = "SurveyID=" + SurveyID;
            RandPntCursor = RandPointsFC.Update(ThisQueryFilter, false);

            //create an insert cursor for isnerting transects into transect featureclass
            InsertCursor = TransectFC.Insert(true);
            InsertBuffer = TransectFC.CreateFeatureBuffer();

            string CorruptFlag;

            while ((RandPntFeature = RandPntCursor.NextFeature()) != null)
            {
                //if we are at the requested transect count, stop making transects
                if (TransectCount == TransectTotal) break;

                //make sure the random point shape is valid
                if (RandPntFeature.ShapeCopy == null) continue;

                //check if this point is corrupted, if so don't process it
                CorruptFlag = (string)Util.SafeConvert(RandPntFeature.get_Value(AcceptedFieldIndex), typeof(string));
                if (CorruptFlag == "?")
                {
                    CorruptCount++;
                    continue;
                }

                //set point to in transect generation mode. if a crash occurs because of a point then
                //we know which point it was
                if (AcceptedFieldIndex > -1)
                {
                    RandPntFeature.set_Value(AcceptedFieldIndex, "?");
                    RandPntCursor.UpdateFeature(RandPntFeature);
                }

                TransType = "";

                //generate new transect from random point
                NewTrnPolyline = Util.CreateTransPolylineFromRandPoint(RandPntFeature.ShapeCopy as IPoint,
                    MaxLineLength, MinLineLength, BoundaryFC, ExcludedFC, FlatAreasFC, SurveyID, ClippedRasterDS,
                    TransCreateAttempts, ref TransType, ref ErrorMessage);

                //update counters on startus of transect generation
                if (TransType == "straight") StraightCount++;
                if (TransType == "contour") ContourCount++;
                if (TransType == "") FailCount++;

                //if we successfully generated a transect...
                if (NewTrnPolyline != null)
                {
                    //set the transect id field and update transect id counter
                    if (TransectIDFieldIndex > -1)
                    {
                        InsertBuffer.set_Value(TransectIDFieldIndex, NewTransectID);
                        NewTransectID++;
                    }

                    //set new transect feature fields
                    InsertBuffer.Shape = NewTrnPolyline;
                    if (FlownFieldIndex > -1) InsertBuffer.set_Value(FlownFieldIndex, "N");
                    if (PT_IDFieldIndex > -1) InsertBuffer.set_Value(PT_IDFieldIndex, RandPntFeature.OID);
                    if (SurveyIDFieldIndex > -1) InsertBuffer.set_Value(SurveyIDFieldIndex, SurveyID);
                    if (BatchIDFieldIndex > -1) InsertBuffer.set_Value(BatchIDFieldIndex, NewBatchID);
                    if (TargetLengthFieldIndex > -1) InsertBuffer.set_Value(TargetLengthFieldIndex, TargetLength);

                    //update random point fields
                    if (AcceptedFieldIndex > -1) RandPntFeature.set_Value(AcceptedFieldIndex, "Y");

                    if (TransectFC.FindField("LENGTH_MTR") > -1)
                        InsertBuffer.set_Value(TransectFC.FindField("LENGTH_MTR"), NewTrnPolyline.Length);

                    if (TransectFC.FindField("PROJECTION") > -1)
                        InsertBuffer.set_Value(TransectFC.FindField("PROJECTION"), NewTrnPolyline.SpatialReference.Name);

                    //save from point coords in transect fields
                    TempPoint = ((ESRI.ArcGIS.esriSystem.IClone)NewTrnPolyline.FromPoint).Clone() as IPoint;

                    if (TransectFC.FindField("PROJTD_X1") > -1)
                        InsertBuffer.set_Value(TransectFC.FindField("PROJTD_X1"), TempPoint.X);

                    if (TransectFC.FindField("PROJTD_Y1") > -1)
                        InsertBuffer.set_Value(TransectFC.FindField("PROJTD_Y1"), TempPoint.Y);

                    //project transect from point to geo coordinates and save coords in transect fields
                    ((IGeometry2)TempPoint).ProjectEx(Util.GetWGSSpatRef(),
                        esriTransformDirection.esriTransformForward, null, false, 0, 0);

                    if (TransectFC.FindField("DD_LONG1") > -1)
                        InsertBuffer.set_Value(TransectFC.FindField("DD_LONG1"), TempPoint.X);

                    if (TransectFC.FindField("DD_LAT1") > -1)
                        InsertBuffer.set_Value(TransectFC.FindField("DD_LAT1"), TempPoint.Y);

                    //save to point coords in transect fields
                    TempPoint = ((ESRI.ArcGIS.esriSystem.IClone)NewTrnPolyline.ToPoint).Clone() as IPoint;

                    if (TransectFC.FindField("PROJTD_X2") > -1)
                        InsertBuffer.set_Value(TransectFC.FindField("PROJTD_X2"), TempPoint.X);

                    if (TransectFC.FindField("PROJTD_Y2") > -1)
                        InsertBuffer.set_Value(TransectFC.FindField("PROJTD_Y2"), TempPoint.Y);

                    //project transect to point to geo coordinates and save coords in transect fields
                    ((IGeometry2)TempPoint).ProjectEx(Util.GetWGSSpatRef(),
                        esriTransformDirection.esriTransformForward, null, false, 0, 0);

                    if (TransectFC.FindField("DD_LONG2") > -1)
                        InsertBuffer.set_Value(TransectFC.FindField("DD_LONG2"), TempPoint.X);

                    if (TransectFC.FindField("DD_LAT2") > -1)
                        InsertBuffer.set_Value(TransectFC.FindField("DD_LAT2"), TempPoint.Y);

                    if (TrnsectElevValFieldIndex > -1 && ElevValFieldIndex > -1)
                        InsertBuffer.set_Value(TrnsectElevValFieldIndex, RandPntFeature.get_Value(ElevValFieldIndex));

                    if (TrnsectElevValFTFieldIndex > -1 && ElevValFTFieldIndex > -1)
                        InsertBuffer.set_Value(TrnsectElevValFTFieldIndex, RandPntFeature.get_Value(ElevValFTFieldIndex));

                    //add new feature to feature class
                    InsertCursor.InsertFeature(InsertBuffer);

                    TransectCount++;
                }
                else
                {
                    //update random point fields
                    if (AcceptedFieldIndex > -1) RandPntFeature.set_Value(AcceptedFieldIndex, "N");
                }

                Util.SetProgressMessage(string.Format("Generating Transects (Straight:{0}, Contour:{1}, Failed:{2}, Corrupted:{3})",
                    StraightCount, ContourCount, FailCount, CorruptCount), false);

                RandPntCursor.UpdateFeature(RandPntFeature);

            }

            InsertCursor = null;
            RandPntCursor = null;
        }
Esempio n. 52
0
        /// <summary>
        /// generate exlcuded area polygons for the specified survey and elevation
        /// </summary>
        public static void GenerateExcludedAreasPolygons(int SurveyID, int MaximumElevInFeet, bool IsAboveElevation,
            IGeoDataset ClippedRasterDS, ref string ErrorMessage)
        {
            ESRI.ArcGIS.SpatialAnalyst.IMathOp ThisMathOp;
            IGeoDataset IntRasterDS = null;
            IQueryFilter ThisQueryFilter;
            ESRI.ArcGIS.GeoAnalyst.IRasterDescriptor ThisRasterDescriptor;
            ESRI.ArcGIS.Geoprocessing.IGeoProcessorResult GeoResult = null;
            ESRI.ArcGIS.Geoprocessing.IGeoProcessor ThisGeoProcessor = null;
            ESRI.ArcGIS.esriSystem.IVariantArray GPParams;
            IFeatureClass NewElvPolyFC, BoundaryFC, ElvPolyFC;
            ESRI.ArcGIS.GeoAnalyst.IConversionOp ThisConversionOp;
            string TempElvFCName, TempAggFCName, InternalErrors = "", TempClipFCName;
            IFeatureBuffer InsertBuffer;
            IFeatureCursor InsertCursor, TempCursor;
            IFeature TempFeature;
            int ShapeAreaIndex;
            double CurrentShapeArea, MaxShapeArea;
            int SurveyIDIndex;
            NPSGlobal NPS;

            NPS = NPSGlobal.Instance;
            TempElvFCName = "NPS_TEMP_TempElvPolyFCName";
            TempAggFCName = "NPS_TEMP_TempElevationFC";
            TempClipFCName = "NPS_TEMP_TempClipFCName";

            ElvPolyFC = Util.GetFeatureClass(NPS.LYR_EXCLUDED_AREAS, ref ErrorMessage);
            if (string.IsNullOrEmpty(ErrorMessage) == false) return;

            BoundaryFC = Util.GetFeatureClass(NPS.LYR_SURVEY_BOUNDARY, ref ErrorMessage);
            if (string.IsNullOrEmpty(ErrorMessage) == false) return;

            SurveyIDIndex = ElvPolyFC.FindField("SurveyID");
            if (SurveyIDIndex == -1)
            {
                ErrorMessage = "Could not find the SurveyID field on the Excluded Areas FeatureClass.";
                return;
            }

            Util.SetProgressMessage("Deleting old temp files");
            Util.DeleteDataset(TempElvFCName, esriDatasetType.esriDTFeatureClass, ref InternalErrors);
            Util.DeleteDataset(TempClipFCName, esriDatasetType.esriDTFeatureClass, ref InternalErrors);
            Util.DeleteDataset(TempAggFCName, esriDatasetType.esriDTFeatureClass, ref InternalErrors);
            Util.DeleteDataset(TempClipFCName + "_Tbl", esriDatasetType.esriDTTable, ref InternalErrors);
            Util.DeleteDataset(TempAggFCName + "_Tbl", esriDatasetType.esriDTTable, ref InternalErrors);

            try
            {
                Util.SetProgressMessage("Converting DEM values to integers");

                ThisMathOp = new ESRI.ArcGIS.SpatialAnalyst.RasterMathOpsClass();
                IntRasterDS = ThisMathOp.Int(ClippedRasterDS);
            }
            catch (Exception ex)
            {
                ErrorMessage = "Error occured while converting DEM float slope values to slope integer values. " + ex.Message;
                return;
            }

            try
            {
                Util.SetProgressMessage("Building excluded area polygons from DEM");

                //determine which values to exclude
                ThisQueryFilter = new QueryFilterClass();

                if (IsAboveElevation)
                    ThisQueryFilter.WhereClause = " Value >= " + MaximumElevInFeet;
                else
                    ThisQueryFilter.WhereClause = " Value <= " + MaximumElevInFeet;

                ThisRasterDescriptor = new ESRI.ArcGIS.GeoAnalyst.RasterDescriptorClass();
                ThisRasterDescriptor.Create(IntRasterDS as IRaster, ThisQueryFilter, "Value");

                ThisConversionOp = new ESRI.ArcGIS.GeoAnalyst.RasterConversionOpClass();
                NewElvPolyFC = ThisConversionOp.RasterDataToPolygonFeatureData(ThisRasterDescriptor as IGeoDataset,
                    NPS.Workspace, TempElvFCName, true) as IFeatureClass;
            }
            catch (Exception ex)
            {
                ErrorMessage = "Error occured while generating a FeatureClass of flat "
                + "areas from the default DEM file. " + ex.Message;
                return;
            }

            try
            {
                Util.SetProgressMessage("Aggregating excluded area polygons");

                ThisGeoProcessor = new ESRI.ArcGIS.Geoprocessing.GeoProcessor();
                GPParams = new ESRI.ArcGIS.esriSystem.VarArrayClass();

                GPParams.Add(System.IO.Path.Combine(NPS.DatabasePath, TempElvFCName));
                GPParams.Add(System.IO.Path.Combine(NPS.DatabasePath, TempAggFCName));
                GPParams.Add("1 Meters");

                GeoResult = ThisGeoProcessor.Execute("AggregatePolygons_management", GPParams, null);
            }
            catch (Exception ex)
            {
                ErrorMessage = string.Format("Geoprocessor error:\r\nTask:AggregatePolygons_management\r\n"
                    + "Params:{0},{1},{2}\r\nException:{3}", System.IO.Path.Combine(NPS.DatabasePath, TempElvFCName),
                    System.IO.Path.Combine(NPS.DatabasePath, TempAggFCName), "1 Meters", ex.Message);
                ThisGeoProcessor = null;
                return;
            }

            ThisGeoProcessor = null;

            Util.DeleteLayerFromMap(TempAggFCName);

            NewElvPolyFC = Util.GetFeatureClass(TempAggFCName, ref ErrorMessage);
            if (string.IsNullOrEmpty(ErrorMessage) == false)
            {
                ErrorMessage = "Could not find temporary FeatureClass " + TempAggFCName + ". " + ErrorMessage;
                return;
            }

            Util.SetProgressMessage("Validating excluded area polygons");

            NewElvPolyFC = Util.GP_Clip_analysis(TempClipFCName, NewElvPolyFC, BoundaryFC, ref ErrorMessage);
            if (string.IsNullOrEmpty(ErrorMessage) == false) return;

            InsertBuffer = ElvPolyFC.CreateFeatureBuffer();
            InsertCursor = ElvPolyFC.Insert(true);

            ThisQueryFilter = null;
            ThisQueryFilter = new QueryFilterClass();
            TempCursor = NewElvPolyFC.Search(ThisQueryFilter, false);

            ShapeAreaIndex = NewElvPolyFC.FindField(NewElvPolyFC.AreaField.Name);

            MaxShapeArea = (double)Util.SafeConvert(Util.GetFirstRecordValue(BoundaryFC,
                BoundaryFC.AreaField.Name, "SurveyID=" + SurveyID), typeof(double));

            Util.SetProgressMessage("Importing excluded area polygons to Survey");

            while ((TempFeature = TempCursor.NextFeature()) != null)
            {
                if (TempFeature.Shape == null) continue;

                CurrentShapeArea = (double)Util.SafeConvert(TempFeature.get_Value(ShapeAreaIndex), typeof(double));
                if ((CurrentShapeArea / MaxShapeArea) >= 0.95) continue;

                InsertBuffer.Shape = TempFeature.ShapeCopy;
                InsertBuffer.set_Value(SurveyIDIndex, SurveyID);

                InsertCursor.InsertFeature(InsertBuffer);
            }

            TempCursor = null;
            InsertCursor = null;

            Util.SetProgressMessage("Cleaning up temp files");
            Util.DeleteDataset(TempElvFCName, esriDatasetType.esriDTFeatureClass, ref InternalErrors);
            Util.DeleteDataset(TempClipFCName, esriDatasetType.esriDTFeatureClass, ref InternalErrors);
            Util.DeleteDataset(TempAggFCName, esriDatasetType.esriDTFeatureClass, ref InternalErrors);
            Util.DeleteDataset(TempClipFCName + "_Tbl", esriDatasetType.esriDTTable, ref InternalErrors);
            Util.DeleteDataset(TempAggFCName + "_Tbl", esriDatasetType.esriDTTable, ref InternalErrors);

            Util.CreateFillerPolygon(ElvPolyFC, SurveyID, ref InternalErrors);
        }
Esempio n. 53
0
        /// <summary>
        /// create a contour transect from a source point
        /// </summary>
        public static IPolyline GetContourLineFromPoint(IPoint npsPoint, double MaxLineLength, double MinLineLength,
            IGeoDataset npsDemDataset, int SurveyID, IFeatureClass BndPolyFC, IFeatureClass ExclPolyFC)
        {
            ESRI.ArcGIS.GeoAnalyst.ISurfaceOp2 npsSurfaceOp;
            IPolyline npsPolyline, npsClippedPolyline, PrevTryPolyline = null;
            bool DidMaxLengthFit, IsInBndPoly, IsInExcludedAreas;
            int LengthAttempts;
            double CurTransLength, LengthTryIncrements, ElevValue;

            //determine a set number of times to try generating intermidiate lengths in both min and max
            //lengths were successful
            LengthAttempts = 20;
            LengthTryIncrements = (MaxLineLength - MinLineLength) / LengthAttempts;

            //create a polyline from the elevation for the random point
            npsSurfaceOp = new ESRI.ArcGIS.GeoAnalyst.RasterSurfaceOpClass();
            npsPolyline = new PolylineClass();
            npsSurfaceOp.ContourAsPolyline(npsDemDataset, npsPoint, out npsPolyline, out ElevValue);
            npsSurfaceOp = null;
            GC.Collect();

            if (npsPolyline == null) return null;

            DidMaxLengthFit = false;

            //try to cut the contour into the max length specified
            npsClippedPolyline = Util.ClipContour(npsPoint, npsPolyline, (MaxLineLength / 2), (MaxLineLength / 2));

            IsInBndPoly = false;
            IsInExcludedAreas = false;

            if (npsClippedPolyline != null)
            {

                //check if contour is within boundary
                IsInBndPoly = Util.HasRelationshipWithFC(npsClippedPolyline as IGeometry,
                    esriSpatialRelEnum.esriSpatialRelWithin, BndPolyFC, "SurveyID=" + SurveyID);

                //check if contour falls in excluded areas
                IsInExcludedAreas = Util.HasRelationshipWithFC(npsClippedPolyline as IGeometry,
                    esriSpatialRelEnum.esriSpatialRelCrosses, ExclPolyFC, "SurveyID=" + SurveyID);
            }

            //if contour obtained falls in excluded areas, abandon poyline
            if (IsInBndPoly == false || IsInExcludedAreas == true) npsClippedPolyline = null;

            //remember if max length fit
            if (npsClippedPolyline != null) DidMaxLengthFit = true;

            //if the max length did not fit, try the min length
            if (npsClippedPolyline == null)
                npsClippedPolyline = Util.ClipContour(npsPoint, npsPolyline, (MinLineLength / 2), (MinLineLength / 2));

            //check if the shortest length can fit
            if (npsClippedPolyline != null)
            {

                //check if contour is within boundary
                IsInBndPoly = Util.HasRelationshipWithFC(npsClippedPolyline as IGeometry,
                    esriSpatialRelEnum.esriSpatialRelWithin, BndPolyFC, "SurveyID=" + SurveyID);

                //check if contour falls in excluded areas
                IsInExcludedAreas = Util.HasRelationshipWithFC(npsClippedPolyline as IGeometry,
                    esriSpatialRelEnum.esriSpatialRelCrosses, ExclPolyFC, "SurveyID=" + SurveyID);
            }

            //if the min failed then clear it
            if (IsInBndPoly == false || IsInExcludedAreas == true) npsClippedPolyline = null;

            //if the max length failed but the min length fit, then try various lengths
            if (npsClippedPolyline != null && DidMaxLengthFit == false)
            {

                CurTransLength = (MinLineLength / 2) + LengthTryIncrements;
                while (npsClippedPolyline != null)
                {

                    PrevTryPolyline = npsClippedPolyline;
                    npsClippedPolyline = Util.ClipContour(npsPoint, npsPolyline, CurTransLength, CurTransLength);

                    IsInBndPoly = false;
                    IsInExcludedAreas = false;

                    if (npsClippedPolyline != null)
                    {
                        //check if contour is within boundary
                        IsInBndPoly = Util.HasRelationshipWithFC(npsClippedPolyline as IGeometry,
                            esriSpatialRelEnum.esriSpatialRelWithin, BndPolyFC, "SurveyID=" + SurveyID);

                        //check if contour falls in excluded areas
                        IsInExcludedAreas = Util.HasRelationshipWithFC(npsClippedPolyline as IGeometry,
                            esriSpatialRelEnum.esriSpatialRelCrosses, ExclPolyFC, "SurveyID=" + SurveyID);
                    }

                    //if contour obtained falls in excluded areas, abandon poyline
                    if (IsInBndPoly == false || IsInExcludedAreas == true) npsClippedPolyline = null;

                    CurTransLength = CurTransLength + LengthTryIncrements;

                }

                //set the last successful as the clipped polyline
                npsClippedPolyline = PrevTryPolyline;

            }

            return npsClippedPolyline;
        }
Esempio n. 54
0
        public IGeoDataset CreateExtractOp(IGeoDataset pGeoDataset, ESRI.ArcGIS.Geometry.IPolygon pPolygone)
        {
            ESRI.ArcGIS.SpatialAnalyst.IExtractionOp pExtractionOp = new ESRI.ArcGIS.SpatialAnalyst.RasterExtractionOpClass();

                 ESRI.ArcGIS.Geodatabase.IGeoDataset pGeoOutput = pExtractionOp.Polygon(pGeoDataset, pPolygone, true);

                 return pGeoOutput;
        }
Esempio n. 55
0
        /// <summary>
        /// generate flatarea poylgons for the specified survey using the specified raster
        /// </summary>
        public static void GenerateFlatAreaPolygons(int SurveyID, double MinSlope, double MaxSlope,
            IGeoDataset ClippedRasterDS, ref string ErrorMessage)
        {
            ESRI.ArcGIS.Geoprocessing.IGeoProcessorResult GeoResult = null;
            ESRI.ArcGIS.Geoprocessing.IGeoProcessor ThisGeoProcessor = null;
            ESRI.ArcGIS.GeoAnalyst.IRasterDescriptor ThisRasterDescriptor;
            ESRI.ArcGIS.GeoAnalyst.IConversionOp ThisConversionOp;
            IGeoDataset FloatRasterDS = null, IntRasterDS = null;
            ESRI.ArcGIS.esriSystem.IVariantArray GPParams;
            ESRI.ArcGIS.GeoAnalyst.ISurfaceOp ThisSurfaceOp;
            ESRI.ArcGIS.SpatialAnalyst.IMathOp ThisMathOp;
            IFeatureClass TempFlatAreasPolyFC = null, TempAggregateFC = null,
                TempAggregateClipFC = null, BoundaryFC = null, FlatAreasFC = null;
            IQueryFilter ThisQueryFilter;
            IFeatureCursor FlatAreasCursor, TempAggregateClipCursor;
            IFeatureBuffer FlatAreasFBuffer;
            IFeature TempAggregateClipFeature;
            string TempFlatAreasPolyFCName, TempAggregateFCName, InternalErrors = "", TempClipFCName;
            object zFactor;
            NPSGlobal NPS;
            int SurveyIDIndex;

            TempClipFCName = "NPS_TEMP_ClippedFC";
            TempAggregateFCName = "NPS_TEMP_FlatAreasAggrFC";
            TempFlatAreasPolyFCName = "NPS_TEMP_FlatAreasFC";
            NPS = NPSGlobal.Instance;
            zFactor = 1;

            BoundaryFC = Util.GetFeatureClass(NPS.LYR_SURVEY_BOUNDARY, ref ErrorMessage);
            if (string.IsNullOrEmpty(ErrorMessage) == false) return;

            FlatAreasFC = Util.GetFeatureClass(NPS.LYR_FLAT_AREAS, ref ErrorMessage);
            if (string.IsNullOrEmpty(ErrorMessage) == false) return;

            SurveyIDIndex = FlatAreasFC.FindField("SurveyID");
            if (SurveyIDIndex == -1)
            {
                ErrorMessage = "Could not find a SurveyID field on the " + ((IDataset)FlatAreasFC).Name + " FeatureClass.";
                return;
            }

            Util.SetProgressMessage("Deleting old temp files");
            Util.DeleteDataset(TempFlatAreasPolyFCName, esriDatasetType.esriDTFeatureClass, ref InternalErrors);
            Util.DeleteDataset(TempAggregateFCName, esriDatasetType.esriDTFeatureClass, ref InternalErrors);
            Util.DeleteDataset(TempClipFCName, esriDatasetType.esriDTFeatureClass, ref InternalErrors);
            Util.DeleteDataset(TempAggregateFCName + "_Tbl", esriDatasetType.esriDTTable, ref InternalErrors);
            Util.DeleteDataset(TempClipFCName + "_Tbl", esriDatasetType.esriDTTable, ref InternalErrors);

            ThisSurfaceOp = new ESRI.ArcGIS.GeoAnalyst.RasterSurfaceOpClass();

            try
            {
                Util.SetProgressMessage("Computing slope values from DEM");

                FloatRasterDS = ThisSurfaceOp.Slope(ClippedRasterDS,
                    ESRI.ArcGIS.GeoAnalyst.esriGeoAnalysisSlopeEnum.esriGeoAnalysisSlopeDegrees, ref zFactor);
            }
            catch (Exception ex)
            {
                ErrorMessage = "Error occured while converting DEM evelation values to float slope values. " + ex.Message;
                return;
            }

            try
            {
                Util.SetProgressMessage("Converting DEM values to integers");

                ThisMathOp = new ESRI.ArcGIS.SpatialAnalyst.RasterMathOpsClass();
                IntRasterDS = ThisMathOp.Int(FloatRasterDS);
            }
            catch (Exception ex)
            {
                ErrorMessage = "Error occured while converting DEM float slope values to slope integer values. " + ex.Message;
                return;
            }

            try
            {
                Util.SetProgressMessage("Building flat area polygons from DEM");

                ThisQueryFilter = new QueryFilterClass();
                ThisQueryFilter.WhereClause = " Value >= " + MinSlope + " AND Value <= " + MaxSlope;

                ThisRasterDescriptor = new ESRI.ArcGIS.GeoAnalyst.RasterDescriptorClass();
                ThisRasterDescriptor.Create(IntRasterDS as IRaster, ThisQueryFilter, "Value");

                ThisConversionOp = new ESRI.ArcGIS.GeoAnalyst.RasterConversionOpClass();
                TempFlatAreasPolyFC = ThisConversionOp.RasterDataToPolygonFeatureData(ThisRasterDescriptor as IGeoDataset,
                    NPS.Workspace, TempFlatAreasPolyFCName, true) as IFeatureClass;
            }
            catch (Exception ex)
            {
                ErrorMessage = "Error occured while generating a FeatureClass of flat "
                + "areas from the default DEM file. " + ex.Message;
                return;
            }

            try
            {
                Util.SetProgressMessage("Aggregating flat area polygons");

                ThisGeoProcessor = new ESRI.ArcGIS.Geoprocessing.GeoProcessor();
                GPParams = new ESRI.ArcGIS.esriSystem.VarArrayClass();

                GPParams.Add(System.IO.Path.Combine(NPS.DatabasePath, TempFlatAreasPolyFCName));
                GPParams.Add(System.IO.Path.Combine(NPS.DatabasePath, TempAggregateFCName));
                GPParams.Add("1 Meters");

                GeoResult = ThisGeoProcessor.Execute("AggregatePolygons_management", GPParams, null);
            }
            catch (Exception ex)
            {
                ErrorMessage = string.Format("Geoprocessor error:\r\nTask:AggregatePolygons_management\r\n"
                    + "Params:{0},{1},{2}\r\nException:{3}", System.IO.Path.Combine(NPS.DatabasePath, TempFlatAreasPolyFCName),
                    System.IO.Path.Combine(NPS.DatabasePath, TempAggregateFCName), "1 Meters", ex.Message);
                ThisGeoProcessor = null;
                return;
            }

            ThisGeoProcessor = null;

            Util.DeleteLayerFromMap(TempAggregateFCName);

            TempAggregateFC = Util.GetFeatureClass(TempAggregateFCName, ref ErrorMessage);
            if (string.IsNullOrEmpty(ErrorMessage) == false)
            {
                ErrorMessage = "Could not find temporary FeatureClass " + TempAggregateFCName + ". " + ErrorMessage;
                return;
            }

            Util.SetProgressMessage("Validating flat area polygons");

            TempAggregateClipFC = Util.GP_Clip_analysis(TempClipFCName, TempAggregateFC, BoundaryFC, ref ErrorMessage);
            if (string.IsNullOrEmpty(ErrorMessage) == false) return;

            FlatAreasFBuffer = FlatAreasFC.CreateFeatureBuffer();
            FlatAreasCursor = FlatAreasFC.Insert(true);

            ThisQueryFilter = null;
            ThisQueryFilter = new QueryFilterClass();
            ThisQueryFilter.WhereClause = "SHAPE_AREA > 25000";
            TempAggregateClipCursor = TempAggregateClipFC.Search(ThisQueryFilter, false);

            Util.SetProgressMessage("Importing flat area polygons to Survey");

            while ((TempAggregateClipFeature = TempAggregateClipCursor.NextFeature()) != null)
            {
                if (TempAggregateClipFeature.Shape == null) continue;

                FlatAreasFBuffer.Shape = TempAggregateClipFeature.ShapeCopy;
                FlatAreasFBuffer.set_Value(SurveyIDIndex, SurveyID);

                FlatAreasCursor.InsertFeature(FlatAreasFBuffer);
            }

            TempAggregateClipCursor = null;
            FlatAreasCursor = null;

            Util.SetProgressMessage("Cleaning up temp files");
            Util.DeleteDataset(TempFlatAreasPolyFCName, esriDatasetType.esriDTFeatureClass, ref InternalErrors);
            Util.DeleteDataset(TempAggregateFCName, esriDatasetType.esriDTFeatureClass, ref InternalErrors);
            Util.DeleteDataset(TempClipFCName, esriDatasetType.esriDTFeatureClass, ref InternalErrors);
            Util.DeleteDataset(TempAggregateFCName + "_Tbl", esriDatasetType.esriDTTable, ref InternalErrors);
            Util.DeleteDataset(TempClipFCName + "_Tbl", esriDatasetType.esriDTTable, ref InternalErrors);

            Util.CreateFillerPolygon(FlatAreasFC, SurveyID, ref InternalErrors);
        }
Esempio n. 56
0
        public IGeoDataset CreateDistanceOpCostPathRaster(IGeoDataset pGeoDataset1, IGeoDataset pGeoDataset2, IGeoDataset pGeoDataset3)
        {
            IDistanceOp pDistanceOp = new RasterDistanceOpClass();

             IGeoDataset pGeoDatasetOutput = pDistanceOp.CostPath(pGeoDataset1, pGeoDataset2, pGeoDataset3, esriGeoAnalysisPathEnum.esriGeoAnalysisPathForEachZone);

             return pGeoDatasetOutput;
        }
Esempio n. 57
0
        /// <summary>
        /// 邻域分析
        /// </summary>
        /// <param name="GeoDataset"></param>
        /// <returns></returns>
        public IGeoDataset CreateNeighborhoodOpBlockStatisticsRaster(IGeoDataset GeoDataset)
        {
            INeighborhoodOp pNeighborhoodOP = new RasterNeighborhoodOpClass();

                 IRasterNeighborhood pRasterNeighborhood = new RasterNeighborhoodClass();

                 pRasterNeighborhood.SetRectangle(3, 3, esriGeoAnalysisUnitsEnum.esriUnitsCells);

                 IGeoDataset pGeoOutput = pNeighborhoodOP.BlockStatistics(GeoDataset,esriGeoAnalysisStatisticsEnum.esriGeoAnalysisStatsMean, pRasterNeighborhood, true);

                 return pGeoOutput;
        }