コード例 #1
2
        private static void SelectFeaturesAndRunCopyFeatures()
        {
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////
            // STEP 1: Make feature layers using the MakeFeatureLayer tool for the inputs to the SelectByLocation tool.
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////

            // Initialize the Geoprocessor 
            Geoprocessor GP = new Geoprocessor();

            // Initialize the MakeFeatureLayer tool
            MakeFeatureLayer makefeaturelayer = new MakeFeatureLayer();
            makefeaturelayer.in_features = @"C:\data\nfld.gdb\wells";
            makefeaturelayer.out_layer = "Wells_Lyr";
            RunTool(GP, makefeaturelayer, null);

            makefeaturelayer.in_features = @"C:\data\nfld.gdb\bedrock";
            makefeaturelayer.out_layer = "bedrock_Lyr";
            RunTool(GP, makefeaturelayer, null);

            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // STEP 2: Execute SelectLayerByLocation using the feature layers to select all wells that intersect the bedrock geology.
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

            // Initialize the SelectLayerByLocation tool
            SelectLayerByLocation SelectByLocation = new SelectLayerByLocation();

            SelectByLocation.in_layer = "Wells_Lyr";
            SelectByLocation.select_features = "bedrock_Lyr";
            SelectByLocation.overlap_type = "INTERSECT";
            RunTool(GP, SelectByLocation, null);

            /////////////////////////////////////////////////////////////////////////////////////////////////
            // STEP 3: Execute SelectLayerByAttribute to select all wells that have a well yield > 150 L/min.
            /////////////////////////////////////////////////////////////////////////////////////////////////

            // Initialize the SelectLayerByAttribute tool
            SelectLayerByAttribute SelectByAttribute = new SelectLayerByAttribute();

            SelectByAttribute.in_layer_or_view = "Wells_Lyr";
            SelectByAttribute.selection_type = "NEW_SELECTION";
            SelectByAttribute.where_clause = "WELL_YIELD > 150";
            RunTool(GP, SelectByAttribute, null);

            ////////////////////////////////////////////////////////////////////////////////////////////////////////
            // STEP 4: Execute CopyFeatures tool to create a new feature class of wells with well yield > 150 L/min.
            ////////////////////////////////////////////////////////////////////////////////////////////////////////

            // Initialize the CopyFeatures tool
            CopyFeatures CopyFeatures = new CopyFeatures();

            CopyFeatures.in_features = "Wells_Lyr";
            CopyFeatures.out_feature_class = @"C:\data\nfld.gdb\high_yield_wells";


            RunTool(GP, CopyFeatures, null);
        }
コード例 #2
0
        public FeatureLayerChangeVersion()
        {
            InitializeComponent();

            featureLayer = (MyMap.Layers["ServiceConnections"] as FeatureLayer);

            Geoprocessor gp_ListVersions = new Geoprocessor("http://sampleserver6.arcgisonline.com/arcgis/rest/services/GDBVersions/GPServer/ListVersions");

            gp_ListVersions.Failed += (s, a) =>
            {
                MessageBox.Show("Geoprocessing service failed: " + a.Error);
            };

            gp_ListVersions.ExecuteCompleted += (c, d) =>
            {
                VersionsCombo.DataContext = (d.Results.OutParameters[0] as GPRecordSet).FeatureSet;

                foreach (Graphic g in (d.Results.OutParameters[0] as GPRecordSet).FeatureSet.Features)
                {
                    if ((g.Attributes["name"] as string) == featureLayer.GdbVersion)
                    {
                        VersionsCombo.SelectedValue = g;
                        break;
                    }
                }
            };

            List<GPParameter> gpparams = new List<GPParameter>();
            gpparams.Add(new GPRecordSet("Versions", new FeatureSet()));
            gp_ListVersions.ExecuteAsync(gpparams);
        }
コード例 #3
0
ファイル: SiteSelector.cs プロジェクト: wingzhangmaybe/CGXM
        private void Init(AxMapControl mc, int programID)
        {
            gp = new Geoprocessor();
            mapControl = mc;
            UpdateMapLayerNameList(mapLayerNameList, mapControl);
            program = new Program();
            program.id = programID;
            program.select();
            project = new Project();
            project.id = program.projectID;
            project.select();
            netSize = program.getRelatedNetSize();
            conditionList = program.getAllRelatedCondition();
            baseFeature = GisUtil.GetBaseFeature(mapControl, project.baseMapIndex);
            mapFolder = System.IO.Path.GetDirectoryName(project.path);
            targetFolder = generateFolder(mapFolder);
            foreach (Condition condition in conditionList)
            {
                if (condition.type == C.CONFIG_TYPE_STANDARD)
                {
                    totalStandardValue += condition.value;
                }
            }
            fishnetPolygonName = "polygon.shp";
            fishnetName = "fishnet.shp";
            fishnetWidth = netSize.width;
            fishnetHeight = netSize.height;

            featureList = new List<Feature>();
        }
        public ViewShedToolViewModel()
        {
            StartViewShedCommand = new RelayCommand(OnStartViewShedCommand);
            CloseViewShedCommand = new RelayCommand(OnCloseViewShedCommand);

            _gpTask = new Geoprocessor(new Uri(ViewshedServiceUrl));
        }
コード例 #5
0
        public static void ClipRaster(string inRaster, string inClipFeature, string outTempRaster)
        {
            Clip clipTool = new Clip();

            //set clip parameters
            clipTool.in_raster = inRaster;
            clipTool.out_raster = outTempRaster;

            //clip extent
            clipTool.in_template_dataset = inClipFeature;

            Geoprocessor gp = new Geoprocessor();
            gp.OverwriteOutput = true;
            gp.AddOutputsToMap = false;

            try
            {

               IGeoProcessorResult result = (IGeoProcessorResult)gp.ExecuteAsync(clipTool);

               while(result.Status != esriJobStatus.esriJobSucceeded)
               {
                   //Console.WriteLine(result.Status.ToString());
                   System.Threading.Thread.Sleep(100);
               }

            }
            catch (Exception ex)
            {
                object level = 0;
                Console.WriteLine(gp.GetMessages(ref level));
                Console.WriteLine(" Failed to clip raster using ESRI clip tool " + ex.Message);
            }
        }
コード例 #6
0
ファイル: MapInfo2MDB.cs プロジェクト: hy1314200/HyDM
        /// <summary>
        /// mapinfo格式转mdb(包括mif,tab)
        /// </summary>
        /// <param name="strMapInfoFilePath">mapinfo数据所在的文件夹(批量转换)或者mapinfo数据文件路径(单个转换)</param>
        /// <param name="strMDBPath">输出mdb的完整路径</param>
        /// <returns></returns>
        private bool MapInfoToMDB(string strMapInfoFilePath,string strMDBPath)
        {
            try
            {
                if (strMapInfoFilePath == "" || strMDBPath == "")
                    return false;

                Geoprocessor geoprocessor = new Geoprocessor();
                QuickImport conversion = new QuickImport();
                //有扩展名,表示为单个文件
                if (System.IO.Path.HasExtension(strMapInfoFilePath))
                {
                    conversion.Input = strMapInfoFilePath;
                }
                else
                {
                    //否则为批量文件
                    conversion.Input = "MAPINFO," + strMapInfoFilePath + "\\*.*,\"RUNTIME_MACROS,\"\"FME_TABLE_PASSWORD,,_MERGE_SCHEMAS,YES\"\",META_MACROS,\"\"SourceFME_TABLE_PASSWORD,\"\",METAFILE,MAPINFO,COORDSYS,,IDLIST,,__FME_DATASET_IS_SOURCE__,true\"";
                }

                conversion.Output = strMDBPath;
                return RunTool(geoprocessor, conversion, null);
            }
            catch (Exception ex)
            {
                On_ProgressFinish(this, "转换过程中出现异常,转换结束,错误原因:" + ex.Message);
            }
            return false;
        }
コード例 #7
0
ファイル: GExtractTool.cs プロジェクト: truonghinh/TnX
        void IClip.ClipByLayerFileInsideSde(object in_feature, string in_layer_file_path, object clip_feature, string clip_layer_file_path, string out_feature)
        {
            using (ComReleaser releaser = new ComReleaser())
            {
                try
                {
                    Geoprocessor gp = new Geoprocessor();
                    IDataManager _dataManager = new DataManager(this._environment);
                    ESRI.ArcGIS.AnalysisTools.Clip clipTool = new ESRI.ArcGIS.AnalysisTools.Clip();

                    //releaser.ManageLifetime(gp);
                    //releaser.ManageLifetime(clipTool);
                    //IVariantArray param = new VarArrayClass();

                    string inlayer = string.Format("{0}.lyr", in_layer_file_path);
                    string cliplayer = string.Format("{0}.lyr", clip_layer_file_path);
                    //MessageBox.Show(string.Format("line 61 GExtractTool in={0}, clip={1}", inlayer, cliplayer));
                    _dataManager.SaveToLayerFile((ILayer)in_feature, inlayer);
                    _dataManager.SaveToLayerFile((ILayer)clip_feature, cliplayer);

                    //MessageBox.Show(((IFeatureLayer)in_feature).FeatureClass.AliasName);
                    gp.SetEnvironmentValue("workspace", this._environment);
                    clipTool.in_features = inlayer;
                    clipTool.clip_features = cliplayer;
                    clipTool.out_feature_class = out_feature;//string.Format("{0}{1}", this._temFullPath, out_feature);//"C:\\tayninh\\temp\\tempmdb.mdb\\" + out_feature;

                    runTool(gp, clipTool, null);
                }
                catch (Exception err) { MessageBox.Show("loi clip: " + err.ToString()); }
            }
        }
コード例 #8
0
ファイル: ClipLayer.cs プロジェクト: chinasio/minegis
        /// <summary>
        /// 两图层进行裁剪运算
        /// </summary>
        /// <param name="inputLayer">被裁剪图层</param>
        /// <param name="clipLayer">裁剪图层</param>
        /// <param name="outputFullPath">输出图层完整路径</param>
        public void ClipByLayer(ILayer inputLayer, ILayer clipLayer, string outputFullPath)
        {
            string inputPath = GetLayerPath(inputLayer);
            string clipPath = GetLayerPath(clipLayer);

            Clip clipTool = new Clip();
            clipTool.in_features = inputPath;
            clipTool.clip_features = clipPath;
            clipTool.out_feature_class = outputFullPath;

            Geoprocessor processor = new Geoprocessor();
            IGPProcess process = null;
            processor.OverwriteOutput = true;
            process = clipTool;
            processor.Validate(process, true);
            processor.Execute(process, null);

            FileInfo fi = new FileInfo(outputFullPath);
            string pathDir = fi.Directory.FullName;
            string name = fi.Name;
            IWorkspaceFactory wsf = new ShapefileWorkspaceFactoryClass();
            IFeatureWorkspace fws = wsf.OpenFromFile(pathDir, 0) as IFeatureWorkspace;
            IFeatureClass featCls = fws.OpenFeatureClass(name);
            IFeatureLayer layer = new FeatureLayerClass();
            layer.FeatureClass = featCls;
            layer.Name = featCls.AliasName;
            m_mapControl.Map.AddLayer(layer as ILayer);
        }
        //执行计算,输出计算结果信息字符串
        private string FieldCal(IFeatureLayer pFtLayer, string strExpression)
        {
            txtMessage.Text = "正在计算请稍后……\r\n";
            try
            {
                Geoprocessor Gp = new Geoprocessor();
                Gp.OverwriteOutput = true;
                CalculateField calField = new CalculateField();
                
                calField.expression = strExpression;

                Gp.Execute(calField, null);

                for (int i = 0; i < Gp.MessageCount; i++)
                {
                    txtMessage.Text += Gp.GetMessage(i).ToString() + "\r\n";
                }
                return "计算成功";
            }
            catch (Exception e)
            {
                txtMessage.Text += e.Message;
                return "计算失败" + e.Message;
            }
        }
コード例 #10
0
        public DriveTimes()
        {
            InitializeComponent();

            graphicsLayer = MyMap.Layers["MyGraphicsLayer"] as GraphicsLayer;

            bufferSymbols = new List<FillSymbol>(
                    new FillSymbol[] { LayoutRoot.Resources["FillSymbol1"] as FillSymbol,
                        LayoutRoot.Resources["FillSymbol2"] as FillSymbol,
                        LayoutRoot.Resources["FillSymbol3"] as FillSymbol });

            _geoprocessorTask = new Geoprocessor("http://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/GPServer/Generate%20Service%20Areas");
            _geoprocessorTask.JobCompleted += GeoprocessorTask_JobCompleted;
            _geoprocessorTask.StatusUpdated += GeoprocessorTask_StatusUpdated;
            _geoprocessorTask.GetResultDataCompleted += GeoprocessorTask_GetResultDataCompleted;
            _geoprocessorTask.Failed += GeoprocessorTask_Failed;

            MyDrawObject = new Draw(MyMap)
            {
                IsEnabled = true,
                DrawMode = DrawMode.Point
            };

            MyDrawObject.DrawComplete += MyDrawObject_DrawComplete;
        }
コード例 #11
0
 public ViewShed()
 {
     InitializeComponent();
       _geoprocessorTask = new Geoprocessor("http://serverapps101.esri.com/arcgis/rest/services/ProbabilisticViewshedModel/GPServer/ProbabilisticViewshedModel");
       _geoprocessorTask.JobCompleted += GeoprocessorTask_JobCompleted;
       _geoprocessorTask.Failed += GeoprocessorTask_Failed;
       graphicsLayer = MyMap.Layers["MyGraphicsLayer"] as GraphicsLayer;
 }
コード例 #12
0
ファイル: DataManager.cs プロジェクト: truonghinh/TnX
 void IAppend.Append(IFeatureClass fcSource, IFeatureClass fcTarget)
 {
     Geoprocessor gp = new Geoprocessor();
        ESRI.ArcGIS.DataManagementTools.Append pAppend = new ESRI.ArcGIS.DataManagementTools.Append(fcSource, fcTarget);
        gp.SetEnvironmentValue("workspace",this._environment);
        pAppend.schema_type = "NO_TEST";
        runTool(gp, pAppend, null);
 }
コード例 #13
0
 //将FeatureClass数据转换为Raster数据
 public static void ConvertFeatureCls2Raster(Geoprocessor gp, string pathIn, string pathOut)
 {
     ESRI.ArcGIS.ConversionTools.FeatureToRaster feature2raster = new ESRI.ArcGIS.ConversionTools.FeatureToRaster();
     feature2raster.in_features = pathIn;
     feature2raster.out_raster = pathOut;
     feature2raster.field = "Shape";
     RunTool(gp, feature2raster, null);
 }
コード例 #14
0
        /// <summary>Construct Extract Data sample control</summary>
        public ExtractData()
        {
            InitializeComponent();

			_graphicsOverlay = MyMapView.GraphicsOverlays["graphicsOverlay"];
            _gpTask = new Geoprocessor(new Uri(ExtractDataServiceUrl));

            SetupUI();
        }
コード例 #15
0
        public DriveTimes()
        {
            InitializeComponent();

            _geoprocessorTask =
                new Geoprocessor("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Network/ESRI_DriveTime_US/GPServer/CreateDriveTimePolygons");
            _geoprocessorTask.ExecuteCompleted += GeoprocessorTask_ExecuteCompleted;
            _geoprocessorTask.Failed += GeoprocessorTask_Failed;
        }
コード例 #16
0
        /// <summary>Construct Viewshed sample control</summary>
        public Viewshed()
        {
            InitializeComponent();

			_inputOverlay = MyMapView.GraphicsOverlays["InputOverlay"];
			_viewshedOverlay = MyMapView.GraphicsOverlays["ViewshedOverlay"];
                
            _gpTask = new Geoprocessor(new Uri(ViewshedServiceUrl));
        }
コード例 #17
0
        /// <summary>Construct Viewshed sample control</summary>
        public Viewshed()
        {
            InitializeComponent();

            mapView.Map.InitialExtent = new Envelope(-12004035.9462375, 4652780.19374956, -11735714.4261546, 4808810.41937776);

            _gpTask = new Geoprocessor(
                new Uri("http://serverapps101.esri.com/arcgis/rest/services/ProbabilisticViewshedModel/GPServer/ProbabilisticViewshedModel"));
        }
コード例 #18
0
 //features to 3D
 public static bool FeaturesTo3D(Geoprocessor gp, string pathIn, string pathOut)
 {
     ESRI.ArcGIS.Analyst3DTools.FeatureTo3DByAttribute featureTo3D = new ESRI.ArcGIS.Analyst3DTools.FeatureTo3DByAttribute();
     featureTo3D.in_features = pathIn;
     featureTo3D.out_feature_class = pathOut;
     featureTo3D.height_field = "Contour";
     return RunTool(gp, featureTo3D, null);
     //IGPProcess tools = null;
 }
コード例 #19
0
        public PolygonsPartitionAggregation(IFeatureClass feacls,string resultPath,string gradeField)
        {
            m_GP = new Geoprocessor();

            m_FeaCls = feacls;
            m_PartitionField = gradeField;

            m_WorkingPath = resultPath;
        }
コード例 #20
0
        public Aggregation()
        {
            m_Dirpath = @"E:\在线地价\PolygonAggregate\PolygonAggregate\data\";
            m_OutputTemp_Dissolve = m_Dirpath + @"Temp_Dissolve\";
            m_OutputTemp_Aggregation = m_Dirpath + @"Temp_Aggregation\";
            m_Filename = "origin";

            m_GP = new Geoprocessor();
            m_GP.OverwriteOutput = true;
        }
コード例 #21
0
ファイル: GpHelper.cs プロジェクト: k4th/geoportal-server
        /// <summary>
        /// Class constructor handles instantiation of a GeoProcessor
        /// </summary>
        static GpHelper()
        {
            if (geoprocessor == null)
                geoprocessor = new Geoprocessor();    // this takes a few seconds...

            // Instruct the geoprocessing engine to not add output to
            // the map document, but allow it to overwrite GP output.
            geoprocessor.AddOutputsToMap = false;
            geoprocessor.OverwriteOutput = true;
        }
コード例 #22
0
 protected virtual void ReturnMessages(Geoprocessor gp)
 {
     if (gp.MessageCount > 0)
     {
         for (int Count = 0; Count <= gp.MessageCount - 1; Count++)
         {
             Console.WriteLine(gp.GetMessage(Count));
         }
     }
 }
コード例 #23
0
        /// <summary>Construct Clip Features sample control</summary>
        public ClipFeatures()
        {
            InitializeComponent();

            mapView.Map.InitialExtent = new Envelope(-130, 10, -70, 60);

            _gpTask = new Geoprocessor(new Uri(SERVICE_URL));

            //Uncomment the following line to show the service parameters at startup.
            //GetServiceInfo().ContinueWith((_) => { }, TaskScheduler.FromCurrentSynchronizationContext());
        }
コード例 #24
0
        /// <summary>Construct Extract Data sample control</summary>
        public ExtractData()
        {
            InitializeComponent();

            mapView.Map.InitialExtent = new Envelope(-8985039.34626515, 4495835.02641862, -8114288.50438322, 4889486.96951941, SpatialReferences.WebMercator);

            _gpTask = new Geoprocessor(
                new Uri("http://sampleserver4.arcgisonline.com/ArcGIS/rest/services/HomelandSecurity/Incident_Data_Extraction/GPServer/Extract%20Data%20Task"));

            SetupUI().ContinueWith(t => { }, TaskScheduler.FromCurrentSynchronizationContext());
        }
コード例 #25
0
ファイル: GProximityTool.cs プロジェクト: truonghinh/TnX
 void IBuffer.BufferInsideSde(string in_features, string out_feature, object distance)
 {
     Geoprocessor gp = new Geoprocessor();
     ESRI.ArcGIS.AnalysisTools.Buffer bufferTool = new ESRI.ArcGIS.AnalysisTools.Buffer();
     //_environment = "Database Connections/Connection to HT-LAPTOP.sde";
     //MessageBox.Show("TnBuffer-line:85--environment: " + _environment);
     gp.SetEnvironmentValue("workspace", _environment);
     bufferTool.in_features = in_features;
     bufferTool.out_feature_class = out_feature;
     bufferTool.buffer_distance_or_field = distance;
     runTool(gp, bufferTool, null);
 }
コード例 #26
0
        /// <summary>Construct Clip Features sample control</summary>
        public ClipFeatures()
        {
            InitializeComponent();

			_inputOverlay = MyMapView.GraphicsOverlays["inputOverlay"];
			_resultsOverlay = MyMapView.GraphicsOverlays["resultsOverlay"];

            _gpTask = new Geoprocessor(new Uri(ClipCountiesServiceUrl));

            //Uncomment the following line to show the service parameters at startup.
            //GetServiceInfo();
        }
コード例 #27
0
        public static void WriteBuildErrorsToTurnFC(string outputFileGdbPath, string fdsName, string turnFCName,
                                                    IGPMessages messages, ITrackCancel trackcancel)
        {
            messages.AddMessage("Writing build errors to the turn feature class...");

            // Create a new field on the turn feature class for the build errors

            Geoprocessor gp = new Geoprocessor();
            gp.AddOutputsToMap = false;
            AddField addFieldTool = new AddField();
            addFieldTool.in_table = outputFileGdbPath + "\\" + fdsName + "\\" + turnFCName;
            addFieldTool.field_name = "BuildError";
            addFieldTool.field_type = "SHORT";
            gp.Execute(addFieldTool, trackcancel);

            // Open the turn feature class in the file geodatabase and find the BuildError field on it

            Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory");
            var wsf = Activator.CreateInstance(factoryType) as IWorkspaceFactory;
            var fws = wsf.OpenFromFile(outputFileGdbPath, 0) as IFeatureWorkspace;
            IFeatureClass turnFC = fws.OpenFeatureClass(turnFCName);
            int buildErrorField = turnFC.FindField("BuildError");

            // Open the BuildErrors.txt file generated from building the network dataset

            string s, leftTrimmedString, oidString;
            int leftTrimAmt = 24 + turnFCName.Length;
            IFeature feat = null;
            string[] buildErrorsFiles = System.IO.Directory.GetFiles(Environment.GetEnvironmentVariable("TEMP"), "BuildErrors.txt", System.IO.SearchOption.AllDirectories);
            string buildErrorsFile = buildErrorsFiles[0];
            System.IO.StreamReader f = new System.IO.StreamReader(buildErrorsFile);

            // Loop through the BuildErrors.txt file and write the value 1 for each entry found.

            while ((s = f.ReadLine()) != null)
            {
                // ignore blank lines
                if (s.Length == 0)
                    continue;

                // ignore build errors not dealing with the turn source
                if (s.Remove(leftTrimAmt) != ("SourceName: " + turnFCName + ", ObjectID: "))
                    continue;

                leftTrimmedString = s.Substring(leftTrimAmt);
                oidString = leftTrimmedString.Remove(leftTrimmedString.IndexOf(", "));
                feat = turnFC.GetFeature(Convert.ToInt32(oidString, System.Globalization.CultureInfo.InvariantCulture));
                feat.set_Value(buildErrorField, 1);
                feat.Store();
            }
            f.Close();
        }
コード例 #28
0
 /// <summary>
 /// 输出地理处理的过程信息
 /// </summary>
 /// <param name="gp"></param>
 /// <returns></returns>
 public static string GetMessages2(Geoprocessor gp)
 {
     StringBuilder msgBuilder = new StringBuilder();
     if (gp != null)
     {
         for (int i = 0; i < gp.MessageCount; i++)
         {
             msgBuilder.Append(gp.GetMessage(i));
             msgBuilder.Append(" ");
         }
     }
     return msgBuilder.ToString();
 }
コード例 #29
0
ファイル: Form1.cs プロジェクト: bsoer/c--plugin
        public void btnCreate_auto_Click(object sender, EventArgs e)
        {
            // Initialize the geoprocessor.
            Geoprocessor GP = new Geoprocessor();
            try
            {
                sbLabel.Text = "Creating Map Package... ";
                uw.Show();
                uw.lblUploadWait.Text = "Creating Map Package...";

                if (workingDir == string.Empty)
                {
                    workingDir = createGDXTempFolder();
                }

                // Project Directory
                //string projDir = System.IO.Directory.GetCurrentDirectory();
                //MessageBox.Show("ProjDir: " + projDir);

                // The active document is always the last template
                ITemplates templates = ArcMap.Application.Templates;
                string mxdPath = templates.get_Item(templates.Count - 1);

                ESRI.ArcGIS.DataManagementTools.PackageMap createPM = new ESRI.ArcGIS.DataManagementTools.PackageMap();
                createPM.in_map = mxdPath;
                createPM.output_file = workingDir + "\\" + Path.GetFileNameWithoutExtension(mxdPath) + ".mpk";
                GP.Execute(createPM, null);

                PMPath = workingDir + "\\" + Path.GetFileNameWithoutExtension(mxdPath) + ".mpk";
                txbFilename.Text = Path.GetFileNameWithoutExtension(mxdPath) + ".mpk";
                fpath_file = PMPath;

                uw.lblUploadWait.Visible = false;
                uw.lblUploadRes.Text = "Map Package successfully created.";
                uw.lblUploadRes.Visible = true;
                uw.prbUpload.Style = ProgressBarStyle.Continuous;
                uw.prbUpload.Value = 100;
                uw.btnCancel.Visible = false;
                uw.btnOk.Visible = true;

                sbLabel.Text = "Map Package successfully created. ";

            }
            catch
            {
                //MessageBox.Show("Python-Error (" + GP.GetReturnCode(0) + "), try to create the map package manually (option menu)");uw.Close();
                uw.Close();
                MessageBox.Show("Please enter a description for the document. (File -> Map Document Properties -> Description)");
                return;
            }
        }
コード例 #30
0
        /// <summary>
        /// Initializes a new instance of the ViewshedViewModel class.
        /// </summary>
        public ViewshedViewModel()
        {
            this.CreateViewshedRelayCommand = new RelayCommand(CreateViewshed);

            Messenger.Default.Register<Esri.ArcGISRuntime.Controls.MapView>(this, (mapView) =>
            {
                this.mapView = mapView;



                this.sms = new SimpleMarkerSymbol();
                this.sms.Color = System.Windows.Media.Colors.Black;
                sms.Style = SimpleMarkerStyle.X;
                sms.Size = 20;

                this.simpleRenderer = new SimpleRenderer();
                this.simpleRenderer.Symbol = sms;

                this.simpleLineSymbol = new SimpleLineSymbol();
                this.simpleLineSymbol.Color = System.Windows.Media.Colors.Red;
                this.simpleLineSymbol.Width = 2;
                this.simpleLineSymbol.Style = SimpleLineStyle.Solid;

                this.simpleFillSymbol = new SimpleFillSymbol();
                this.simpleFillSymbol.Color =  (Color)ColorConverter.ConvertFromString("#44FF9999");
                this.simpleFillSymbol.Outline = simpleLineSymbol;

                this.viewshedRenderer = new SimpleRenderer();
                this.viewshedRenderer.Symbol = this.simpleFillSymbol;

                gpTask = new Geoprocessor(new Uri(viewshedServiceUrl));

                this.viewshedGraphicsLayer = new GraphicsLayer();
                this.viewshedGraphicsLayer.ID = "Viewshed";
                this.viewshedGraphicsLayer.DisplayName = "Viewshed";
                this.viewshedGraphicsLayer.Renderer = this.viewshedRenderer;
                this.viewshedGraphicsLayer.InitializeAsync();

                this.inputGraphicsLayer = new GraphicsLayer();
                this.inputGraphicsLayer.ID = "Input Point";
                this.inputGraphicsLayer.DisplayName = "Input Point";
                this.inputGraphicsLayer.Renderer = this.simpleRenderer;
                this.inputGraphicsLayer.InitializeAsync();

                this.mapView.Map.Layers.Add(this.inputGraphicsLayer);
                this.mapView.Map.Layers.Add(this.viewshedGraphicsLayer);

            });


        }
コード例 #31
0
        /// <summary>
        /// Ejecuta el modelo de amenazas de incendios
        /// </summary>
        /// <param name="sTablaPrecipPromedio">Tabla Precipitacion Promedio</param>
        /// <param name="sConsultaTablaPrecipPromedio">SQL para la table precipitacion promedio</param>
        /// <param name="sPrefijo">Prefijo para los nombres de las capas</param>
        /// <param name="sTablaTempPromedio">Nombre de la tabla temporal de promedios</param>
        /// <param name="sConsultaTablaTempPromedio">SQL para la tabla temporal de promedios</param>
        /// <param name="bUsarSatelite">Indica si se han de utilizar las imagenes de satelita</param>
        /// <param name="bMostrarIntermedios">Indica si se mostraran los resultados intermedios en el mapa activo</param>
        private void GenerarModelo(string sTablaPrecipPromedio, string sConsultaTablaPrecipPromedio, string sPrefijo,
                                   string sTablaTempPromedio, string sConsultaTablaTempPromedio, bool bUsarSatelite,
                                   bool bMostrarIntermedios, String[] sRastersPrecipitacion)
        {
            String sPath   = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
            String tempDir = "";

            sPath = sPath.Replace("file:\\", "");
            SIGPIParametros parametros = new SIGPIParametros();

            try
            {
                XmlSerializer          serializer = new XmlSerializer(typeof(SIGPIParametros));
                System.IO.StreamReader r          = new System.IO.StreamReader(sPath + "\\parameters\\parametros.xml");
                parametros = (SIGPIParametros)serializer.Deserialize(r);
                r.Close();
                serializer = null;
                r          = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "SIGPI 2013");
                return;
            }

            SIGPIProcesamiento procesamiento = new SIGPIProcesamiento(parametros);
            SIGPICls           sigpi         = new SIGPICls();
            SIGPIDao           sigpiDao      = new SIGPIDao();

            sigpiDao.ConnectLocalDB(parametros.RutaBD);
            sigpiDao.UltimaFechaIncorporacion(sigpi);
            sigpi.Parametros = parametros;

            OleDbCommand   command = sigpiDao.LocalDBConnection.CreateCommand();
            OleDbParameter param   = command.CreateParameter();
            OleDbParameter param1  = command.CreateParameter();

            param.ParameterName = "fecProce";
            param.Value         = sigpi.FechaProcesamiento;

            command.CommandText = "UPDATE FECHAS_PROCESO SET FEC_PROCE = @fecProce";
            command.Parameters.Add(param);

            string sSQL = ""; // "UPDATE FECHAS_PROCESO SET FEC_PROCE = #" + sigpi.FechaProcesamiento.ToString("MM/dd/yyyy") + "#";

            try
            {
                sigpiDao.EjecutarSentenciaSinQuery(command);
            }
            catch (Exception ex)
            {
                MessageBox.Show("No se pudo actualizar la fecha de incorporacion.\n" + ex.Message);
            }

            IProgressDialogFactory pProDiaFac = new ProgressDialogFactoryClass();
            IStepProgressor        pStepPro   = pProDiaFac.Create(null, 0);

            pStepPro.MinRange  = 1;
            pStepPro.MaxRange  = 5;
            pStepPro.StepValue = 1;
            IProgressDialog2 pProDia = (IProgressDialog2)pStepPro;

            pProDia.Animation = esriProgressAnimationTypes.esriProgressGlobe;

            pProDia.Title = "Generar Modelo Amenazas";
            pProDia.ShowDialog();
            pStepPro.Step();
            pStepPro.Message = "Generando Grids Meteorologicos...";

            IFeatureClass     pFeatureClass;
            IWorkspaceFactory pShpWorkspaceFactory     = new ShapefileWorkspaceFactoryClass();
            IWorkspaceFactory pFileGDBWorkspaceFactory = new FileGDBWorkspaceFactoryClass();

            string sFormatTmp = "gdb_" + sigpi.FechaProcesamiento.ToString("yyyyMMdd") + "_" +
                                DateTime.Now.ToString("HHmmss");

            tempDir = sigpi.Parametros.TempDir;

            if (tempDir == null || tempDir.Trim().Equals(""))
            {
                tempDir = System.IO.Path.GetTempPath();
            }
            string sRutaFileGDB = System.IO.Path.GetTempPath() + sFormatTmp + ".gdb";

            if (System.IO.Directory.Exists(sRutaFileGDB))
            {
                try
                {
                    System.IO.Directory.Delete(sRutaFileGDB);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("No se pudo borrar la File Geodatabase Temporal: " +
                                    sRutaFileGDB +
                                    " Intente Borrarla Manualmente. " + ex.Message);
                    return;
                }
            }

            Geoprocessor   gp = new Geoprocessor();
            IWorkspaceName pWSName;
            string         sCapaResultado = "Amenaza_" + sigpi.FechaProcesamiento.ToString("yyyy_MM_dd");

            string sRutaGdbResultados = parametros.RutaSIGPI + parametros.Resultado + "\\" +
                                        sigpi.FechaProcesamiento.Year.ToString() + "-" +
                                        sigpi.FechaProcesamiento.ToString("MM") + "-Modelos.gdb";

            if (System.IO.Directory.Exists(sRutaGdbResultados))
            {
                GPUtilitiesClass gpUtilClass = new GPUtilitiesClass();
                try
                {
                    Delete del = new Delete();
                    del.in_data = sRutaGdbResultados + "\\" + sCapaResultado;
                    gp.Execute(del, null);
                }
                catch (Exception)
                {
                }
            }
            else
            {
                try
                {
                    pWSName = pFileGDBWorkspaceFactory.Create(parametros.RutaSIGPI + parametros.Resultado + "\\",
                                                              sigpi.FechaProcesamiento.Year.ToString() + "-" +
                                                              sigpi.FechaProcesamiento.ToString("MM") + "-Modelos.gdb", null, 0);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("No se pudo crear la Geodatabase de resultados: \n" + sRutaGdbResultados);
                    pStepPro.Hide();
                }
            }

            pWSName = pFileGDBWorkspaceFactory.Create(System.IO.Path.GetTempPath(), sFormatTmp, null, 0);
            ESRI.ArcGIS.esriSystem.IName name = (ESRI.ArcGIS.esriSystem.IName)pWSName;

            IFeatureWorkspace pWorkspaceTemp;

            try
            {
                pWorkspaceTemp = (IFeatureWorkspace)name.Open();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }

            IWorkspaceFactory pWF     = new AccessWorkspaceFactoryClass();
            IFeatureWorkspace pWSMask = (IFeatureWorkspace)pWF.OpenFromFile(parametros.RutaGBD, 0);
            IGeoDataset       pFCMask = (IGeoDataset)pWSMask.OpenFeatureClass(parametros.Mascara);
            ISpatialReference pSpaRef = pFCMask.SpatialReference;
            IEnvelope         pEnv    = pFCMask.Extent;

            string sNombreTabla = "TMPPR_";

            DateTime fechaProcesamiento = sigpi.FechaProcesamiento;

            fechaProcesamiento = fechaProcesamiento.Date;


            for (int i = 0; i < 10; i++)
            {
                try
                {
                    sigpiDao.EjecutarSentenciaSinQuery("DROP TABLE " + sNombreTabla + i.ToString());
                }
                catch (Exception ex)
                {
                    System.Console.WriteLine(ex.Message);
                }
                // "IIf([LECTUS_PRECI]![LECTURA]<=2,5,IIf([LECTUS_PRECI]![LECTURA]<=8 And [LECTUS_PRECI]![LECTURA]>2,4,IIf([LECTUS_PRECI]![LECTURA]<=14 And [LECTUS_PRECI]![LECTURA]>8,3,IIf([LECTUS_PRECI]![LECTURA]<=24 And [LECTUS_PRECI]![LECTURA]>14,2,IIf([LECTUS_PRECI]![LECTURA]>24,1,0))))) AS LECTURAS " +
                //sSQL = "SELECT CODIGO, FECHA, X, Y, LECTURA AS RASTERVALU " +
                //              "INTO " + sNombreTabla + i.ToString() + " " +
                //              "FROM LECTUS_PRECI " +
                //              "WHERE (((FECHA)=#" + sigpi.FechaProcesamiento.AddDays(-i).ToString("MM/dd/yyyy") + "#))";
                command             = sigpiDao.LocalDBConnection.CreateCommand();
                command.CommandText = "SELECT CODIGO, FECHA, X, Y, LECTURA AS RASTERVALU " +
                                      "INTO " + sNombreTabla + i.ToString() + " " +
                                      "FROM LECTUS_PRECI " +
                                      "WHERE (((FECHA) >=@fecha) and ((FECHA) <@fecha1))";
                param = command.CreateParameter();
                param.ParameterName = "fecha";
                param.Value         = sigpi.FechaProcesamiento.AddDays(-i);
                command.Parameters.Add(param);
                param1 = command.CreateParameter();
                param1.ParameterName = "fecha1";
                param1.Value         = sigpi.FechaProcesamiento.AddDays(-i + 1);
                command.Parameters.Add(param1);

                try
                {
                    sigpiDao.EjecutarSentenciaSinQuery(command);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error generando las tablas temporales de precipitaciones. Descripcion: \n" + ex.Message);
                    //pProDia.HideDialog();
                    return;
                }
            }

            try
            {
                sigpiDao.EjecutarSentenciaSinQuery("DROP TABLE TEMPERATURA_PROMEDIO");
            }
            catch (Exception ex)
            {
            }

            //"IIf(Avg(LECTUS_TEMPE.LECTURA)<=6,1,IIf(Avg(LECTUS_TEMPE.LECTURA) <=12 And Avg(LECTUS_TEMPE.LECTURA)>6,2," +
            //"IIf(Avg(LECTUS_TEMPE.LECTURA)<=18 And Avg(LECTUS_TEMPE.LECTURA)>12,3,IIf(Avg(LECTUS_TEMPE.LECTURA)<=24 And " +
            //"Avg(LECTUS_TEMPE.LECTURA)>12,4,IIf(Avg(LECTUS_TEMPE.LECTURA)>24,5,0))))) AS LECTURAS, " +

            //sSQL = "SELECT CODIGO, Max(LECTUS_TEMPE.FECHA) AS FECHA, 10 AS Num_Dias, X, Y, AVG(LECTURA) AS RASTERVALU " +
            //        "INTO TEMPERATURA_PROMEDIO " +
            //        "FROM LECTUS_TEMPE " +
            //        "WHERE (((FECHA)>=#" + sigpi.FechaProcesamiento.AddDays(-10).ToString("MM/dd/yyyy") + "# " +
            //        "And (FECHA)<=#" + sigpi.FechaProcesamiento.ToString("MM/dd/yyyy") + "#)) " +
            //        "GROUP BY CODIGO, X, Y";
            command             = sigpiDao.LocalDBConnection.CreateCommand();
            command.CommandText = "SELECT CODIGO, Max(LECTUS_TEMPE.FECHA) AS FECHA, 10 AS Num_Dias, X, Y, AVG(LECTURA) AS RASTERVALU " +
                                  "INTO TEMPERATURA_PROMEDIO " +
                                  "FROM LECTUS_TEMPE " +
                                  "WHERE (((FECHA)>= @fecha1 " +
                                  "And (FECHA)<= @fecha)) " +
                                  "GROUP BY CODIGO, X, Y";
            param = command.CreateParameter();
            param.ParameterName = "fecha";
            param.Value         = sigpi.FechaProcesamiento;
            param1 = command.CreateParameter();
            param1.ParameterName = "fecha1";
            param1.Value         = sigpi.FechaProcesamiento.AddDays(-10);
            command.Parameters.Add(param1);
            command.Parameters.Add(param);

            try
            {
                sigpiDao.EjecutarSentenciaSinQuery(command);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error Generando Tabla: TEMPERATURA_PROMEDIO " + ex.Message);
                pProDia.HideDialog();
                return;
            }

            string sExpression = "";
            string sOutGrid;
            double dPeso = 0;
            string sAmenazaXPrecipitacion    = sRutaFileGDB + "\\amenaza_x_precipitacion";
            string sTablaTemperaturaPromedio = "TEMPERATURA_PROMEDIO";
            string sFCTempPromedio           = "TEMP_PROMEDIO";
            string sPrefijoIDW                     = "idw";
            string sAmenazaXTemperatura            = sRutaFileGDB + "\\" + "amenaza_x_temperatura";
            string sAmenazasParciales              = parametros.RutaGBD + "\\" + "amenazas_parciales_2";
            string sAmenazaBruta                   = sRutaFileGDB + "\\amenaza_incendio_bruta";
            string sAmenazaFinal                   = sRutaFileGDB + "\\amenaza_incendio_final";
            string sTablaReclassIncendios          = parametros.TablaReclasificacionIncendios;     //"tbl_reclass_amenaza_incendios";
            string sTablaReclassTemp               = parametros.TablaReclasificacionTemperatura;   //"tbl_reclass_temperatura";
            string sTablaReclassPrecip             = parametros.TablaReclasificacionPrecipitacion; //"tbl_reclass_precipitacion";
            string sAmenazaXTemperaturaCombinada   = sRutaFileGDB + "\\" + "amenaza_x_temperatura_combinada";
            string sEstVirtualesPrecipitacion      = sRutaFileGDB + "\\" + "estaciones_virtuales_precipitacion";
            string sAmenazaXPrecipitacionCombinada = sRutaFileGDB + "\\" + "amenaza_x_precipitacion_combinada";
            string sAmenazaFinalBrutaNVI           = sRutaFileGDB + "\\" + "amenaza_incend_raw_nvi";
            string sNVITempReclass                 = sRutaFileGDB + "\\" + "nvi_reclass_temp";
            string sFromField             = "FROM_";
            string sToField               = "TO_";
            string sOutField              = "OUT";
            string sNoData                = "NODATA";
            string sFieldLecturas         = "RASTERVALU";               //LECTURAS";
            string sTipoEstadistico       = parametros.TipoEstadistico; //"MAXIMUM";
            string sAmenazaXPrecipReclass = sAmenazaXPrecipitacion + "_reclass";
            string sAmenazaXTempReclass   = sAmenazaXTemperatura + "_reclass";
            string nvi = parametros.RutaSIGPI + "NVI" + "\\" + "tmpMosaic.500m_16_days_NDVI_GEO.tif";

            double dPesoPrecipitacion     = parametros.PesoPrecipitacion;     //0.29;
            double dPesoTemperatura       = parametros.PesoTemperatura;       //0.24;
            double dPesoAmenazasParciales = parametros.PesoAmenazasParciales; //0.47;

            IDataset         pDS;
            IDatasetName     pDSName;
            IDatasetName     pDSName2  = new FeatureClassNameClass();
            IExportOperation pExportOp = new ExportOperationClass();

            string sEstacionesVirtuales           = sRutaFileGDB + "\\" + "EstacionesVirtuales.shp";
            ExtractValuesToPoints extractValPoint = new ExtractValuesToPoints();

            extractValPoint.in_point_features  = sEstacionesVirtuales;
            extractValPoint.interpolate_values = "NONE";
            extractValPoint.add_attributes     = "VALUE_ONLY";


            //'0.037037037;
            // 1" = 1/3600
            double dCellSize = parametros.TamanoCelda / (3600 * 30);

            double[] iPesos      = parametros.Pesos; //{ 30, 20, 10, 9, 8, 7, 6, 5, 4, 3 };
            double   iTotalPesos = 0;                //102;

            foreach (double dP in iPesos)
            {
                iTotalPesos += dP;
            }

            gp.AddOutputsToMap = bMostrarIntermedios;
            gp.SetEnvironmentValue("Mask", parametros.RutaGBD + "\\" + parametros.Mascara);
            gp.SetEnvironmentValue("Extent", pEnv.XMin.ToString() + " " + pEnv.YMin.ToString() + " " +
                                   pEnv.XMax.ToString() + " " + pEnv.YMax.ToString());

            ESRI.ArcGIS.SpatialAnalystTools.Idw idw = new Idw();
            idw.z_field   = sFieldLecturas;
            idw.cell_size = dCellSize;

            for (int i = 0; i < 10; i++)
            {
                pFeatureClass          = procesamiento.FCPrecipitacion(sNombreTabla + i.ToString(), pSpaRef);
                pDS                    = (IDataset)pFeatureClass;
                pDSName                = (IDatasetName)pDS.FullName;
                pDSName2.Name          = sNombreTabla + i.ToString();
                pDSName2.WorkspaceName = pWSName;
                try
                {
                    pExportOp.ExportFeatureClass(pDSName, null, null, null, (IFeatureClassName)pDSName2, 0);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    pProDia.HideDialog();
                    return;
                }

                if (bUsarSatelite)
                {
                    //Geoprocessor gp1 = new Geoprocessor();
                    //extractValPoint.in_raster = sRastersPrecipitacion[i];  // txtRutaPrecipitacion.Text;
                    //extractValPoint.out_point_features = sEstVirtualesPrecipitacion + i.ToString();

                    //try
                    //{
                    //  gp1.Execute(extractValPoint, null);
                    //}
                    //catch (Exception ex)
                    //{
                    //  MessageBox.Show(ex.Message);
                    //}

                    //Merge merge = new Merge();
                    //string sInputMerge = sRutaFileGDB + "\\" + sNombreTabla + i.ToString() + ";" + sEstVirtualesPrecipitacion + i.ToString();
                    //merge.inputs = sInputMerge;
                    ////"[" + sRutaFileGDB + "\\" + sNombreTabla + i.ToString() + ";" + sEstVirtualesPrecipitacion + i.ToString() + "]" ;
                    //merge.output = sRutaFileGDB + "\\" + "est_precip_temporal" + i.ToString();
                    //try
                    //{
                    //  gp.Execute(merge, null);
                    //}
                    //catch (Exception ex)
                    //{
                    //  MessageBox.Show(ex.Message);
                    //}

                    //idw.in_point_features = sRutaFileGDB + "\\" + "est_precip_temporal" + i.ToString();

                    idw.in_point_features = sRutaFileGDB + "\\" + sNombreTabla + i.ToString();
                }
                else
                {
                    idw.in_point_features = sRutaFileGDB + "\\" + sNombreTabla + i.ToString();
                }

                sOutGrid       = sRutaFileGDB + "\\" + sPrefijoIDW + "_" + sNombreTabla + i.ToString();
                idw.out_raster = sOutGrid;
                try
                {
                    gp.Execute(idw, null);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

                dPeso        = iPesos[i] / iTotalPesos;
                sExpression += "( Raster(r'" + sOutGrid + "') * " + dPeso.ToString().Replace(",", ".") + ")";
                if (i < 9)
                {
                    sExpression += " + ";
                }
            }


            pStepPro.Step();

            ////for (int i = 0; i < 10; i++)
            ////{
            ////  //pStepPro.Message = "Generando Modelo Precipitacion: " + i.ToString();
            ////  sOutGrid = sRutaFileGDB + "\\" + sPrefijoIDW + "_" + sNombreTabla + i.ToString();
            ////  idw.in_point_features = sRutaFileGDB + "\\" + sNombreTabla + i.ToString();
            ////  idw.out_raster = sOutGrid;
            ////  gp.Execute(idw, null);
            ////  dPeso = iPesos[i] / iTotalPesos;
            ////  sExpression += "(" + sOutGrid + " * " + dPeso.ToString() + ")";
            ////  if (i < 9)
            ////    sExpression += " + ";
            ////}
            //gp.AddMessage("Expresion: " + sExpression);
            //SingleOutputMapAlgebra mapAlgebra = new SingleOutputMapAlgebra();

            ESRI.ArcGIS.SpatialAnalystTools.RasterCalculator mapAlgebra = new RasterCalculator();
            //mapAlgebra.expression_string = sExpression;
            // mapAlgebra.out_raster = sAmenazaXPrecipitacion;

            mapAlgebra.expression = sExpression;

            mapAlgebra.output_raster = sAmenazaXPrecipitacion;
            pStepPro.Message         = "Generando Amenaza Precipitacion...";
            try
            {
                gp.Execute(mapAlgebra, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error Generando Amenaza x Precipitacion. " + ex.Message);
                pProDia.HideDialog();
                return;
            }

            //if (bUsarSatelite)  // Para la combinacion de la precipitacion x estaciones y satelite
            //{

            //  //CellStatistics cellStatisticsP = new CellStatistics();
            //  //cellStatisticsP.in_rasters_or_constants = sAmenazaXPrecipitacion + ";" + txtRutaPrecipitacion.Text;
            //  //cellStatisticsP.out_raster = sAmenazaXPrecipitacionCombinada;
            //  //cellStatisticsP.statistics_type = sTipoEstadistico;
            //  try
            //  {
            //    gp.Execute(extractValPoint, null);
            //    //sAmenazaXPrecipitacion = sAmenazaXPrecipitacionCombinada;
            //  }
            //  catch (Exception ex)
            //  {
            //    MessageBox.Show("Error generando estaciones virtuales con precipitacion." + ex.Message);
            //    return;
            //  }

            //  Merge merge = new Merge();
            //  merge.inputs =

            //}

            DateTime date   = sigpi.FechaProcesamiento;
            string   sMonth = date.ToString("MM");

            pStepPro.Step();
            pStepPro.Message = "Generando Amenaza x Temperatura";
            pFeatureClass    = procesamiento.FCPrecipitacion(sTablaTemperaturaPromedio, pSpaRef);
            pDS                    = (IDataset)pFeatureClass;
            pDSName                = (IDatasetName)pDS.FullName;
            pDSName2.Name          = sFCTempPromedio;
            pDSName2.WorkspaceName = pWSName;
            try
            {
                pExportOp.ExportFeatureClass(pDSName, null, null, null, (IFeatureClassName)pDSName2, 0);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            idw.in_point_features = sRutaFileGDB + "\\" + sFCTempPromedio;
            idw.out_raster        = sAmenazaXTemperatura;
            try
            {
                gp.Execute(idw, null);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }


            //if (bUsarSatelite)
            //{
            //  Geoprocessor gp1 = new Geoprocessor();
            //  Con pContmp = new Con();
            //  pContmp.in_conditional_raster = txtRutaTemperatura.Text;
            //  pContmp.in_true_raster_or_constant = txtRutaTemperatura.Text;
            //  pContmp.in_false_raster_or_constant = -99;
            //  string sRasterTTemp = sAmenazaXTemperaturaCombinada + "_ajs";
            //  pContmp.out_raster = sRasterTTemp;
            //  pContmp.where_clause = "VALUE < 55";

            //  try
            //  {
            //    gp1.Execute(pContmp, null);
            //  }
            //  catch (Exception)
            //  {
            //    sRasterTTemp = txtRutaTemperatura.Text; ;
            //  }
            //  gp1 = null;

            //  CellStatistics cellStatistics = new CellStatistics();
            //  cellStatistics.in_rasters_or_constants = sAmenazaXTemperatura + ";" + sRasterTTemp;
            //  cellStatistics.out_raster = sAmenazaXTemperaturaCombinada;
            //  cellStatistics.statistics_type = sTipoEstadistico;
            //  try
            //  {
            //    gp.Execute(cellStatistics, null);
            //    sAmenazaXTemperatura = sAmenazaXTemperaturaCombinada;
            //  }
            //  catch (Exception)
            //  {
            //  }
            //}

            ReclassByTable rbt = new ReclassByTable();

            rbt.in_raster          = sAmenazaXPrecipitacion;
            rbt.in_remap_table     = sTablaReclassPrecip; // parametros.RutaGBD + "\\" + sTablaReclassPrecip;
            rbt.from_value_field   = sFromField;
            rbt.to_value_field     = sToField;
            rbt.output_value_field = sOutField;
            rbt.missing_values     = sNoData;
            rbt.out_raster         = sAmenazaXPrecipReclass;
            //pStepPro.Message = "Generando Amenaza X Precipitacion Reclasificada";
            try
            {
                gp.Execute(rbt, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                pProDia.HideDialog();
                return;
            }

            rbt.in_raster      = sAmenazaXTemperatura;
            rbt.in_remap_table = sTablaReclassTemp; // parametros.RutaGBD + "\\" + sTablaReclassTemp;
            rbt.out_raster     = sAmenazaXTempReclass;
            //pStepPro.Message = "Generando Amenaza X Temperatura Reclasificada";
            try
            {
                gp.Execute(rbt, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                pProDia.HideDialog();
                return;
            }

            sExpression = "( Raster(r'" + sAmenazaXPrecipReclass + "') * " + dPesoPrecipitacion.ToString().Replace(",", ".") + ") + " +
                          "( Raster(r'" + sAmenazaXTempReclass + "') * " + dPesoTemperatura.ToString().Replace(",", ".") + ") + " +
                          "( Raster(r'" + sAmenazasParciales + "') * " + dPesoAmenazasParciales.ToString().Replace(",", ".") + ")";

            //mapAlgebra.expression_string = sExpression;
            //mapAlgebra.out_raster = sAmenazaBruta;

            sExpression              = sExpression.Replace("\\\\", "/").Replace("\\", "/");
            mapAlgebra.expression    = sExpression;
            mapAlgebra.output_raster = sAmenazaBruta;

            pStepPro.Message = "Generando Amenaza Final Bruta";
            try
            {
                gp.Execute(mapAlgebra, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            //if (txtRutaNVI.Text.Trim() != "")
            //{
            Geoprocessor gp2 = new Geoprocessor();

            mapAlgebra               = new RasterCalculator();
            sExpression              = "Con (Raster(r'" + nvi + "') < 0.75, Raster(r'" + sAmenazaBruta + "'), Raster(r'" + sAmenazaBruta + "') -1)";
            sExpression              = sExpression.Replace("\\\\", "/").Replace("\\", "/");
            mapAlgebra.expression    = sExpression;
            mapAlgebra.output_raster = sAmenazaFinalBrutaNVI;

            try
            {
                gp2.Execute(mapAlgebra, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            //}


            rbt.in_raster          = sAmenazaFinalBrutaNVI;  // sAmenazaBruta;
            rbt.in_remap_table     = sTablaReclassIncendios; // parametros.RutaGBD + "\\" + sTablaReclassIncendios;
            rbt.from_value_field   = sFromField;
            rbt.to_value_field     = sToField;
            rbt.output_value_field = sOutField;
            rbt.missing_values     = sNoData;
            rbt.out_raster         = sAmenazaFinal;
            pStepPro.Message       = "Generando Amenaza Final Reclasificada";
            gp.AddOutputsToMap     = true;
            try
            {
                gp.Execute(rbt, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            Copy copy = new Copy();

            copy.in_data = sAmenazaFinal;

            copy.out_data = sRutaGdbResultados + "\\" + sCapaResultado;
            try
            {
                gp.Execute(copy, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error Copiando el resultado. \n " + ex.Message);
            }



            MessageBox.Show("Algoritmo completo ejecutado: " + sRutaGdbResultados + "\\" + sCapaResultado);

            if (m_pApp != null)
            {
                IRasterLayer pRLayer = new RasterLayerClass();
                try
                {
                    IWorkspaceFactory  pWF2      = new FileGDBWorkspaceFactoryClass();
                    IRasterWorkspaceEx pRW       = (IRasterWorkspaceEx)pWF2.OpenFromFile(sRutaGdbResultados, 0);
                    IRasterDataset     pRDataset = pRW.OpenRasterDataset(sCapaResultado);
                    pRLayer.CreateFromDataset(pRDataset);
                    pRLayer.Name = sCapaResultado;
                    IMxDocument pMxDoc = m_pApp.Document as IMxDocument;
                    IMap        pMap   = pMxDoc.FocusMap;
                    AsignarSimbologiaProbabilidad(pRLayer);
                    pMap.AddLayer(pRLayer);
                    if (pMap.LayerCount > 0)
                    {
                        pMap.MoveLayer(pRLayer, pMap.LayerCount - 1);
                    }

                    pMxDoc.UpdateContents();
                    pMxDoc.ActiveView.Refresh();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error cargando Capa!!!");
                }
            }

            pProDia.HideDialog();
        }
コード例 #32
0
        async void gpFarthest_JobCompleted(object sender, JobInfoEventArgs e)
        {
            try
            {
                Geoprocessor gpFOC = sender as Geoprocessor;
                client.ArcGISDynamicMapServiceLayer gpLayer = gpFOC.GetResultMapServiceLayer(e.JobInfo.JobId);
                gpLayer.ID      = "Farthest On Circle";
                gpLayer.Opacity = .65;

                _mapWidget.Map.Layers.Add(gpLayer);

                //get legend
                HttpClient client   = new HttpClient();
                string     response =
                    await client.GetStringAsync(_baseURL + "MapServer/legend?f=pjson");

                XmlDocument   doc      = (XmlDocument)JsonConvert.DeserializeXmlNode(response);
                XmlNodeList   xmlnode  = doc.GetElementsByTagName("legend");
                List <legend> pLegends = new List <legend>();
                int           count    = 0;
                double        test     = System.Convert.ToInt16(Range.Text) / System.Convert.ToInt16(Speed.Text);
                int           theval   = System.Convert.ToInt16(test);
                _dtLegends.Clear();

                foreach (XmlNode node in xmlnode)
                {
                    legend pLegend = new legend();
                    foreach (XmlNode child in node.ChildNodes)
                    {
                        if (child.Name == "label")
                        {
                            pLegend.label = child.InnerText + " Hours of Transit";
                        }
                        if (child.Name == "url")
                        {
                            pLegend.url = _baseURL + "MapServer/1/images/" + child.InnerText;
                        }
                    }
                    if (count <= theval && count < 24)
                    {
                        _dtLegends.Add(pLegend);
                    }

                    count++;
                }


                if (pWin == null)
                {
                    pWin = new LegendDialog();
                }
                pWin.ListView.DataContext = _dtLegends;
                pWin.Closed += pWin_Closed;
                pWin.Show();
                pWin.Topmost = true;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
        }
コード例 #33
0
ファイル: BufferAnalysisForm.cs プロジェクト: arcpad/epsgis
        private void buttonAnalysis_Click(object sender, EventArgs e)
        {
            //修改当前指针样式
            this.Cursor = Cursors.WaitCursor;

            //make sure that all parameters are okay
            double bufferDistance;

            double.TryParse(txtBufferDistance.Text, out bufferDistance);
            if (0.0 == bufferDistance)
            {
                MessageBox.Show("无效的缓冲距离!");
                return;
            }

            if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(txtOutputPath.Text)) ||
                ".shp" != System.IO.Path.GetExtension(txtOutputPath.Text))
            {
                MessageBox.Show("无效的文件名!");
                return;
            }

            if (m_hookHelper.FocusMap.LayerCount == 0)
            {
                return;
            }

            //get the layer from the map
            IFeatureLayer layer = GetFeatureLayer((string)cboLayers.SelectedItem);

            if (null == layer)
            {
                txtMessages.Text += "图层 " + (string)cboLayers.SelectedItem + "未被找到!\r\n";
                return;
            }

            //scroll the textbox to the bottom
            ScrollToBottom();
            //add message to the messages box
            txtMessages.Text += "进行缓冲区的图层: " + layer.Name + "\r\n";

            txtMessages.Text += "\r\n正在获取空间数据。这可能需要几秒钟时间...\r\n";
            txtMessages.Update();
            //get an instance of the geoprocessor
            Geoprocessor gp = new Geoprocessor();

            gp.OverwriteOutput = true;
            txtMessages.Text  += "正在进行缓冲区分析...\r\n";
            txtMessages.Update();

            //create a new instance of a buffer tool
            ESRI.ArcGIS.AnalysisTools.Buffer buffer = new ESRI.ArcGIS.AnalysisTools.Buffer(layer, txtOutputPath.Text, Convert.ToString(bufferDistance) + " " + (string)cboUnits.SelectedItem);

            //execute the buffer tool (very easy :-))
            IGeoProcessorResult results = (IGeoProcessorResult)gp.Execute(buffer, null);

            if (results.Status != esriJobStatus.esriJobSucceeded)
            {
                txtMessages.Text += "缓冲区失败的图层: " + layer.Name + "\r\n";
            }
            txtMessages.Text += ReturnMessages(gp);
            //scroll the textbox to the bottom
            ScrollToBottom();

            txtMessages.Text += "\r\n完成!\r\n";
            txtMessages.Text += "------------------------------------------------------\r\n";
            //scroll the textbox to the bottom
            ScrollToBottom();

            //修改当前指针样式
            this.Cursor = Cursors.Default;
        }
コード例 #34
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            Geoprocessor GP          = new Geoprocessor();
            ExportCAD    GPExportCAD = new ExportCAD();

            //设置in_features属性
            if (this.cklstCurLayers.CheckedItems.Count == 0)
            {
                return;
            }
            progressBar1.Maximum = cklstCurLayers.CheckedItems.Count;
            string filePath = null;

            //for (int i = 0; i < this.cklstCurLayers.Items.Count; i++)
            //{
            //    if (this.cklstCurLayers.GetItemChecked(i))
            //    {
            //        filePath = filePath + m_dicPathAliasName[i] + ";";
            //    }
            //    //filePath = filePath + this.cklstCurLayers.CheckedItems[i].ToString() + ";";
            //}
            //filePath = filePath.TrimEnd(Convert.ToChar(";"));
            //GPExportCAD.in_features = filePath;

            //设置Output_Type属性
            GPExportCAD.Output_Type = this.cbOutputType.SelectedItem.ToString();

            //设置Output_File属性
            if (this.tbOutputFile.Text == null || this.tbOutputFile.Text == "")
            {
                MessageBox.Show(@"请选择输出路径。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (System.IO.File.Exists(this.tbOutputFile.Text))
            {
                DialogResult dr = MessageBox.Show("当前文件已存在" + Environment.NewLine + "点击“是”将覆盖现有文件" + Environment.NewLine + "点击“否”将追加到现有文件" + Environment.NewLine + "点击“取消”退出本次操作!", "", MessageBoxButtons.YesNoCancel);
                if (dr == DialogResult.Yes)
                {
                    System.IO.File.Delete(this.tbOutputFile.Text);
                }
                else if (dr == DialogResult.No)
                {
                }
                else
                {
                    return;
                }
            }
            GPExportCAD.Output_File = this.tbOutputFile.Text.Trim();

            ///设置Ignore_FileNames属性
            ///IGNORE_FILENAMES_IN_TABLES:忽略文档实体字段中的路径,
            ///并允许将所有实体输出到单个 CAD 文件。
            ///USE_FILENAMES_IN_TABLES";//允许使用文档实体字段中的路径,
            ///并使用每个实体的路径,以使每个 CAD 部分写入到各自的文件。这是默认设置。
            //if (this.cbIgnoreFileNames.Checked)
            GPExportCAD.Ignore_FileNames = "IGNORE_FILENAMES_IN_TABLES";
            //else
            //    GPExportCAD.Ignore_FileNames = "USE_FILENAMES_IN_TABLES";

            ///设置Append_To_Existing属性
            ///APPEND_TO_EXISTING_FILES:允许将输出文件内容添加到现有 CAD 输出文件中。
            ///现有 CAD 文件内容不会丢失。
            ///OVERWRITE_EXISTING_FILES";输出文件内容将覆盖现有 CAD 文件内容。这是默认设置。
            //if (this.cbIgnoreFileNames.Checked)
            GPExportCAD.Append_To_Existing = "APPEND_TO_EXISTING_FILES";
            //else
            //    GPExportCAD.Append_To_Existing = "OVERWRITE_EXISTING_FILES";
            try
            {
                for (int i = 0; i < this.cklstCurLayers.Items.Count; i++)
                {
                    if (this.cklstCurLayers.GetItemChecked(i))
                    {
                        filePath = m_dicPathAliasName[i];
                        GPExportCAD.in_features = filePath;
                        GP.Execute(GPExportCAD, null);
                        progressBar1.Value++;
                    }
                }
                //GP.Execute(GPExportCAD, null);
                MessageBox.Show(@"转换完成!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
コード例 #35
0
        /// <summary>
        /// 生成等值线
        /// </summary>
        /// <param name="targetworkspace"></param>
        /// <param name="nameOftargetFeatureClass"></param>
        /// <param name="sLayerAliasName"></param>
        private bool CreateContours(IWorkspace targetworkspace, string nameOftargetFeatureClass,
                                    string sLayerAliasName, string extent, ref string failInfo)
        {
            double douElevation;

            //设置一个最小值
            progressBarControl1.Properties.Minimum = 0;
            //设置一个最大值
            progressBarControl1.Properties.Maximum = 6;
            //设置步长,即每次增加的数
            progressBarControl1.Properties.Step = 1;
            //设置进度条的样式
            progressBarControl1.Properties.ProgressViewStyle = DevExpress.XtraEditors.Controls.ProgressViewStyle.Solid;
            progressBarControl1.Position = 0;

            try
            {
                Geoprocessor GP = new Geoprocessor();

                if (withIn(m_strDataFilePath) == false)
                {
                    return(false);
                }
                if (TB_Interval.Text == "")
                {
                    MessageBox.Show("请输入正确的等高距!", "提示!");
                    return(false);
                }
                if (double.TryParse(TB_Interval.Text.Trim(), out douElevation))
                {
                }
                else
                {
                    TB_Interval.Text = null;
                    MessageBox.Show("请输入正确的等高距!", "提示!");
                    return(false);
                }

                string featurOut = m_MakeContoursFolder + "\\Cont.shp";
                int    k         = 0;
                while (System.IO.File.Exists(featurOut))
                {
                    k++;
                    featurOut = m_MakeContoursFolder + "\\Cont" + k.ToString() + ".shp";
                }
                int countCont = System.IO.Directory.GetFiles(m_MakeContoursFolder, "Cont*").Length;
                if (countCont > 0)
                {
                    featurOut = m_MakeContoursFolder + "\\Cont" + countCont.ToString() + ".shp";
                }
                if (DrawContours.ConvertASCIIDescretePoint2FeatureClass(GP, m_strDataFilePath, featurOut) == false)
                {
                    return(false);
                }
                //执行步长
                this.progressBarControl1.PerformStep();

                string ContourRaster = m_MakeContoursFolder + "\\Spline";
                //string ContourRaster = m_MakeContoursFolder + "\\" + nameOftargetFeatureClass + "_Render";
                if (extent != "")//右上左下  xmax  ymax  xmin  ymin
                {
                    GP.SetEnvironmentValue("Extent", extent);
                }
                bool   suc = false;
                string sRasterLayerAliasName = sLayerAliasName + "渲染图";
                ILayer rsLayer = DataEditCommon.GetLayerByName(DataEditCommon.g_pMap, sRasterLayerAliasName);
                if (rsLayer != null)
                {
                    DataEditCommon.g_pMap.DeleteLayer(rsLayer);
                }
                if (System.IO.Directory.Exists(ContourRaster))
                {
                    try
                    {
                        System.IO.Directory.Delete(ContourRaster, true);
                    }
                    catch
                    {
                        k = 1;
                        while (System.IO.Directory.Exists(ContourRaster))
                        {
                            ContourRaster = m_MakeContoursFolder + "\\Spline" + k.ToString();
                            k++;
                        }
                    }
                }
                switch (CB_InterpolationMethod.Text)
                {
                case "样条函数插值法":
                    suc = DrawContours.Interpolate2RasterSpline(GP, featurOut, ContourRaster, CB_SplineType.Text);
                    break;

                case "自然邻域插值法":
                    suc = DrawContours.Interpolate2RasterNN(GP, featurOut, ContourRaster);
                    break;

                case "克里格插值法":
                    suc = DrawContours.Interpolate2RasterKriging(GP, featurOut, ContourRaster,
                                                                 CB_semiVariogramProp.Text, CB_searchRadiusProp.Text);
                    break;

                case "反距离权重插值法":
                    suc = DrawContours.Interpolate2RasterIDW(GP, featurOut, ContourRaster);
                    break;

                case "趋势面插值法":
                    suc = DrawContours.TrendToRaster(GP, featurOut, ContourRaster);
                    break;
                }
                if (suc == false)
                {
                    return(false);
                }
                this.progressBarControl1.PerformStep();
                GP = new Geoprocessor();
                string R2Contour = m_MakeContoursFolder + "\\Contour.shp";
                k = 1;
                while (System.IO.File.Exists(R2Contour))
                {
                    R2Contour = m_MakeContoursFolder + "\\Contour" + k.ToString() + ".shp";
                    k++;
                }
                int countContour = System.IO.Directory.GetFiles(m_MakeContoursFolder, "Contour*").Length;
                if (countContour > 0)
                {
                    R2Contour = m_MakeContoursFolder + "\\Contour" + countContour.ToString() + ".shp";
                }

                if (DrawContours.SplineRasterToContour(GP, ContourRaster, R2Contour, douElevation) == false)
                {
                    return(false);
                }
                this.progressBarControl1.PerformStep();

                string EvEContour = m_MakeContoursFolder + "\\EvEContour.shp";
                k = 1;
                while (System.IO.File.Exists(EvEContour))
                {
                    EvEContour = m_MakeContoursFolder + "\\EvEContour" + k.ToString() + ".shp";
                    k++;
                }
                int countEvEContour = System.IO.Directory.GetFiles(m_MakeContoursFolder, "EvEContour*").Length;
                if (countEvEContour > 0)
                {
                    EvEContour = m_MakeContoursFolder + "\\EvEContour" + countEvEContour.ToString() + ".shp";
                }
                if (DrawContours.FeaturesTo3D(GP, R2Contour, EvEContour) == false)
                {
                    return(false);
                }
                this.progressBarControl1.PerformStep();

                //获得等值线Shp文件所在的工作空间
                IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactory();
                IWorkspace        sourceworkspace  = workspaceFactory.OpenFromFile(m_MakeContoursFolder, 0);
                //裁切
                IPolygon bianjie = GetPolygon();

                //导入等值线Shp文件到数据库中
                DrawSpecialCommon drawspecial = new DrawSpecialCommon();
                string            nameOfsourceFeatureClass = EvEContour.Substring(EvEContour.LastIndexOf("\\") + 1);
                nameOfsourceFeatureClass = nameOfsourceFeatureClass.Substring(0, nameOfsourceFeatureClass.LastIndexOf("."));
                bool          Import = false;
                List <ziduan> list   = new List <ziduan>();
                list.Add(new ziduan("BID", ""));
                list.Add(new ziduan("mingcheng", sLayerAliasName));
                list.Add(new ziduan("mcid", this.cbCoalSeam.Text));
                list.Add(new ziduan("date", DateTime.Now.ToString()));
                list.Add(new ziduan("type", CB_InterpolationMethod.Text));
                IFeatureLayer pFeatureLayer = DataEditCommon.GetLayerByName(DataEditCommon.g_pMap, EditLayerName) as IFeatureLayer;
                string        WhereClause   = "mcid='" + this.cbCoalSeam.Text + "'";

                DataEditCommon.DeleteFeatureByWhereClause(pFeatureLayer, WhereClause);
                if (radioBtnKJ.Checked && bianjie != null)
                {
                    Import = IntersectAll(DataEditCommon.GetFeatureClassByName(sourceworkspace, nameOfsourceFeatureClass), bianjie, list);
                }
                else
                {
                    Import = drawspecial.ShapeImportGDB(sourceworkspace, targetworkspace, nameOfsourceFeatureClass, nameOftargetFeatureClass, list);
                }
                this.progressBarControl1.PerformStep();

                if (Import == false)
                {
                    MessageBox.Show(sLayerAliasName + "导入数据库失败!");
                    DataEditCommon.g_axTocControl.Update();
                    DataEditCommon.g_pAxMapControl.Refresh();
                    failInfo = sLayerAliasName;
                    return(false);
                }

                //添加相应的渲染图
                IRasterLayer newRasterLayer = new RasterLayerClass();
                newRasterLayer.CreateFromFilePath(ContourRaster);
                newRasterLayer = IntersectRaster(newRasterLayer, bianjie);
                //newRasterLayer.CreateFromDataset(newRasterDs);
                newRasterLayer.Name = sRasterLayerAliasName;
                UsingRasterStretchColorRampRender(newRasterLayer);
                //groupLayer.Add(newRasterLayer as ILayer);
                int indexPosition = DataEditCommon.g_pAxMapControl.LayerCount;//GroupLayer序号

                //判断MapControl中是否存在该图层
                ILayer mLayer = DataEditCommon.GetLayerByName(DataEditCommon.g_pMap, sRasterLayerAliasName);
                if (mLayer != null)
                {
                    DataEditCommon.g_pMyMapCtrl.Map.DeleteLayer(mLayer);
                    indexPosition--;
                }
                DataEditCommon.g_pAxMapControl.AddLayer(newRasterLayer as ILayer, indexPosition);//添加到最下面
                DataEditCommon.g_pAxMapControl.ActiveView.Extent = newRasterLayer.AreaOfInterest;
                DataEditCommon.g_axTocControl.Update();
                DataEditCommon.g_pAxMapControl.Refresh();
                this.progressBarControl1.PerformStep();

                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return(false);
            }
        }
コード例 #36
0
 public DataManipulator(string fileName)
 {
     myProcessor = new Geoprocessor();
 }
コード例 #37
0
        public override void Initialize(IArgument[] arguments)
        {
            //set component to run in loop mode
            this.CascadingUpdateCallsDisabled = true;

            Status = LinkableComponentStatus.Initializing;

            //read arguments
            foreach (IArgument entry in arguments)
            {
                if (entry.Id == "ElevationSurface")
                {
                    _Inpath = Path.GetFullPath(entry.Value.ToString());
                }
                else if (entry.Id == "OutputFile")
                {
                    _outpath = Path.GetFullPath(entry.Value.ToString());
                }
            }

            // -- Time settings for input and output exchange items --
            ITime timeHorizon = new Time(StartTime, EndTime);


            //Create input element set
            Element e = new Element("Filled Elevation");

            e.Id = "Filled Elevation";
            ElementSet eSet = new ElementSet("Filled Elevation", "Filled Elevation", ElementType.IdBased);

            eSet.AddElement(e);
            Quantity quantity = new Quantity(new Unit("Raster", 1.0, 0.0, "Raster"), "Filled Elevation", "Filled Elevation");

            //add input item
            _InputItem = new EngineEInputItem("Filled Elevation", quantity, eSet, this);
            //_InputItem.StoreValuesInExchangeItem = true;
            _InputItem.SetTimeHorizon(timeHorizon);
            this.EngineInputItems.Add(_InputItem);
            _InputItem.SetSingleTime(StartTime);

            //add input exchange item to input item list
            _inputs.Add(_InputItem);


            //create output element set
            e    = new Element("Flow Direction Raster");
            e.Id = "Flow Direction Raster";
            eSet = new ElementSet("FDR", "FDR", ElementType.IdBased);
            eSet.AddElement(e);
            quantity = new Quantity(new Unit("Raster", 1.0, 0.0, "Raster"), "Flow Direction", "Flow Direction");
            //add output item
            _OutputItem = new EngineEOutputItem("Flow Direction", quantity, eSet, this);
            _OutputItem.SetSingleTime(StartTime);

            //_OutputItem.StoreValuesInExchangeItem = true;
            _OutputItem.SetTimeHorizon(timeHorizon);
            this.EngineOutputItems.Add(_OutputItem);

            //add output exchange item to output item list
            _outputs.Add(_OutputItem);



            //initialize geoprocessing objects
            GP = new Geoprocessor();
            GP.OverwriteOutput = true;

            //checkout spatial analyst license
            esriLicenseStatus LicenseStatus = esriLicenseStatus.esriLicenseUnavailable;

            LicenseStatus = license.Initialize(esriLicenseProductCode.esriLicenseProductCodeArcInfo);
            LicenseStatus = license.CheckOutExtension(esriLicenseExtensionCode.esriLicenseExtensionCodeSpatialAnalyst);


            Status = LinkableComponentStatus.Initialized;
        }
コード例 #38
0
        // On tap, either get related records for the tapped well or find nearby wells if no well was tapped
        private async void mapView1_Tap(object sender, MapViewInputEventArgs e)
        {
            if (BusyVisibility == Visibility.Visible)
            {
                MessageBox.Show("Please wait until the current operation is complete.");
                return;
            }

            // Show busy UI
            BusyVisibility = Visibility.Visible;

            // Clear previous results
            TapPoints.Clear();
            DriveTimePolygons.Clear();

            // Create graphic and add to tap points
            var g = new Graphic()
            {
                Geometry = e.Location
            };

            TapPoints.Add(g);

            string error = null;

            // Initialize the Geoprocessing task with the drive time calculation service endpoint
            Geoprocessor task = new Geoprocessor(new Uri("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/" +
                                                         "Network/ESRI_DriveTime_US/GPServer/CreateDriveTimePolygons"));

            // Initialize input parameters
            var parameter = new GPInputParameter();

            parameter.GPParameters.Add(new GPFeatureRecordSetLayer("Input_Location", e.Location));
            parameter.GPParameters.Add(new GPString("Drive_Times", "1 2 3"));

            try
            {
                // Run the operation
                var result = await task.ExecuteAsync(parameter);

                // Check that layers were returned from the operation
                var outputLayers = result.OutParameters.OfType <GPFeatureRecordSetLayer>();
                if (outputLayers.Count() > 0)
                {
                    // Get the first layer returned - this will be the drive time areas
                    var outputLayer = outputLayers.First();
                    if (outputLayer.FeatureSet != null && outputLayer.FeatureSet.Features != null)
                    {
                        // Instead of adding drive time polygons one-by-one, update the collection all at once to
                        // allow the map to render the new features in one rendering pass.
                        DriveTimePolygons = new ObservableCollection <Graphic>(outputLayer.FeatureSet.Features);
                    }
                    else
                    {
                        error = "No results returned";
                    }
                }
                else
                {
                    error = "No results returned";
                }
            }
            catch (Exception ex)
            {
                error = "Drive time calculation failed: " + ex.Message;
            }

            // If operation did not succeed, notify user
            if (error != null)
            {
                MessageBox.Show(error);
            }

            // Hide busy UI
            BusyVisibility = Visibility.Collapsed;
        }
コード例 #39
0
        private void TransForm(string Inputfile, string Output, string outputPath)
        {
            //构造Geoprocessor
            Geoprocessor gp   = new Geoprocessor();
            string       path = Path.GetDirectoryName(Output);

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            try
            {
                ESRI.ArcGIS.DataManagementTools.MakeXYEventLayer step1 = new ESRI.ArcGIS.DataManagementTools.MakeXYEventLayer();
                step1.table      = Inputfile + "\\Sheet1$";//textBox1.Text.ToString() + "\\xy.xls\\Sheet1$";
                step1.in_x_field = txbX.Text.ToString();
                step1.in_y_field = txbY.Text.ToString();
                RunTool(gp, step1, null);
                Console.WriteLine(Inputfile);
                //Console.WriteLine("MakeXYEventLayer:添加点数据");

                ESRI.ArcGIS.DataManagementTools.PointsToLine step2 = new ESRI.ArcGIS.DataManagementTools.PointsToLine();
                step2.Input_Features       = step1.out_layer;
                step2.Output_Feature_Class = outputPath + "\\temp.shp";//@"C:\Users\Yayu.Jiang\Desktop\output\temp.shp";
                RunTool(gp, step2, null);
                //Console.WriteLine("PointsToLine:点转线");

                ESRI.ArcGIS.DataManagementTools.FeatureToPolygon step3 = new ESRI.ArcGIS.DataManagementTools.FeatureToPolygon();
                step3.in_features       = step2.Output_Feature_Class;
                step3.out_feature_class = Output;//@"C:\Users\Yayu.Jiang\Desktop\output\xy.shp";
                RunTool(gp, step3, null);
                //Console.WriteLine("FeatureToPolygon:要素转面");

                ESRI.ArcGIS.DataManagementTools.CalculateField calculateField = new ESRI.ArcGIS.DataManagementTools.CalculateField();
                calculateField.in_table = Output;
                calculateField.field    = "ID";
                //calculateField.expression = "5";
                calculateField.expression      = Path.GetFileNameWithoutExtension(Output);
                calculateField.expression_type = "VB";
                RunTool(gp, calculateField, null);
                //Console.WriteLine("CalculateField:填充ID字段");

                ESRI.ArcGIS.DataManagementTools.AddField addField = new ESRI.ArcGIS.DataManagementTools.AddField();
                addField.in_table     = Output;
                addField.field_name   = "YSBH";
                addField.field_type   = "TEXT";
                addField.field_length = 50;
                RunTool(gp, addField, null);
                //Console.WriteLine("AddField:添加字段YSBH");

                string[] foldName = Inputfile.Split('\\');
                calculateField.in_table        = addField.out_table;
                calculateField.field           = "YSBH";
                calculateField.expression_type = "VB";
                calculateField.expression      = "\"" + foldName[foldName.Length - 2] + "\"";
                //calculateField.expression = "\"aaa\"";
                RunTool(gp, calculateField, null);
                //Console.WriteLine("CalculateField:填充字段YSBH");

                #region 添加字段
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    DataRow  dr     = dt.Rows[i];
                    string[] fields = { dr["fields"].ToString(), dr["types"].ToString(), dr["length"].ToString() };
                    addField.field_name = fields[0];
                    addField.field_type = fields[1];
                    if (fields[1] == "TEXT")
                    {
                        addField.field_length = Convert.ToInt32(fields[2]);
                    }
                    RunTool(gp, addField, null);
                    //Console.WriteLine("AddField:添加字段" + dr["fields"].ToString());
                }

                #endregion
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
コード例 #40
0
        private void button6_Click(object sender, EventArgs e)
        {
            Geoprocessor gp = new Geoprocessor();

            gp.AddOutputsToMap = true;
            gp.OverwriteOutput = true;
            CreateThiessenPolygons ct = new CreateThiessenPolygons();
            ILayer        points      = GetLayerByName(map, "public_library_shp");
            IFeatureClass fc          = (points as IFeatureLayer2).FeatureClass;

            ct.in_features       = fc;
            ct.out_feature_class = output;
            ILayer    bounds      = GetLayerByName(map, "cty00_shp");
            IEnvelope envelope    = bounds.AreaOfInterest.Envelope;
            string    envelopestr = string.Format("{0} {1} {2} {3}",
                                                  envelope.XMin, envelope.YMax, envelope.XMax, envelope.YMin);

            gp.SetEnvironmentValue("Extent", envelopestr);
            gp.Execute(ct, null);

            AddJoin joined = new AddJoin();

            joined.join_table        = population;
            joined.in_layer_or_view  = "trt00_shp";
            joined.in_field          = "STFID2";
            joined.join_field        = "GEO_ID";
            joined.out_layer_or_view = output + @"\joinedoutput";
            gp.Execute(joined, null);

            Intersect intersect = new Intersect();

            intersect.in_features       = "marketshare" + ";" + tracts;
            intersect.join_attributes   = "ALL";
            intersect.out_feature_class = output + @"\intersect";
            gp.Execute(intersect, null);

            AddField addedfield = new AddField();

            addedfield.in_table   = "intersect";
            addedfield.field_name = "field";
            addedfield.field_type = "FLOAT";
            gp.Execute(addedfield, null);

            AddJoin joined2 = new AddJoin();

            joined2.join_table        = population;
            joined2.in_layer_or_view  = "intersect";
            joined2.in_field          = "STFID2";
            joined2.join_field        = "GEO_ID";
            joined2.out_layer_or_view = output + @"\joinedoutput";
            gp.Execute(joined2, null);

            CalculateField calc = new CalculateField();

            calc.in_table   = "intersect";
            calc.field      = "field";
            calc.expression = "!population.P001001!*!intersect.Shape_Area!/!intersect_Area!";
            gp.Execute(calc, null);

            Dissolve dissolved = new Dissolve();

            dissolved.in_features       = intersect;
            dissolved.statistics_fields = "field";
            dissolved.out_feature_class = output + @"\dissolve";
            gp.Execute(dissolved, null);
        }
コード例 #41
0
ファイル: GPExecutor.cs プロジェクト: rs-sdust/GFStatistics
 public GPExecutor()
 {
     this.m_gp = new Geoprocessor();
     this.m_gp.OverwriteOutput = true;
 }
コード例 #42
0
ファイル: Buffer.cs プロジェクト: AgentWord/SiPing
        /*变量:
         * 1、图层
         * 2、距离
         * 3、单位
         * 4、保存路径
         */
        private void button1_Click(object sender, EventArgs e)
        {
            double bufferDistance, bufferDistance2, bufferDistance3;

            double.TryParse(txtBufferDistance.Text, out bufferDistance);
            double.TryParse(txtBufferDistance2.Text, out bufferDistance2);
            double.TryParse(txtBufferDistance3.Text, out bufferDistance3);
            if (CNunit.SelectedIndex == 0)
            {
                DW = "Meters";
            }
            else if (CNunit.SelectedIndex == 1)
            {
                DW = "Kilometers";
            }
            if (0.0 == bufferDistance)
            {
                MessageBox.Show("输入范围距离无效!");
                return;
            }
            if (CNunit.SelectedItem == null)
            {
                MessageBox.Show("请选择单位", "提示");
                return;
            }
            //判断输出路径是否合法
            if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(txtOutputPath.Text)) || ".shp" != System.IO.Path.GetExtension(txtOutputPath.Text))
            {
                MessageBox.Show("输出路径无效!");
                return;
            }
            IFeatureLayer layer = GetFeatureLayer((string)cboLayers.SelectedItem);

            if (null == layer)
            {
                MessageBox.Show("选中图层无效!");
                return;
            }
            Geoprocessor gp = new Geoprocessor();

            gp.OverwriteOutput = true;
            double[] dis      = { 0, bufferDistance, bufferDistance2, bufferDistance3 };
            double[] distance = { bufferDistance, bufferDistance2, bufferDistance3 };
            string[] level    = { "", "高级", "中级", "低级" };
            int      i        = 1;

            txtOutputPath.Text = System.IO.Path.Combine(SystemSet.Base_Map + "\\处理数据库\\实验数据", (level[i] + "_" + (string)cboLayers.SelectedItem + "_范围.shp"));
            int l1 = txtOutputPath.Text.LastIndexOf("\\");

            lab_message.Text = txtOutputPath.Text.Substring(l1 + 1) + "正在处理···";
            ESRI.ArcGIS.AnalysisTools.MultipleRingBuffer mulBuffer = new MultipleRingBuffer();
            mulBuffer.Input_Features        = layer;
            mulBuffer.Output_Feature_class  = txtOutputPath.Text;
            mulBuffer.Buffer_Unit           = "Meters";
            mulBuffer.Distances             = distance;//[bufferDistance, bufferDistance2, bufferDistance3];
            mulBuffer.Outside_Polygons_Only = "full";
            mulBuffer.Field_Name            = "分析半径";
            gp.Execute(mulBuffer, null);
            MessageBox.Show("成功");



            while (i < 4)
            {
                //修改当前指针样式
                this.Cursor = Cursors.WaitCursor;
                //调用缓冲去区处理工具buffer
                txtOutputPath.Text = System.IO.Path.Combine(SystemSet.Base_Map + "\\处理数据库\\实验数据", (level[i] + "_" + (string)cboLayers.SelectedItem + "_buffer.shp"));
                int l = txtOutputPath.Text.LastIndexOf("\\");
                lab_message.Text = txtOutputPath.Text.Substring(l + 1) + "正在处理···";
                ESRI.ArcGIS.AnalysisTools.Buffer buffer = new ESRI.ArcGIS.AnalysisTools.Buffer(layer, txtOutputPath.Text, Convert.ToString(dis[i]) + " " + DW);//单级缓冲

                //gp.Execute(buffer, null);
                try
                {
                    IGeoProcessorResult results = (IGeoProcessorResult)gp.Execute(buffer, null);
                    if (results.Status != esriJobStatus.esriJobSucceeded)
                    {
                        MessageBox.Show("缓冲区失败的图层: " + layer.Name, "提示!");
                    }
                    this.Cursor = Cursors.Default;
                    MessageBox.Show(level[i] + "_" + layer.Name + "分析统计完成!", "提示!");
                    //将统计分析完成的图层添加到mapcontrol
                    IWorkspaceFactory pWorkspaceFactory = new ShapefileWorkspaceFactoryClass();                                                                                                                                     //定义工作空间工厂接口
                    IWorkspace        pWorkSpace        = pWorkspaceFactory.OpenFromFile(txtOutputPath.Text.Substring(0, txtOutputPath.Text.Length - (level[i] + "_" + (string)cboLayers.SelectedItem + "_buffer.shp").Length), 0); //实例化工作空间
                    IFeatureWorkspace pFeatureWorkspace = pWorkSpace as IFeatureWorkspace;
                    IFeatureClass     pFeatureClass     = pFeatureWorkspace.OpenFeatureClass(level[i] + "_" + (string)cboLayers.SelectedItem + "_buffer.shp");                                                                      //
                    //以上得到的是featureclass。

                    IDataset      pDataset      = pFeatureClass as IDataset;
                    IFeatureLayer pFeatureLayer = new FeatureLayerClass();
                    pFeatureLayer.FeatureClass = pFeatureClass;
                    pFeatureLayer.Name         = pDataset.Name;//图层名称
                    ILayer pLayer = pFeatureLayer as ILayer;

                    m_hookHelper.FocusMap.AddLayer(pLayer);
                    m_hookHelper.FocusMap.MoveLayer(pLayer, cboLayers.SelectedIndex + i);
                    i++;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    this.Cursor = Cursors.Default;
                    this.Close();
                    return;
                }
            }

            //GISHandler.GISTools.QueryByBuffer(m_hookHelper);
            this.Close();
            StasticResult SR = new StasticResult(this.mapContol);

            SR.Show();
            SR.StartPosition = FormStartPosition.CenterScreen;
            SR.TopMost       = true;

            //1、将结果图层添加到axmapcontrol中
            //2、多级缓冲 -->方法递归调用。/for循环三次  distance+=distance(图层叠加在一起  不好进行统计。)
            //3、将各级缓冲区中所叠置基图中的属性信息 自定义提取 装入 gridcontrol中。完成!
        }
コード例 #43
0
        private void Buffer(string unit)
        {
            //修改当前指针样式
            Cursor = Cursors.WaitCursor;



            if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(outputPath.Text)) ||
                ".shp" != System.IO.Path.GetExtension(outputPath.Text))
            {
                MessageBox.Show("无效的文件名!");
                return;
            }

            if (_hookHelper.FocusMap.LayerCount == 0)
            {
                return;
            }

            //get the layer from the map
            IFeatureLayer layer = GetFeatureLayer((string)inputComBox.SelectedItem);

            if (null == layer)
            {
                txtMessages.Text += "图层 " + (string)inputComBox.SelectedItem + "未被找到!\r\n";
                return;
            }

            //scroll the textbox to the bottom
            ScrollToBottom();
            //add message to the messages box
            txtMessages.Text += "进行缓冲区的图层: " + layer.Name + "\r\n";

            txtMessages.Text += "\r\n正在获取空间数据。这可能需要几秒钟时间...\r\n";
            txtMessages.Update();

            //get an instance of the geoprocessor
            Geoprocessor gp = new Geoprocessor {
                OverwriteOutput = true
            };

            txtMessages.Text += "正在进行缓冲区分析...\r\n";
            txtMessages.Update();



            //create a new instance of a buffer tool
            ESRI.ArcGIS.AnalysisTools.Buffer buffer = new ESRI.ArcGIS.AnalysisTools.Buffer(
                layer, outputPath.Text, unit
                );

            //execute the buffer tool (very easy :-))
            IGeoProcessorResult results = (IGeoProcessorResult)gp.Execute(buffer, null);


            if (results.Status != esriJobStatus.esriJobSucceeded)
            {
                txtMessages.Text += "缓冲区失败的图层: " + layer.Name + "\r\n";
            }

            txtMessages.Text += ReturnMessages(gp);
            //scroll the textbox to the bottom
            ScrollToBottom();

            txtMessages.Text += "\r\n完成!\r\n";
            txtMessages.Text += "------------------------------------------------------\r\n";
            //scroll the textbox to the bottom
            ScrollToBottom();

            //修改当前指针样式
            this.Cursor = Cursors.Default;
        }
コード例 #44
0
        private void BuildUI()
        {
            if (ParamContainer == null || ParameterConfigs == null ||
                ParameterConfigs.Count < 1)
            {
                return;
            }
            if ((Results == null || Results.Count < 1) && (Errors == null || Errors.Count < 1))
            {
                return;
            }
            if (!inputLayerInfoAvailable())
            {
                return;
            }
            ParamContainer.Children.Clear();
            ParamContainer.ColumnDefinitions.Clear();
            ParamContainer.RowDefinitions.Clear();
            ParamContainer.ColumnDefinitions.Add(new ColumnDefinition()
            {
                Width = GridLength.Auto
            });
            ParamContainer.ColumnDefinitions.Add(new ColumnDefinition()); // { Width = new GridLength(0, GridUnitType.Star) });
            HasSimpleResults       = false;
            layerParamNameIDLookup = InputLayers != null ?
                                     new Dictionary <string, string>(InputLayers) : new Dictionary <string, string>();
            int pendingGPResultImageLayers = 0;

            #region Results
            if (Results != null && Results.Count > 0)
            {
                #region GP mapserver result
                MapServiceLayerParameterConfig mapServiceLayerParameterConfig = ParameterConfigs.FirstOrDefault(p => p.Type == GPParameterType.MapServiceLayer) as MapServiceLayerParameterConfig;
                if (mapServiceLayerParameterConfig != null && mapServiceLayerParameterConfig.SupportsJobResource)
                {
                    string t   = "/rest/services/";
                    string url = string.Format("{0}/{1}/MapServer/jobs/{2}", TaskUrl.Substring(0, TaskUrl.IndexOf(t, StringComparison.OrdinalIgnoreCase) + t.Length - 1), mapServiceLayerParameterConfig.Name, JobID);

                    ArcGISDynamicMapServiceLayer layer = new ArcGISDynamicMapServiceLayer
                    {
                        Url      = url,
                        ProxyURL = UseProxy ? ProxyUrl : null
                    };
                    layer.SetValue(ESRI.ArcGIS.Mapping.Core.LayerExtensions.ExcludeSerializationProperty, true);
                    addToMap(mapServiceLayerParameterConfig, layer);
                }
                #endregion

                #region display each result
                foreach (ParameterConfig config in ParameterConfigs)
                {
                    MapServiceLayerParameterConfig cfg;
                    if (config.Type == GPParameterType.MapServiceLayer && (cfg = config as MapServiceLayerParameterConfig) != null && !cfg.SupportsJobResource)
                    {
                        pendingGPResultImageLayers++;
                        Geoprocessor gp = new Geoprocessor(TaskUrl);
                        gp.OutputSpatialReference        = Map.SpatialReference.Clone();
                        gp.GetResultImageLayerCompleted += (s, e) =>
                        {
                            GPResultImageLayer gpImageLayer = e.GPResultImageLayer;
                            setLayerProps(cfg, gpImageLayer);
                            gpImageLayer.ProxyUrl = UseProxy ? ProxyUrl : null;
                            Map.Layers.Add(gpImageLayer);
                            layerParamNameIDLookup.Add(cfg.Name, gpImageLayer.ID);
                            pendingGPResultImageLayers--;
                            if (layerParamNameIDLookup.Count > 1 && pendingGPResultImageLayers == 0)
                            {
                                LayerOrderer.OrderLayers(Map, LayerOrder, layerParamNameIDLookup);
                            }
                        };
                        // Initialize proxy
                        gp.ProxyURL = UseProxy ? ProxyUrl : null;
                        gp.GetResultImageLayerAsync(JobID, cfg.Name);
                        continue;
                    }

                    GPParameter param = getParameter(config.Name);
                    if (param == null)
                    {
                        continue;
                    }
                    string value = ParameterBase.ParameterToDisplayString(config.Type, param);

                    switch (config.Type)
                    {
                    case GPParameterType.Boolean:
                    case GPParameterType.Double:
                    case GPParameterType.Long:
                    case GPParameterType.String:
                    case GPParameterType.Date:
                    case GPParameterType.LinearUnit:
                        if (value == null)
                        {
                            value = string.Empty;
                        }
                        addparamUI(config.Label, value, false);
                        break;

                    case GPParameterType.FeatureLayer:
                        addToMap(param as GPFeatureRecordSetLayer, config);
                        break;

                    case GPParameterType.RecordSet:
                        if (string.IsNullOrEmpty(value) && param is GPRecordSet)
                        {
                            GPRecordSet rs = param as GPRecordSet;
                            if (string.IsNullOrEmpty(rs.Url) && rs.FeatureSet != null)
                            {
                                value = ESRI.ArcGIS.Mapping.GP.Resources.Strings.OnlyUrlOutputIsSupportedForRecordsets;
                            }
                            else
                            {
                                value = string.Empty;
                            }
                            addparamUI(config.Label, value, false);
                        }
                        else
                        {
                            addparamUI(config.Label, value, true);
                        }
                        break;

                    case GPParameterType.DataFile:
                    case GPParameterType.RasterData:
                    case GPParameterType.RasterDataLayer:
                        if (value == null)
                        {
                            value = string.Empty;
                        }
                        addparamUI(config.Label, value, true);
                        break;
                    }
                }
                #endregion

                if (layerParamNameIDLookup.Count > 1 && pendingGPResultImageLayers == 0)
                {
                    LayerOrderer.OrderLayers(Map, LayerOrder, layerParamNameIDLookup);
                }
            }
            #endregion

            #region Errors
            if (Errors != null && Errors.Count > 0)
            {
                foreach (Exception error in Errors)
                {
                    addparamUI(ESRI.ArcGIS.Mapping.GP.Resources.Strings.LabelError + " ", error.Message, false);
                    HasSimpleResults = true;
                }
            }
            #endregion
        }
コード例 #45
0
 /// <summary>
 /// 引发 <see cref="E:System.Windows.Forms.Form.Closed" /> 事件。
 /// </summary>
 /// <param name="e">一个包含事件数据的 <see cref="T:System.EventArgs" />。</param>
 protected override void OnClosed(EventArgs e)
 {
     this._geoProcessor = null;
 }
コード例 #46
0
        private void button3_Click(object sender, EventArgs e)
        {
            ESRI.ArcGIS.DataManagementTools.Clip clp = new Clip();
            clp.in_raster  = getlayer(comboBox1.Text.ToString());
            clp.out_raster = textBoxsave.Text;
            if (checkBox1.Checked == true)
            {
                IGPUtilities gputilities = new GPUtilitiesClass();
                IEnvelope    penvelope   = 遥感数据管理系统.Form1.envelope.penv;
                clp.rectangle = string.Format("{0} {1} {2} {3} ", penvelope.XMin, penvelope.YMin, penvelope.XMax, penvelope.YMax);
            }
            else
            {
                IGPUtilities gputilities = new GPUtilitiesClass();
                IGeoDataset  pgeodataset = gputilities.OpenRasterDatasetFromString(getlayer(comboBox2.Text.ToString())) as IGeoDataset;
                IEnvelope    penvelope   = pgeodataset.Extent;
                clp.in_template_dataset = getlayer(comboBox2.Text.ToString());
                clp.rectangle           = string.Format("{0} {1} {2} {3} ", penvelope.XMin, penvelope.YMin, penvelope.XMax, penvelope.YMax);
            }
            clp.clipping_geometry = "true";
            Geoprocessor gp = new Geoprocessor();

            gp.OverwriteOutput = true;
            IGeoProcessorResult gpresult = gp.Execute(clp, null) as IGeoProcessorResult;

            if (gpresult.Status == esriJobStatus.esriJobSucceeded)
            {
                DialogResult dl = MessageBox.Show("裁剪成功");
                if (dl == DialogResult.OK)
                {
                    if (checkBox3.Checked == true)
                    {
                        string fileFullName = textBoxsave.Text;
                        if (fileFullName == "")
                        {
                            return;
                        }
                        string            filePathName      = System.IO.Path.GetDirectoryName(fileFullName);
                        string            fileName          = System.IO.Path.GetFileName(fileFullName);
                        IWorkspaceFactory pWorkspaceFactory = new RasterWorkspaceFactory();                    //创建工作空间工厂
                        IWorkspace        pWorkspace        = pWorkspaceFactory.OpenFromFile(filePathName, 0); //打开工作空间
                        IRasterWorkspace  pRasterWorkspace  = pWorkspace as IRasterWorkspace;                  //创建栅格工作空间
                        IRasterDataset    pRasterDataset    = pRasterWorkspace.OpenRasterDataset(fileName);    //创建Dataset
                        //影像金字塔创建与判断
                        IRasterPyramid2 pRasPymid = pRasterDataset as IRasterPyramid2;
                        if (pRasPymid != null)
                        {
                            if (!(pRasPymid.Present))
                            {
                                pRasPymid.Create();//创建金字塔
                            }
                        }
                        IRaster      pRaster      = pRasterDataset.CreateDefaultRaster();
                        IRasterLayer pRasterLayer = new RasterLayer();
                        pRasterLayer.CreateFromRaster(pRaster);
                        ILayer pLayer = pRasterLayer as ILayer;
                        axmapcontrol.AddLayer(pLayer, 0);
                    }
                }
            }
            else
            {
                MessageBox.Show("裁剪失败");
            }
        }
コード例 #47
0
        private void buttonOk_Click(object sender, EventArgs e)
        {
            //检验参数是否正确设置
            double bufferDistance;

            double.TryParse(txtBufferDistance.Text, out bufferDistance);
            if (0.0 == bufferDistance)
            {
                MessageBox.Show("距离设置错误!");
                return;
            }

            if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(txtOutputPath.Text)) || ".shp" != System.IO.Path.GetExtension(txtOutputPath.Text))
            {
                MessageBox.Show("输出格式错误!");
                return;
            }

            if (ComboBoxLayer.Items.Count <= 0)
            {
                return;
            }

            IFeatureLayer pFeatureLayer = (IFeatureLayer)GetLayerByName(ComboBoxLayer.SelectedItem.ToString());

            Geoprocessor gp = new Geoprocessor();

            gp.OverwriteOutput = true;
            gp.AddOutputsToMap = true;

            string unit = "Kilometers";

            ESRI.ArcGIS.AnalysisTools.Buffer buffer = new ESRI.ArcGIS.AnalysisTools.Buffer(pFeatureLayer, txtOutputPath.Text, Convert.ToString(bufferDistance) + " " + unit);
            IGeoProcessorResult results             = (IGeoProcessorResult)gp.Execute(buffer, null);

            //添加缓冲区图层到当前地图中
            string fileDirectory = txtOutputPath.Text.ToString().Substring(0, txtOutputPath.Text.LastIndexOf("\\"));
            int    j;

            j = txtOutputPath.Text.LastIndexOf("\\");
            string            tmpstr            = txtOutputPath.Text.ToString().Substring(j + 1);
            IWorkspaceFactory pWorkspaceFactory = new ShapefileWorkspaceFactory() as IWorkspaceFactory;
            IWorkspace        pWS = pWorkspaceFactory.OpenFromFile(fileDirectory, 0);
            IFeatureWorkspace pFS = pWS as IFeatureWorkspace;
            //IFeatureClass pfc = pFS.OpenFeatureClass(this.ComboBoxLayer.SelectedText+ "_buffer.shp");
            IFeatureClass pfc = pFS.OpenFeatureClass(tmpstr);
            IFeatureLayer pfl = new FeatureLayer() as IFeatureLayer;

            pfl.FeatureClass = pfc;
            pfl.Name         = pfc.AliasName;

            IRgbColor pColor = new RgbColor() as IRgbColor;

            pColor.Red          = 255;
            pColor.Green        = 0;
            pColor.Blue         = 0;
            pColor.Transparency = 255;
            //产生一个线符号对象
            ILineSymbol pOutline = new SimpleLineSymbol();

            pOutline.Width = 2;
            pOutline.Color = pColor;
            //设置颜色属性
            pColor              = new RgbColor();
            pColor.Red          = 255;
            pColor.Green        = 0;
            pColor.Blue         = 0;
            pColor.Transparency = 100;
            //设置填充符号的属性
            ISimpleFillSymbol pFillSymbol = new SimpleFillSymbol();

            pFillSymbol.Color   = pColor;
            pFillSymbol.Outline = pOutline;
            pFillSymbol.Style   = esriSimpleFillStyle.esriSFSSolid;

            ISimpleRenderer  pRen;
            IGeoFeatureLayer pGeoFeatLyr = pfl as IGeoFeatureLayer;

            pRen                 = pGeoFeatLyr.Renderer as ISimpleRenderer;
            pRen.Symbol          = pFillSymbol as ISymbol;
            pGeoFeatLyr.Renderer = pRen as IFeatureRenderer;

            ILayerEffects pLayerEffects = pfl as ILayerEffects;

            pLayerEffects.Transparency = 150;

            Form1.m_mapControl.AddLayer((ILayer)pfl, 0);
            MessageBox.Show(ComboBoxLayer.SelectedText + "缓存生成成功!");
        }
コード例 #48
0
ファイル: FrmBuffer.cs プロジェクト: johnforrest/GeoCoding
        private void buttonX1Buffer_Click(object sender, EventArgs e)
        {
            //make sure that all parameters are okay
            double bufferDistance;

            //转换distance为double类型
            double.TryParse(textBoxX1.Text, out bufferDistance);
            if (0.0 == bufferDistance)
            {
                MessageBox.Show("缓冲区距离无效!");
                return;
            }
            //判断输出路径是否合法
            try
            {
                if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(textBoxX2.Text)) || ".shp" != System.IO.Path.GetExtension(textBoxX2.Text))
                {
                    return;
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("路径无效!");
            }
            //判断图层个数
            if (m_hookHelper.FocusMap.LayerCount == 0)
            {
                return;
            }

            //get the layer from the map
            IFeatureLayer pInputlayer = GetFeatureLayer((string)comboBoxEx1.SelectedItem);

            if (null == pInputlayer)
            {
                textBoxX3.Text += "找不到图层 " + (string)comboBoxEx1.SelectedItem + "!\r\n";
                return;
            }

            //scroll the textbox to the bottom
            ScrollToBottom();

            textBoxX3.Text += "\r\n缓冲区分析开始,请稍候..\r\n";
            textBoxX3.Update();



            //get an instance of the geoprocessor
            Geoprocessor gp = new Geoprocessor();

            gp.OverwriteOutput = true;


            //IDataset dataset1 = pInputlayer as IDataset;
            //IGeoDataset geoDataset = dataset1 as IGeoDataset;

            //ClsConvertUnit clsConvertUnit = new ClsConvertUnit();
            //double pTrandist = clsConvertUnit.GetBufferValueByUnit(geoDataset.SpatialReference, bufferDistance);

            object test = Convert.ToString(bufferDistance) + " " + (string)comboBoxEx2.SelectedItem;

            //create a new instance of a buffer tool
            ESRI.ArcGIS.AnalysisTools.Buffer buffer = new ESRI.ArcGIS.AnalysisTools.Buffer(pInputlayer, textBoxX2.Text, Convert.ToString(bufferDistance) + " " + (string)comboBoxEx2.SelectedItem);
            ////ESRI.ArcGIS.AnalysisTools.Buffer buffer = new ESRI.ArcGIS.AnalysisTools.Buffer(pInputlayer, textBoxX2.Text, Convert.ToString(pTrandist) + " " + (string)comboBoxEx2.SelectedItem);

            //buffer.dissolve_option = "ALL";//这个要设成ALL,否则相交部分不会融合
            buffer.dissolve_option = "NONE";//这个要设成ALL,否则相交部分不会融合
            //buffer.line_side = "FULL";//默认是"FULL",最好不要改否则出错
            //buffer.line_end_type = "ROUND";//默认是"ROUND",最好不要改否则出错

            //execute the buffer tool (very easy :-))
            IGeoProcessorResult results = null;

            try
            {
                results = (IGeoProcessorResult)gp.Execute(buffer, null);
            }
            catch (Exception ex)
            {
                textBoxX3.Text += "缓冲区分析失败: " + pInputlayer.Name + "\r\n";
            }
            if (results.Status != esriJobStatus.esriJobSucceeded)
            {
                textBoxX3.Text += "缓冲区分析失败: " + pInputlayer.Name + "\r\n";
            }

            //scroll the textbox to the bottom
            ScrollToBottom();

            textBoxX3.Text += "\r\n分析完成.\r\n";
            textBoxX3.Text += "-----------------------------------------------------------------------------------------\r\n";
            //scroll the textbox to the bottom
            ScrollToBottom();
        }
コード例 #49
0
ファイル: Clips.cs プロジェクト: dearLhz/MyDatapreMenu
        //确定  按钮
        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                IFeatureClass featureclassInput = null;
                IFeatureClass featureclassClip  = null;

                IFields outfields = null;

                // Create a new ShapefileWorkspaceFactory CoClass to create a new workspace
                IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactoryClass();

                // System.IO.Path.GetDirectoryName(shapefileLocation) returns the directory part of the string. Example: "C:\test\"
                // System.IO.Path.GetFileNameWithoutExtension(shapefileLocation) returns the base filename (without extension). Example: "cities"
                //IFeatureClass featureClass = featureWorkspace.OpenFeatureClass(System.IO.Path.GetFileNameWithoutExtension(shapefileLocation));

                IFeatureWorkspace featureWorkspaceInput = (IFeatureWorkspace)workspaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(TxtInputFile.Text), 0); // Explicit Cast
                IFeatureWorkspace featureWorkspaceOut   = (IFeatureWorkspace)workspaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(txtOutputPath.Text), 0);
                IFeatureWorkspace featureWorkspaceClip  = (IFeatureWorkspace)workspaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(txtClipsFile.Text), 0);

                //timer 控件可用
                timerPro.Enabled = true;
                //scroll the textbox to the bottom

                txtMessages.Text = "\r\n分析开始,这可能需要几分钟时间,请稍候..\r\n";
                txtMessages.Update();

                //inputfeatureclass = featureWorkspace.OpenFeatureClass("land00_ws");
                //clipfeatureclass = featureWorkspace.OpenFeatureClass("drain_ws_buffer");

                featureclassInput = featureWorkspaceInput.OpenFeatureClass(System.IO.Path.GetFileNameWithoutExtension(TxtInputFile.Text));
                featureclassClip  = featureWorkspaceClip.OpenFeatureClass(System.IO.Path.GetFileNameWithoutExtension(txtClipsFile.Text));
                outfields         = featureclassInput.Fields;

                Geoprocessor gp = new Geoprocessor();
                gp.OverwriteOutput = true;
                //IFeatureClass outfeatureclass = featureWorkspace.CreateFeatureClass("Clip_result", outfields, null, null, esriFeatureType.esriFTSimple, "Shape", "");
                IFeatureClass featureclassOut = null;

                //文件存在的处理
                if (File.Exists(txtOutputPath.Text.Trim()) == true)
                {
                    featureclassOut = featureWorkspaceOut.OpenFeatureClass(System.IO.Path.GetFileNameWithoutExtension(txtOutputPath.Text));
                    DelFeatureFile(featureclassOut, txtOutputPath.Text.Trim());
                }

                featureclassOut = featureWorkspaceOut.CreateFeatureClass(System.IO.Path.GetFileNameWithoutExtension(txtOutputPath.Text), outfields, null, null, esriFeatureType.esriFTSimple, "Shape", "");

                ESRI.ArcGIS.AnalysisTools.Clip clipTool =
                    new ESRI.ArcGIS.AnalysisTools.Clip(featureclassInput, featureclassClip, featureclassOut);

                gp.Execute(clipTool, null);
                workspaceFactory = null;

                //复制feature层
                //IDataset pDataset = outfeatureclass as IDataset;
                //pDataset.Copy("Clip_result1", featureWorkspace as IWorkspace);

                //添加图层到当前地图
                IFeatureLayer outlayer = new FeatureLayerClass();
                outlayer.FeatureClass = featureclassOut;
                outlayer.Name         = featureclassOut.AliasName;
                pMap.AddLayer((ILayer)outlayer);
                //
                txtMessages.Text += "\r\n分析完成.\r\n";
                timerPro.Enabled  = false;
            }
            catch (Exception ex)
            {
                //
                txtMessages.Text += "\r\n分析失败.\r\n";
                timerPro.Enabled  = false;
                MessageBox.Show(ex.Message.ToString());
            }
        }
コード例 #50
0
        private void RunButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Geoprocessor gpAircraftComms = new Geoprocessor(_serviceURL);
                gpAircraftComms.JobCompleted += gpAircraftComms_JobCompleted;
                gpAircraftComms.Failed       += gpAircraftComms_Failed;

                List <GPParameter> parameters = new List <GPParameter>();
                FeatureSet         pFeatures  = new FeatureSet(_graphicsLayer.Graphics);
                parameters.Add(new GPFeatureRecordSetLayer("Waypoints", pFeatures));
                parameters.Add(new GPString("Aircraft_Model", aircraftmodel.Text));
                FeatureSet pPolygon = new FeatureSet(_graphicsLayerPoly.Graphics);
                parameters.Add(new GPFeatureRecordSetLayer("AreaTarget", pPolygon));

                parameters.Add(new GPDouble("Grid_Point_Granularity__deg_", System.Convert.ToDouble(gridgranularity.Text)));
                string[] theTimevals = startTime.Text.Split(' ');
                string[] theTime     = theTimevals[0].Split(':');
                int      hour        = 0;
                int      minute      = 0;
                int      seconds     = 0;
                if (theTimevals[1] == "PM")
                {
                    hour = System.Convert.ToInt16(theTime[0]) + 12;
                }
                else
                {
                    hour = System.Convert.ToInt16(theTime[0]);
                }
                minute  = System.Convert.ToInt16(theTime[1]);
                seconds = System.Convert.ToInt16(theTime[2]);
                DateTime start;
                if (StartDate.SelectedDate == null)
                {
                    start = new DateTime(StartDate.DisplayDate.Date.Year, StartDate.DisplayDate.Date.Month, StartDate.DisplayDate.Day, hour, minute, seconds);
                }
                else
                {
                    start = new DateTime(StartDate.SelectedDate.Value.Date.Year, StartDate.SelectedDate.Value.Date.Month, StartDate.SelectedDate.Value.Date.Day, hour, minute, seconds);
                }

                string[] theTimevalsStop = stopTime.Text.Split(' ');
                string[] theTimeStop     = theTimevalsStop[0].Split(':');
                if (theTimevalsStop[1] == "PM")
                {
                    hour = System.Convert.ToInt16(theTimeStop[0]) + 12;
                }
                else
                {
                    hour = System.Convert.ToInt16(theTimeStop[0]);
                }
                minute  = System.Convert.ToInt16(theTimeStop[1]);
                seconds = System.Convert.ToInt16(theTimeStop[2]);

                DateTime stop;
                if (StopDate.SelectedDate == null)
                {
                    stop = new DateTime(StopDate.DisplayDate.Year, StopDate.DisplayDate.Month, StopDate.DisplayDate.Day, hour, minute, seconds);
                }
                else
                {
                    stop = new DateTime(StopDate.SelectedDate.Value.Date.Year, StopDate.SelectedDate.Value.Date.Month, StopDate.SelectedDate.Value.Date.Day, hour, minute, seconds);
                }

                parameters.Add(new GPDate("Start_Time__UTC_", start.ToUniversalTime()));
                parameters.Add(new GPDate("Stop_Time__UTC_", stop.ToUniversalTime()));

                gpAircraftComms.ProcessSpatialReference = new SpatialReference(4326);
                gpAircraftComms.SubmitJobAsync(parameters);

                if (_mapWidget != null)
                {
                    _mapWidget.Map.MouseClick -= Map_MouseClick;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error in run: " + ex.Message);
            }
        }
コード例 #51
0
        }         // private GraphicsLayer getRLLayer()

        /// <summary>
        /// Geoprocessor service will be asked
        /// </summary>
        /// <param name="geom"></param>
        private void askGeoprocessor(ESRI.ArcGIS.Client.Geometry.Geometry geom)
        {
            var map  = MapApplication.Current.Map;
            var poly = geom as ESRI.ArcGIS.Client.Geometry.Polygon;

            //poly = poly.Clone();
            //poly.SpatialReference = map.SpatialReference;
            log(string.Format("askGeoprocessor, spatialReference map wkid '{0}', map wkt '{1}', geom wkid '{2}', geom wkt '{3}'",
                              map.SpatialReference.WKID, map.SpatialReference.WKT, poly.SpatialReference.WKID, poly.SpatialReference.WKT));
            double fSeismodens = 0, fProfilelength = 0, fShapeArea = 0;             // result
            var    oldCursor = MapApplication.Current.Map.Cursor;

            // todo: make gp as class member and check bisy state before asking.
            var gp = new Geoprocessor("http://cache.algis.com/ArcGIS/rest/services/" +
                                      "five/seismodens/GPServer/seismoprofiles%20density");

            gp.UpdateDelay = 300;
            var data = new List <GPParameter>();

            data.Add(new GPFeatureRecordSetLayer("inputPolygon", poly));

            gp.Failed += (sender, args) => {
                var tf = args as TaskFailedEventArgs;
                log(string.Format("gp.Failed, message {0}", tf.Error.Message));
                MapApplication.Current.Map.Cursor = oldCursor;
                MessageBox.Show(string.Format("Геопроцессор не может выполнить запрос \n {0}", tf.Error));
            };             // gp.Failed

            gp.JobCompleted += (sender, args) => {
                var    ji   = args as JobInfoEventArgs;
                string msgs = "";
                ji.JobInfo.Messages.ForEach(gpm => msgs += string.Format("\n{0}: {1}", gpm.MessageType, gpm.Description));
                log(string.Format("gp.JobCompleted, job status {0}, job id {1}, msgs {2}",
                                  ji.JobInfo.JobStatus, ji.JobInfo.JobId, msgs));
                MapApplication.Current.Map.Cursor = oldCursor;
                if (ji.JobInfo.JobStatus != esriJobStatus.esriJobSucceeded)
                {
                    MessageBox.Show(string.Format("Геопроцессор не может выполнить запрос \n {0}", msgs));
                    return;
                }

                gp.GetResultDataCompleted += (resSender, resArgs) => {
                    var p  = resArgs as GPParameterEventArgs;
                    var dv = p.Parameter as GPDouble;
                    var ci = new System.Globalization.CultureInfo("en-US");
                    log(string.Format(ci, "gp.GetResultDataCompleted, param name '{0}', value '{1}'", p.Parameter.Name, dv.Value));
                    if (p.Parameter.Name.Contains("seismoDens"))
                    {
                        fSeismodens = dv.Value;
                        gp.GetResultDataAsync(ji.JobInfo.JobId, "profilesLength");
                    }
                    if (p.Parameter.Name.Contains("profilesLength"))
                    {
                        fProfilelength = dv.Value;
                        gp.GetResultDataAsync(ji.JobInfo.JobId, "shapeArea");
                    }
                    if (p.Parameter.Name.Contains("shapeArea"))
                    {
                        fShapeArea = dv.Value;
                        log(string.Format("askGeoprocessor, we got all the results, job done."));
                        MessageBox.Show(string.Format(ci, "Сейсмоплотность {0} км/км2, \t\n суммарная длина профилей {1} км, \t\n " +
                                                      "очерченная площадь {2} км2", fSeismodens, fProfilelength, fShapeArea));
                    }
                };                 // gp.GetResultDataCompleted

                gp.GetResultDataAsync(ji.JobInfo.JobId, "seismoDens");
            };             // gp.JobCompleted

            MapApplication.Current.Map.Cursor = System.Windows.Input.Cursors.Wait;
            gp.SubmitJobAsync(data); // http://help.arcgis.com/en/webapi/silverlight/help/index.html#/Geoprocessing_task/01660000000n000000/
        }                            // private void askGeoprocessor(ESRI.ArcGIS.Client.Geometry.Geometry geom)
コード例 #52
0
ファイル: RuleGraphAttribute.cs プロジェクト: zj8487/HyDM
        private string strSrcFiled       = null; //源图层的字段名
        public override bool Check(ref List <Error> checkResult)
        {
            IFeatureClass  pResultFc  = null;
            IFeatureCursor pResultCur = null;

            try{
                string path = string.Format("{0}\\{1}", System.IO.Path.GetDirectoryName(m_QueryWorkspace.PathName), COMMONCONST.DB_Name_Temp);
                //创建临时操作tempdist.mdb,防止把所有结果库数据存储到query库,引起query库超限
                if (File.Exists(path))
                {
                    Hy.Common.Utility.Esri.AEAccessFactory.OpenPGDB(ref TempWorkspace, path);
                }
                else
                {
                    Hy.Common.Utility.Esri.AEAccessFactory.CreatePGDB(System.IO.Path.GetDirectoryName(m_QueryWorkspace.PathName), COMMONCONST.DB_Name_Temp, ref TempWorkspace);
                }
                if (TempWorkspace == null)
                {
                    SendMessage(enumMessageType.RuleError, "创建临时操作数据库失败!无法执行检查!");
                    return(false);
                }
                // 生成中间结果图层
                // 线物不能穿越地类图斑的检查使用Identity进行,其余都使用Intersect
                // 仅适用于二调质检
                string     Resultlayer = strSrcLayer + "_Intersect";
                IGPProcess gpProcess   = null;
                string     strKey      = strSrcLayer.ToUpper();
                string     inputtables = string.Format(@"""{0}\{1}\{2}"";""{0}\{1}\{3}""", m_BaseWorkspace.PathName, "Dataset", strSrcLayer, strRelLayer);
                Intersect  spIntersect = new Intersect();
                spIntersect.in_features       = inputtables;
                spIntersect.cluster_tolerance = "0.001 Meters";
                spIntersect.join_attributes   = "ALL";
                spIntersect.out_feature_class = TempWorkspace.PathName + "\\" + Resultlayer;
                spIntersect.output_type       = "INPUT";

                gpProcess = spIntersect;
                m_gp      = new Geoprocessor();
                Execute(gpProcess);

                // 等待gp
                int counter = 0;
                while (counter++ < 100)
                {
                    if ((TempWorkspace as IWorkspace2).get_NameExists(esriDatasetType.esriDTFeatureClass, Resultlayer))
                    {
                        break;
                    }

                    System.Threading.Thread.Sleep(100);
                }
                if (m_gp != null)
                {
                    gpProcess = null;
                    m_gp      = null;
                    GC.Collect();
                }
                // 从结果图层中取出错误
                pResultFc = ((IFeatureWorkspace)TempWorkspace).OpenFeatureClass(Resultlayer);
                IQueryFilter pQry = new QueryFilterClass();

                switch (strKey)
                {
                case "LXDW":
                    pQry.WhereClause = "ZLTBBH<>TBBH";
                    break;

                case "XZDW":        //线物不能穿越地类图斑、线物要素的扣除检查
                    if (m_pPara.strAlias.IndexOf("线物不能穿越地类图斑") > -1)
                    {
                        string strClause = " and Avg(len_dist)-sum(shape_length)< " + (1 * this.m_UnitScale).ToString("N7");
                        TempWorkspace.ExecuteSQL(string.Format("delete from XZDW_Intersect where  fid_XZDW in (SELECT fid_xzdw FROM xzdw_Intersect GROUP BY fid_xzdw,fid_dltb having count(0)>1 {0}) and fid_dltb in (SELECT fid_dltb FROM xzdw_Intersect GROUP BY fid_xzdw,fid_dltb having count(0)>1 {0})", strClause));

                        pQry.SubFields   = " Distinct BSM,FID_XZDW,BSM_1";
                        pQry.WhereClause = "len_dist-shape_length>" + (1 * this.m_UnitScale).ToString("N7") + " and shape_length>" + (0.2 * this.m_UnitScale).ToString("N7");
//                            pQry.WhereClause = "len_dist-shape_length>" + (1 * this.m_UnitScale).ToString("N7") + " and shape_length>" + (0.2 * this.m_UnitScale).ToString("N7") + @" and
//                                                    fid_xzdw in
//                                                    (
//                                                    select a.fid_xzdw from
//                                                    (select fid_xzdw from xzdw_Intersect group by fid_xzdw having count(0)>1) as a,
//                                                    (SELECT fid_xzdw FROM xzdw_Intersect GROUP BY fid_xzdw,fid_dltb having count(0)=1) as b
//                                                    where a.fid_xzd9w=b.fid_xzdw
//                                                    )";
                    }
                    else
                    {
                        if (m_pPara.strAlias.IndexOf("线物要素的扣除检查") > -1)
                        {
                            pQry.WhereClause = getkcblsql();
                        }
                    }
                    break;

                default:
                    pQry.WhereClause = "left(ZLDWDM,12)<>XZQDM and shape_Area>" + (400 * this.m_UnitScale).ToString("N7");
                    break;
                }
                pResultCur  = pResultFc.Search(pQry, true);
                checkResult = GetResult(pResultCur as ICursor);

                // 更新状态
                string _strSql = "update LR_ResultEntryRule set TargetFeatClass1= '" + m_pPara.strGeographyObject +
                                 "',TargetFeatClass2='" + m_pPara.strGraphSpeckle +
                                 "|' where RuleInstID='" + this.m_InstanceID + "'";

                Hy.Common.Utility.Data.AdoDbHelper.ExecuteSql(this.m_ResultConnection, _strSql);
                // 释放资源,删除中间结果
                if (pResultCur != null)
                {
                    Marshal.ReleaseComObject(pResultCur);
                    pResultCur = null;
                }
                ((IDataset)pResultFc).Delete();

                return(true);
            }
            catch (Exception ex)
            {
                SendMessage(enumMessageType.Exception, ex.ToString());
                return(false);
            }
            finally
            {
                if (m_gp != null)
                {
                    m_gp = null;
                }
                // 释放资源,删除中间结果
                if (pResultCur != null)
                {
                    Marshal.ReleaseComObject(pResultCur);
                    pResultCur = null;
                }
                if (pResultFc != null)
                {
                    Marshal.ReleaseComObject(pResultFc);
                    pResultFc = null;
                }
                //压缩临时数据库
                IDatabaseCompact databaseCompact = TempWorkspace as IDatabaseCompact;
                if (databaseCompact != null)
                {
                    if (databaseCompact.CanCompact())
                    {
                        databaseCompact.Compact();
                    }
                }
                if (TempWorkspace != null)
                {
                    Marshal.ReleaseComObject(TempWorkspace);
                    TempWorkspace = null;
                }
                GC.Collect();
            }
        }
コード例 #53
0
        private void button1_Click(object sender, EventArgs e)
        {
            double bufferDistance;

            double.TryParse(txtBufferDistance.Text, out bufferDistance);
            if (0.0 == bufferDistance)
            {
                MessageBox.Show("距离设置错误", "Error!");
                return;
            }
            if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(txtOutputPath.Text)) || ".shp" != System.IO.Path.GetExtension(txtOutputPath.Text))
            {
                MessageBox.Show("输出格式错误!");
                return;
            }
            if (comboBoxLayer.Items.Count <= 0)
            {
                return;
            }
            DataOperator  pDo = new DataOperator(m_map, null);
            IFeatureLayer pFl = (IFeatureLayer)pDo.GetLayerbyName(comboBoxLayer.SelectedItem.ToString());
            Geoprocessor  gp  = new Geoprocessor();

            gp.OverwriteOutput = true;
            gp.AddOutputsToMap = true;
            string unit = "Kilometers";

            ESRI.ArcGIS.AnalysisTools.Buffer buffer = new ESRI.ArcGIS.AnalysisTools.Buffer(pFl, txtOutputPath.Text, Convert.ToString(bufferDistance) + "" + unit);
            try
            {
                IGeoProcessorResult results = (IGeoProcessorResult)gp.Execute(buffer, null);
            }
            catch
            {
            }
            string fileDirectory = txtOutputPath.Text.ToString().Substring(0, txtOutputPath.Text.LastIndexOf("\\"));
            int    j;

            j = txtOutputPath.Text.LastIndexOf("\\");
            string            tmpstr = txtOutputPath.Text.ToString().Substring(j + 1);
            IWorkspaceFactory pWsf   = new ShapefileWorkspaceFactory() as IWorkspaceFactory;
            IWorkspace        pWs    = pWsf.OpenFromFile(fileDirectory, 0);
            IFeatureWorkspace pFs    = pWs as IFeatureWorkspace;
            IFeatureClass     pFc    = pFs.OpenFeatureClass(tmpstr);
            IFeatureLayer     pfl    = new FeatureLayer() as IFeatureLayer;

            pfl.FeatureClass = pFc;
            IRgbColor pColor = new RgbColor() as IRgbColor;

            pColor.Red          = 255;
            pColor.Green        = 0;
            pColor.Blue         = 0;
            pColor.Transparency = 255;
            ILineSymbol pOutline = new SimpleLineSymbol();

            pOutline.Width      = 2;
            pOutline.Color      = pColor;
            pColor              = new RgbColor();
            pColor.Red          = 255;
            pColor.Green        = 0;
            pColor.Blue         = 0;
            pColor.Transparency = 100;
            ISimpleFillSymbol pFillSymbol = new SimpleFillSymbol();

            pFillSymbol.Color   = pColor;
            pFillSymbol.Outline = pOutline;
            pFillSymbol.Style   = esriSimpleFillStyle.esriSFSSolid;
            ISimpleRenderer  pRen;
            IGeoFeatureLayer pGeofl = pfl as IGeoFeatureLayer;

            pRen            = pGeofl.Renderer as ISimpleRenderer;
            pRen.Symbol     = pFillSymbol as ISymbol;
            pGeofl.Renderer = pRen as IFeatureRenderer;
            ILayerEffects pLayerEffects = pfl as ILayerEffects;

            pLayerEffects.Transparency = 150;
            m_mapControl.AddLayer((ILayer)pfl, 0);
            MessageBox.Show(comboBoxLayer.SelectedText + "缓冲区生成成功!");
        }
コード例 #54
0
        private void btOk_Click(object sender, EventArgs e)
        {
            int    sExcute = 0;
            int    sIsNul  = 0;
            int    sIsThan = 0;
            double sAll    = 0;

            for (int i = 0; i < this.dataGridView1.Rows.Count - 1; i++)
            {
                if (this.dataGridView1.Rows[i].Cells[1].Value == null)
                {
                    sIsNul = 1;    //如果权重存在空值,sIsNul=1
                }
                else
                {
                    double ssRow = double.Parse(this.dataGridView1.Rows[i].Cells[1].Value.ToString());
                    sAll = sAll + ssRow;
                }
            }
            if ((sAll != 1.0) && (sIsNul == 0))
            {
                sIsThan = 1;  //如果权重之和不为1,sIsThan=1
            }
            //判断权重是否为空
            if (sIsNul == 1)
            {
                MessageBox.Show("请您输入数据权重!");
            }
            //判断权重之和是否等于1
            if (sIsThan == 1)
            {
                MessageBox.Show("请您确保输入的权重之和等于1");
            }
            if (txtSavePath.Equals(""))
            {
                MessageBox.Show("请选择输出路径!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            //准备后续执行

            if ((sIsNul == 0) && (sIsThan == 0) && (Onebt == 1))
            {
                //现创建一个存放临时文件的临时文件夹
                string newPath = System.IO.Path.Combine(Temfile, "");
                System.IO.Directory.CreateDirectory(newPath);
                this.rtxtState.AppendText("正在执行,请您耐心等待...\n");
                this.rtxtState.ScrollToCaret();
                this.rtxtState.AppendText("准备调用GP工具箱...\n");
                this.rtxtState.ScrollToCaret();
                IVariantArray parameters = new VarArrayClass();
                Geoprocessor  GP         = new Geoprocessor();

                ESRI.ArcGIS.SpatialAnalystTools.RasterCalculator sCalR = new ESRI.ArcGIS.SpatialAnalystTools.RasterCalculator();
                this.rtxtState.AppendText("开始遍历读取表中数据...\n");
                this.rtxtState.ScrollToCaret();
                this.rtxtState.AppendText("开始对栅格数据重分类...\n");
                this.rtxtState.ScrollToCaret();
                for (int m = 0; m < this.dataGridView1.Rows.Count - 1; m++)
                {
                    string sFileName;
                    sFileName = Temfile + "\\重分类" + (m + 1).ToString() + ".tif";
                    //计算栅格最小值
                    double         dMin0 = 0;
                    IGeoProcessor2 gp    = new GeoProcessorClass();
                    gp.OverwriteOutput = true;
                    // Create a variant array to hold the parameter values.
                    IVariantArray       parameters2 = new VarArrayClass();
                    IGeoProcessorResult result      = new GeoProcessorResultClass();
                    // Set parameter values.
                    parameters2.Add(this.dataGridView1.Rows[m].Cells[0].Value.ToString());
                    parameters2.Add("MINIMUM");
                    result = gp.Execute("GetRasterProperties_management", parameters2, null);
                    dMin0  = (double)result.ReturnValue;
                    int dMin = (int)dMin0;
                    //计算栅格最大值
                    double         dMax0 = 0;
                    IGeoProcessor2 gp2   = new GeoProcessorClass();
                    gp2.OverwriteOutput = true;
                    // Create a variant array to hold the parameter values.
                    IVariantArray       parameters3 = new VarArrayClass();
                    IGeoProcessorResult result3     = new GeoProcessorResultClass();
                    // Set parameter values.
                    parameters3.Add(this.dataGridView1.Rows[m].Cells[0].Value.ToString());
                    parameters3.Add("MAXIMUM");
                    result3 = gp2.Execute("GetRasterProperties_management", parameters3, null);
                    dMax0   = (double)result3.ReturnValue;
                    int dMax = (int)dMax0;
                    //计算分类区间
                    int Avera     = (dMax - dMin) / 4;
                    int interval1 = dMin + Avera;
                    int interval2 = dMin + 2 * Avera;
                    int interval3 = dMin + 3 * Avera;
                    //开始对数据进行重分类
                    ESRI.ArcGIS.SpatialAnalystTools.Reclassify tReclass = new ESRI.ArcGIS.SpatialAnalystTools.Reclassify();
                    tReclass.in_raster      = this.dataGridView1.Rows[m].Cells[0].Value.ToString();
                    tReclass.missing_values = "NODATA";
                    tReclass.out_raster     = sFileName;
                    tReclass.reclass_field  = "VALUE";
                    //tReclass.remap = "1400 2176 1;2176 2538 2;2538 3040 3;3040 4073 4";
                    tReclass.remap = dMin.ToString() + " " + interval1.ToString() + " " + "1;" + interval1.ToString() + " " + interval2.ToString() + " " + "2;" + interval2.ToString() + " " + interval3.ToString() + " " + "3;" + interval3.ToString() + " " + dMax.ToString() + " " + "4;";
                    // ScrollToBottom("Reclassify");
                    //tGeoResult = (IGeoProcessorResult)tGp.Execute(tReclass, null);
                    GP.Execute(tReclass, null);
                }
                this.rtxtState.AppendText("输入数据重分类完成...\n");
                this.rtxtState.ScrollToCaret();
                //开始进行栅格计算
                this.rtxtState.AppendText("开始准备进行栅格加权运算...\n");
                this.rtxtState.ScrollToCaret();
                string sFileName2 = "重分类";
                string sRoad      = Temfile + "\\重分类";
                for (int n = 1; n < this.dataGridView1.Rows.Count; n++)
                {
                    sFileName2 = sRoad + n.ToString() + "." + "tif";
                    strExp     = "\"" + sFileName2 + "\"" + "*" + double.Parse(this.dataGridView1.Rows[n - 1].Cells[1].Value.ToString());
                    if (n < this.dataGridView1.Rows.Count - 1)
                    {
                        sR2 = sR2 + strExp + "+";
                    }
                    else
                    {
                        sR2 = sR2 + strExp;
                    }
                }
                sR3 = sR2;
                sCalR.expression = sR3;
                sR = Temfile + "\\地质灾害.tif";
                sCalR.output_raster = sR;
                GP.Execute(sCalR, null);
                this.rtxtState.AppendText("栅格计算成功,得到地质灾害分布栅格影像...\n");
                this.rtxtState.ScrollToCaret();
                this.rtxtState.AppendText("开始对地质灾害影像进行重分类...\n");
                this.rtxtState.ScrollToCaret();
                //开始准备对生成的地质灾害.tif进行分类
                //计算栅格最小值
                double         dMin02 = 0;
                IGeoProcessor2 gp3    = new GeoProcessorClass();
                gp3.OverwriteOutput = true;
                // Create a variant array to hold the parameter values.
                IVariantArray       parameters22 = new VarArrayClass();
                IGeoProcessorResult result22     = new GeoProcessorResultClass();
                // Set parameter values.
                parameters22.Add(sR);
                parameters22.Add("MINIMUM");
                result22 = gp3.Execute("GetRasterProperties_management", parameters22, null);
                dMin02   = (double)result22.ReturnValue;

                //计算栅格最大值
                double         dMax02 = 0;
                IGeoProcessor2 gp4    = new GeoProcessorClass();
                gp4.OverwriteOutput = true;
                // Create a variant array to hold the parameter values.
                IVariantArray       parameters33 = new VarArrayClass();
                IGeoProcessorResult result33     = new GeoProcessorResultClass();
                // Set parameter values.
                parameters33.Add(sR);
                parameters33.Add("MAXIMUM");
                result33 = gp4.Execute("GetRasterProperties_management", parameters33, null);
                dMax02   = (double)result33.ReturnValue;

                //计算分类区间
                double Avera2     = (dMax02 - dMin02) / 4;
                double interval12 = dMin02 + Avera2;
                double interval22 = dMin02 + 2 * Avera2;
                double interval32 = dMin02 + 3 * Avera2;

                //开始对地质灾害.tif重分类
                ESRI.ArcGIS.SpatialAnalystTools.Reclassify tReclass2 = new ESRI.ArcGIS.SpatialAnalystTools.Reclassify();

                tReclass2.in_raster      = Temfile + "\\地质灾害.tif";
                tReclass2.missing_values = "NODATA";
                tReclass2.out_raster     = txtSavePath.Text;
                tReclass2.reclass_field  = "VALUE";
                //tReclass.remap = "1400 2176 1;2176 2538 2;2538 3040 3;3040 4073 4";
                tReclass2.remap = dMin02.ToString() + " " + interval12.ToString() + " " + "1;" + interval12.ToString() + " " + interval22.ToString() + " " + "2;" + interval22.ToString() + " " + interval32.ToString() + " " + "3;" + interval32.ToString() + " " + dMax02.ToString() + " " + "4;";
                // ScrollToBottom("Reclassify");
                //tGeoResult = (IGeoProcessorResult)tGp.Execute(tReclass, null);
                GP.Execute(tReclass2, null);
                //删除临时文件夹
                string deleteFile = Temfile;
                DeleteFolder(deleteFile);
                this.rtxtState.AppendText("完成地质灾害生态红线的划分,已将结果成功保存...\n");
                this.rtxtState.ScrollToCaret();
            }
        }
コード例 #55
0
 static ArcExtensions2()
 {
     _gp = new Geoprocessor();
 }
コード例 #56
0
ファイル: GP.cs プロジェクト: rs-sdust/GFStatistics
 public GP()
 {
     this._gp = new Geoprocessor();
     this._gp.OverwriteOutput = true;
 }
コード例 #57
0
 public DataUploader(FieldValidator fieldValidator, Geoprocessor geoprocessor)
 {
     _fieldValidator = fieldValidator;
     _geoprocessor   = geoprocessor;
 }
コード例 #58
0
        /// <summary>
        /// 道路风险计算
        /// </summary>
        /// <param name="workPath">存储路径</param>
        /// <param name="roadEvalPath">道路评价结果 </param>
        /// <param name="roadRainsShpPath">加了雨量字段的道路缓冲区</param>
        /// <returns></returns>
        public bool RoadRaskCaulte(string roadEvalName, string roadRainsName, string saveWorkspace)
        {
            //读取 道路评价结果栅格数据的信息
            RasterHelper rh = new RasterHelper();
            //IRasterWorkspace rasterWorkspace =  new RasterLayer();
            IWorkspaceFactory rWorkspaceFactory = new RasterWorkspaceFactory();
            IWorkspace        SWorkspace        = rWorkspaceFactory.OpenFromFile(saveWorkspace, 0);
            IRasterWorkspace  rasterWorkspace   = SWorkspace as IRasterWorkspace;

            IRasterDataset rasterDt = rasterWorkspace.OpenRasterDataset(roadEvalName);

            //  var t = rh.GetRasterProps(rasterDt);
            IRasterLayer rasterLayer = new RasterLayer();

            rasterLayer.CreateFromFilePath(saveWorkspace + "\\" + roadEvalName);
            IRaster pRaster = rasterLayer.Raster;

            IRasterProps rasterProps = (IRasterProps)pRaster;;//存储了栅格信息

            //初始化GP工具
            Geoprocessor gp = new Geoprocessor();

            gp.OverwriteOutput = true;
            //string path = @"D:\GISTest";
            //gp.SetEnvironmentValue("workspace", path);
            //道路缓冲区 根据雨量转栅格
            FeatureToRaster featureToRaster = new FeatureToRaster();

            featureToRaster.cell_size   = rasterProps.MeanCellSize().X;//这里可以提前规定一个值,而不是每次去读取
            featureToRaster.in_features = OpenFeatureClass(saveWorkspace + "\\" + roadRainsName);
            featureToRaster.out_raster  = saveWorkspace + "\\roadGrid";
            featureToRaster.field       = "RAINS";//这个字段需要矢量图层中加上
            try
            {
                gp.Execute(featureToRaster, null);
            }
            catch (Exception ex)
            {
                Console.WriteLine("矢量转栅格失败!");
                return(false);
            }

            //栅格计算器 计算风险级数
            IMapAlgebraOp  mapAlgebra     = new RasterMapAlgebraOpClass();
            IRasterDataset roadEvalRaster = OpenRasterDataSet(rasterWorkspace, roadEvalName);
            IRasterDataset roadGridRaster = OpenRasterDataSet(rasterWorkspace, saveWorkspace + @"\roadGrid");
            IGeoDataset    geo1           = roadEvalRaster as IGeoDataset;
            IGeoDataset    geo2           = roadGridRaster as IGeoDataset;

            mapAlgebra.BindRaster(geo1, "EvalRaster");
            mapAlgebra.BindRaster(geo2, "RoadRains");
            IGeoDataset raskDataset = mapAlgebra.Execute("[EvalRaster] * [RoadRains] / 25");//然后存储  表达式必须间隔开
            ISaveAs     saveAs      = raskDataset as ISaveAs;

            saveAs.SaveAs("roadPre", SWorkspace, "");
            //加入图层
            IRasterLayer rasterLayer2 = new RasterLayer();

            rasterLayer2.CreateFromFilePath(saveWorkspace + "\\" + "roadPre");

            MainFrom.m_mapControl.AddLayer(rasterLayer2, 0);
            //MainFrom.m_mapControl.Refresh(esriViewDrawPhase.esriViewGeography, null, null);
            MainFrom.m_pTocControl.Update();
            //将生成的风险栅格重分类
            //<0.2	一级:可能性小
            //0.2-0.4	二级:可
            //能性较小
            //0.4-0.6	三级:可能性较大
            //0.6-0.8	四级:可能性大
            //>0.8	五级:可能性很大
            // 输入:raskDataset

            // 输出:geoDataset_result
            IReclassOp pReclassOp   =  new RasterReclassOpClass();
            INumberRemap pNumRemap  =  new NumberRemapClass();
            IDictionary <int, RoadRange> roadRanges = this.roadRiskConfig.GetRoadRiskLevelFromConfig();

            foreach (var v in roadRanges)
            {
                pNumRemap.MapRange(v.Value.MinValue, v.Value.MaxValue, v.Key);
            }

            /*
             * pNumRemap.MapRange(0, 0.2, 1);
             * pNumRemap.MapRange(0.2, 0.4, 2);
             * pNumRemap.MapRange(0.4, 0.6, 3);
             * pNumRemap.MapRange(0.6, 0.8, 4);
             * pNumRemap.MapRange(0.8,1000,5);
             */
            //pNumRemap.MapRangeToNoData(-1000,0);
            //pNumRemap.MapRangeToNoData(1000, 20000);
            IRemap pRemap = pNumRemap as IRemap;

            // 重分类
            // geoDataset为上一步得到的栅格
            //     IGeoDataset geoDataset_result = pReclassOp.ReclassByRemap(raskDataset, pRemap, true);//还没有测试成功


            // RasterCalculator rasterCalculator = new RasterCalculator("[EvalRaster]*[RoadRains]/25", saveWorkspace + @"\RainEval.tif");
            try
            {
                // gp.Execute(rasterCalculator, null);
            }
            catch (Exception ex)
            {
                Debug.Print(ex.Message);
                for (int i = 0; i < gp.MessageCount; i++)
                {
                    Debug.Print(gp.GetMessage(i));
                }
                Console.WriteLine("栅格计算失败!");
                return(false);
            }
            return(true);
        }
コード例 #59
0
        private async void StartGP_Click(object sender, RoutedEventArgs e)
        {
            StartGP.IsEnabled = false;
            ClearGraphics();
            ClearButton.Visibility         = Windows.UI.Xaml.Visibility.Collapsed;
            ProcessingTextBlock.Visibility = Visibility.Collapsed;

            var inputPolyline = await mapView1.Editor.RequestShapeAsync(DrawShape.Polyline);

            var inputGraphic = new Graphic {
                Geometry = inputPolyline
            };
            GraphicsLayer inputLayer = mapView1.Map.Layers["InputLayer"] as GraphicsLayer;

            inputLayer.Graphics.Add(inputGraphic);

            MyProgressRing.Visibility = Visibility.Visible;
            MyProgressRing.IsActive   = true;

            string message = null;

            Geoprocessor task           = new Geoprocessor(new Uri(ServiceUri));
            var          inputParameter = new GPInputParameter();

            inputParameter.GPParameters.Add(new GPFeatureRecordSetLayer("Input_Features", inputPolyline));
            inputParameter.GPParameters.Add(new GPLinearUnit("Linear_unit", LinearUnits.Miles, Int32.Parse(DistanceTextBox.Text)));
            try
            {
                //Submit the job and await the results
                var gpJobInfo = await task.SubmitJobAsync(inputParameter);

                //Poll the server every 5 seconds for the status of the job.
                //Cancelled, Cancelling, Deleted, Deleting, Executing, Failed, New, Submitted, Succeeded, TimedOut, Waiting
                while (gpJobInfo.JobStatus != GPJobStatus.Cancelled &&
                       gpJobInfo.JobStatus != GPJobStatus.Deleted &&
                       gpJobInfo.JobStatus != GPJobStatus.Failed &&
                       gpJobInfo.JobStatus != GPJobStatus.Succeeded &&
                       gpJobInfo.JobStatus != GPJobStatus.TimedOut)
                {
                    gpJobInfo = await task.CheckJobStatusAsync(gpJobInfo.JobID);

                    await Task.Delay(5000);
                }

                //Now that the job is completed, check whether the service returned the results as Features or as a GPResultImageLayer.
                //This can happen if the number of features to return exceeds the limit set on the service
                if (gpJobInfo.JobStatus == GPJobStatus.Succeeded)
                {
                    var resultData = await task.GetResultDataAsync(gpJobInfo.JobID, "Clipped_Counties");

                    if (resultData is GPFeatureRecordSetLayer)
                    {
                        GPFeatureRecordSetLayer gpLayer = resultData as GPFeatureRecordSetLayer;
                        if (gpLayer.FeatureSet.Features.Count == 0)
                        {
                            var resultImageLayer = await task.GetResultImageLayerAsync(gpJobInfo.JobID, "Clipped_Counties");

                            GPResultImageLayer gpImageLayer = resultImageLayer;
                            gpImageLayer.Opacity = 0.5;
                            mapView1.Map.Layers.Add(gpImageLayer);
                            ProcessingTextBlock.Visibility = Visibility.Visible;
                            ProcessingTextBlock.Text       = "Greater than 500 features returned.  Results drawn using map service.";
                            return;
                        }
                        GraphicsLayer resultLayer = mapView1.Map.Layers["MyResultGraphicsLayer"] as GraphicsLayer;
                        foreach (Graphic g in gpLayer.FeatureSet.Features)
                        {
                            resultLayer.Graphics.Add(g);
                        }
                    }
                }
                MyProgressRing.Visibility = Visibility.Collapsed;
                MyProgressRing.IsActive   = false;

                ClearButton.Visibility = Visibility.Visible;
                StartGP.IsEnabled      = true;
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }

            if (message != null)
            {
                await new MessageDialog(message, "GP Failed").ShowAsync();
            }
        }
コード例 #60
0
        private static void ConvertPersonalGeodatabaseToFileGeodatabase()
        {
            // Initialize the Geoprocessor
            Geoprocessor geoprocessor = new Geoprocessor();

            // Allow for the overwriting of file geodatabases, if they previously exist.
            geoprocessor.OverwriteOutput = true;

            // Set the workspace to a folder containing personal geodatabases.
            geoprocessor.SetEnvironmentValue("workspace", @"C:\data");

            // Identify personal geodatabases.
            IGpEnumList workspaces = geoprocessor.ListWorkspaces("*", "Access");
            string      workspace  = workspaces.Next();

            while (workspace != "")
            {
                // Set workspace to current personal geodatabase
                geoprocessor.SetEnvironmentValue("workspace", workspace);

                // Create a file geodatabase with the same name as the personal geodatabase
                string gdbname = System.IO.Path.GetFileName(workspace).Replace(".mdb", "");
                string dirname = System.IO.Path.GetDirectoryName(workspace);

                // Execute CreateFileGDB tool
                CreateFileGDB createFileGDBTool = new CreateFileGDB(dirname, gdbname + ".gdb");
                geoprocessor.Execute(createFileGDBTool, null);

                // Initialize the Copy Tool
                Copy copyTool = new Copy();

                // Identify feature classes and copy to file geodatabase
                IGpEnumList fcs = geoprocessor.ListFeatureClasses("", "", "");
                string      fc  = fcs.Next();
                while (fc != "")
                {
                    Console.WriteLine("Copying " + fc + " to " + gdbname + ".gdb");
                    copyTool.in_data  = fc;
                    copyTool.out_data = dirname + "\\" + gdbname + ".gdb" + "\\" + fc;
                    geoprocessor.Execute(copyTool, null);
                    fc = fcs.Next();
                }

                // Identify feature datasets and copy to file geodatabase
                IGpEnumList fds = geoprocessor.ListDatasets("", "");
                string      fd  = fds.Next();
                while (fd != "")
                {
                    Console.WriteLine("Copying " + fd + " to " + gdbname + ".gdb");
                    copyTool.in_data   = fd;
                    copyTool.data_type = "FeatureDataset";
                    copyTool.out_data  = dirname + "\\" + gdbname + ".gdb" + "\\" + fd;
                    try
                    {
                        geoprocessor.Execute(copyTool, null);
                    }
                    catch (Exception ex)
                    {
                        object sev = null;
                        System.Windows.Forms.MessageBox.Show(ex.Message);
                    }
                    fd = fds.Next();
                }

                // Identify tables and copy to file geodatabase
                IGpEnumList tbls = geoprocessor.ListTables("", "");
                string      tbl  = tbls.Next();
                while (tbl != "")
                {
                    Console.WriteLine("Copying " + tbl + " to " + gdbname + ".gdb");
                    copyTool.in_data  = tbl;
                    copyTool.out_data = dirname + "\\" + gdbname + ".gdb" + "\\" + tbl;
                    geoprocessor.Execute(copyTool, null);
                    tbl = tbls.Next();
                }

                workspace = workspaces.Next();
            }
        }