private void gpSateEphemeris_JobCompleted(object sender, JobInfoEventArgs e) { try { if (_graphicsLayerPoly == null) { _graphicsLayerPoly = new client.GraphicsLayer(); _graphicsLayerPoly.ID = "SensorFootprints"; client.AcceleratedDisplayLayers aclyrs = _mapWidget.Map.Layers.FirstOrDefault(lyr => lyr is client.AcceleratedDisplayLayers) as client.AcceleratedDisplayLayers; if (aclyrs.Count() > 0) { aclyrs.ChildLayers.Add(_graphicsLayerPoly); } } else { _graphicsLayerPoly.Graphics.Clear(); } if (_graphicsLayerLine == null) { _graphicsLayerLine = new client.GraphicsLayer(); _graphicsLayerLine.ID = "EphemerisLines"; client.AcceleratedDisplayLayers aclyrs = _mapWidget.Map.Layers.FirstOrDefault(lyr => lyr is client.AcceleratedDisplayLayers) as client.AcceleratedDisplayLayers; if (aclyrs.Count() > 0) { aclyrs.ChildLayers.Add(_graphicsLayerLine); } } else { _graphicsLayerLine.Graphics.Clear(); } if (_graphicsLayerPoint == null) { _graphicsLayerPoint = new client.GraphicsLayer(); _graphicsLayerPoint.ID = "EphemerisPoints"; client.AcceleratedDisplayLayers aclyrs = _mapWidget.Map.Layers.FirstOrDefault(lyr => lyr is client.AcceleratedDisplayLayers) as client.AcceleratedDisplayLayers; if (aclyrs.Count() > 0) { aclyrs.ChildLayers.Add(_graphicsLayerPoint); } } else { _graphicsLayerPoint.Graphics.Clear(); } ResourceDictionary mydictionary = new ResourceDictionary(); mydictionary.Source = new Uri("/SatelliteEphemerisGenerationAddin;component/SymbolDictionary.xaml", UriKind.RelativeOrAbsolute); gp = sender as Geoprocessor; _jobid = e.JobInfo.JobId; gp.GetResultDataAsync(e.JobInfo.JobId, "SensorFootprints", "Footprints"); gp.GetResultDataCompleted += gp_GetResultDataCompleted; } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); } }
private void GeoprocessorTask_JobCompleted(object sender, JobInfoEventArgs e) { jobid = null; if (e.JobInfo.JobStatus == esriJobStatus.esriJobSucceeded) { _geoprocessorTask.GetResultDataAsync(e.JobInfo.JobId, "ServiceAreas"); } }
void _geoprocessorTask_JobCompleted(object sender, JobInfoEventArgs e) { if (e.JobInfo.JobStatus != esriJobStatus.esriJobSucceeded) { MessageBox.Show("Extract Data task failed to complete"); return; } _geoprocessorTask.GetResultDataAsync(e.JobInfo.JobId, "Output_Zip_File"); }
void gp_GetResultDataCompleted(object sender, GPParameterEventArgs e) { try { ResourceDictionary mydictionary = new ResourceDictionary(); mydictionary.Source = new Uri("/SatelliteEphemerisGenerationAddin;component/SymbolDictionary.xaml", UriKind.RelativeOrAbsolute); GPFeatureRecordSetLayer gpFLayer = e.Parameter as GPFeatureRecordSetLayer; if (gpFLayer.FeatureSet.Features.Count > 0) { foreach (client.Graphic g in gpFLayer.FeatureSet.Features) { if (e.UserState.ToString() == "Footprints") { g.Symbol = mydictionary["BasicFillSymbol_Yellow_Trans_6"] as client.Symbols.SimpleFillSymbol; _graphicsLayerPoly.Graphics.Add(g); } else if (e.UserState.ToString() == "Lines") { g.Symbol = mydictionary["BasicLineSymbol_Green_3"] as client.Symbols.SimpleLineSymbol; _graphicsLayerLine.Graphics.Add(g); } else if (e.UserState.ToString() == "Points") { g.Symbol = mydictionary["BluePin"] as client.Symbols.MarkerSymbol; _graphicsLayerPoint.Graphics.Add(g); } } } if (e.UserState.ToString() == "Footprints") { gp.GetResultDataAsync(_jobid, "EphemerisLines", "Lines"); } else if (e.UserState.ToString() == "Lines") { gp.GetResultDataAsync(_jobid, "EphemerisPoints", "Points"); } } catch (Exception ex) { MessageBox.Show("Error in GetResultDataCompleted, UserState: " + e.UserState.ToString()); MessageBox.Show("Error in GetResultDataCompleted, Exception: " + ex.Message); } }
public async void Clip() { //get the user's input line var inputLine = await this.mapView.Editor.RequestShapeAsync(DrawShape.Polyline) as Polyline; // clear the graphics layers this.resultGraphicsLayer.Graphics.Clear(); this.inputGraphicsLayer.Graphics.Clear(); // add new graphic to layer this.inputGraphicsLayer.Graphics.Add(new Graphic { Geometry = inputLine, Symbol = this.simpleInputLineSymbol }); // add the parameters var parameter = new GPInputParameter(); parameter.GPParameters.Add(new GPFeatureRecordSetLayer("Input_Features", inputLine)); parameter.GPParameters.Add(new GPLinearUnit("Linear_unit", LinearUnits.Miles, this.Distance)); // poll the task var result = await SubmitAndPollStatusAsync(parameter); // add successful results to the map if (result.JobStatus == GPJobStatus.Succeeded) { this.Status = "Finished processing. Retrieving results..."; var resultData = await gpTask.GetResultDataAsync(result.JobID, "Clipped_Counties"); if (resultData is GPFeatureRecordSetLayer) { GPFeatureRecordSetLayer gpLayer = resultData as GPFeatureRecordSetLayer; if (gpLayer.FeatureSet.Features.Count == 0) { // the the map service results var resultImageLayer = await gpTask.GetResultImageLayerAsync(result.JobID, "Clipped_Counties"); // make the result image layer opaque GPResultImageLayer gpImageLayer = resultImageLayer; gpImageLayer.Opacity = 0.5; this.mapView.Map.Layers.Add(gpImageLayer); this.Status = "Greater than 500 features returned. Results drawn using map service."; return; } // get the result features and add them to the GraphicsLayer var features = gpLayer.FeatureSet.Features; foreach (Feature feature in features) { this.resultGraphicsLayer.Graphics.Add(feature as Graphic); } } this.Status = "Success!!!"; } }
// *********************************************************************************** // * ..ERGChemcial GP Tool Job Completed // *********************************************************************************** private void ergChemicalGeoprocessorTask_JobCompleted(object sender, JobInfoEventArgs e) { Geoprocessor geoprocessorTask = sender as Geoprocessor; geoprocessorTask.GetResultDataCompleted += ergGPTask_GetResultDataCompleted; geoprocessorTask.Failed += new EventHandler <TaskFailedEventArgs>(GeoprocessorTask_Failed); _gpJobId = e.JobInfo.JobId; geoprocessorTask.GetResultDataAsync(e.JobInfo.JobId, "output_areas"); }
// *********************************************************************************** // * ... Nearest weather station located... get the wind info from this station // *********************************************************************************** // *********************************************************************************** // * ..ERG Placard GP Tool Job Completed // *********************************************************************************** private void findNearestWSGPTask_JobCompleted(object sender, JobInfoEventArgs e) { Geoprocessor geoprocessorTask = sender as Geoprocessor; geoprocessorTask.GetResultDataCompleted += findNearestWSGPTask_GetResultDataCompleted; geoprocessorTask.Failed += new EventHandler <TaskFailedEventArgs>(GeoprocessorTask_Failed); _gpJobId = e.JobInfo.JobId; geoprocessorTask.GetResultDataAsync(e.JobInfo.JobId, "SACPoint_shp"); }
private void gpAircraftRouteGen_JobCompleted(object sender, JobInfoEventArgs e) { try { Geoprocessor gpAircraftRouteGen = sender as Geoprocessor; gpAircraftRouteGen.GetResultDataCompleted += gp_GetResultDataCompleted; gpAircraftRouteGen.GetResultDataAsync(e.JobInfo.JobId, "Computed_Points"); } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); } }
// Calls the ExtractData service and prompts the user for saving the results private async void ExtractDataButton_Click(object sender, RoutedEventArgs e) { try { uiPanel.IsEnabled = false; progress.Visibility = txtStatus.Visibility = Visibility.Visible; var layersToClip = listLayers.SelectedItems.OfType <string>().Select(s => new GPString(s, s)).ToList(); if (layersToClip == null || layersToClip.Count == 0) { throw new ApplicationException("Please select layers to extract data from."); } if (graphicsLayer.Graphics.Count == 0) { throw new ApplicationException("Please digitize an area of interest polygon on the map."); } var parameter = new GPInputParameter() { OutSpatialReference = SpatialReferences.WebMercator }; parameter.GPParameters.Add(new GPMultiValue <GPString>("Layers_to_Clip", layersToClip)); parameter.GPParameters.Add(new GPFeatureRecordSetLayer("Area_of_Interest", graphicsLayer.Graphics[0].Geometry)); parameter.GPParameters.Add(new GPString("Feature_Format", (string)comboFormat.SelectedItem)); var result = await SubmitAndPollStatusAsync(parameter); if (result.JobStatus == GPJobStatus.Succeeded) { txtStatus.Text = "Finished processing. Retrieving results..."; var outParam = await _gpTask.GetResultDataAsync(result.JobID, "Output_Zip_File") as GPDataFile; if (outParam != null && outParam.Uri != null) { await SaveResultsToFile(outParam); } } } catch (Exception ex) { MessageBox.Show(ex.Message, "Sample Error"); } finally { uiPanel.IsEnabled = true; progress.Visibility = txtStatus.Visibility = Visibility.Collapsed; } }
private void GeoprocessorTask_JobCompleted(object sender, JobInfoEventArgs e) { jobid = null; InformationText.Text = descText; if (e.JobInfo.JobStatus == esriJobStatus.esriJobSucceeded) { _geoprocessorTask.GetResultDataAsync(e.JobInfo.JobId, "ServiceAreas"); } if (e.JobInfo.JobStatus == esriJobStatus.esriJobFailed) { MessageBox.Show("Geoprocessing service failed! Check the Geoproccessing Parameters."); } }
private void GPService_JobCompleted(object sender, JobInfoEventArgs e) { this.IsBusy = false; this.ToggleWidgetContent(1); txtExtractionStatus.Visibility = Visibility.Collapsed; if (e.JobInfo.JobStatus == esriJobStatus.esriJobSucceeded) { lnkExtractionOutput.Visibility = Visibility.Visible; txtJobErrorMessage.Visibility = Visibility.Collapsed; gpService.GetResultDataAsync(e.JobInfo.JobId, "Output_Zip_File"); // parameterName } else { txtJobErrorMessage.Text = e.JobInfo.Messages[0].Description; txtJobErrorMessage.Visibility = Visibility.Visible; lnkExtractionOutput.Visibility = Visibility.Collapsed; } }
private void GeoprocessorTask_JobCompleted(object sender, JobInfoEventArgs e) { Geoprocessor geoprocessorTask = sender as Geoprocessor; geoprocessorTask.GetResultDataCompleted += (s1, ev1) => { GraphicsLayer graphicsLayer = MyMap.Layers["MyResultGraphicsLayer"] as GraphicsLayer; if (ev1.Parameter is GPFeatureRecordSetLayer) { GPFeatureRecordSetLayer gpLayer = ev1.Parameter as GPFeatureRecordSetLayer; if (gpLayer.FeatureSet.Features.Count == 0) { geoprocessorTask.GetResultImageLayerCompleted += (s2, ev2) => { GPResultImageLayer gpImageLayer = ev2.GPResultImageLayer; gpImageLayer.Opacity = 0.5; MyMap.Layers.Add(gpImageLayer); ProcessingTextBlock.Text = "Greater than 500 features returned. Results drawn using map service."; _processingTimer.Stop(); }; geoprocessorTask.GetResultImageLayerAsync(e.JobInfo.JobId, "Clipped_Counties"); return; } foreach (Graphic graphic in gpLayer.FeatureSet.Features) { graphic.Symbol = LayoutRoot.Resources["ClipFeaturesFillSymbol"] as ESRI.ArcGIS.Client.Symbols.Symbol; graphicsLayer.Graphics.Add(graphic); } } ProcessingTextBlock.Visibility = Visibility.Collapsed; _processingTimer.Stop(); }; geoprocessorTask.GetResultDataAsync(e.JobInfo.JobId, "Clipped_Counties"); }
void gp_JobCompleted(object sender, Client.Tasks.JobInfoEventArgs e) { if (e.JobInfo.JobStatus == esriJobStatus.esriJobFailed) { IsExecuting = false; ExecutingText = ESRI.ArcGIS.Mapping.GP.Resources.Strings.JobFailed; asyncErrors.AddRange(e.JobInfo.Messages.Where(p => p.MessageType == GPMessageType.Error).Select(p => new Exception(p.Description))); fireAsyncCompleteEvent(); } else { ExecutingText = ESRI.ArcGIS.Mapping.GP.Resources.Strings.GettingResults; asyncResultsExpected = Configuration.OutputParameters.Count; JobID = e.JobInfo.JobId; foreach (ParameterSupport.ParameterConfig param in Configuration.OutputParameters) { if (!resultRequestedParams.Contains(param.Name)) { if (param.Type == GPParameterType.MapServiceLayer) { asyncResultsExpected--; asyncResults.Add(null); if (asyncResultsExpected == 0) { fireAsyncCompleteEvent(); } } else { Geoprocessor gp = new Geoprocessor(ServiceEndpoint.AbsoluteUri); gp.Failed += gp_FailedAsync; gp.GetResultDataCompleted += gp2_GetResultDataCompleted; // Initialize proxy gp.ProxyURL = Configuration.UseProxy ? Configuration.ProxyUrl : null; gp.GetResultDataAsync(e.JobInfo.JobId, param.Name); } } } } }
// Get the users input line on the map and fire off a GP Job to clip features private async void StartButton_Click(object sender, RoutedEventArgs e) { try { uiPanel.IsEnabled = false; inputLayer.Graphics.Clear(); resultLayer.Graphics.Clear(); foreach (var lyr in mapView.Map.Layers.OfType <GPResultImageLayer>()) { mapView.Map.Layers.Remove(lyr); } //get the user's input line var inputLine = await mapView.Editor.RequestShapeAsync(DrawShape.Polyline) as Polyline; progress.Visibility = Visibility.Visible; inputLayer.Graphics.Add(new Graphic() { Geometry = inputLine }); var parameter = new GPInputParameter(); parameter.GPParameters.Add(new GPFeatureRecordSetLayer("Input_Features", inputLine)); parameter.GPParameters.Add(new GPLinearUnit("Linear_unit", LinearUnits.Miles, Int32.Parse(txtMiles.Text))); var result = await SubmitAndPollStatusAsync(parameter); if (result.JobStatus == GPJobStatus.Succeeded) { txtStatus.Text = "Finished processing. Retrieving results..."; var resultData = await _gpTask.GetResultDataAsync(result.JobID, "Clipped_Counties"); if (resultData is GPFeatureRecordSetLayer) { GPFeatureRecordSetLayer gpLayer = resultData as GPFeatureRecordSetLayer; if (gpLayer.FeatureSet.Features.Count == 0) { var resultImageLayer = await _gpTask.GetResultImageLayerAsync(result.JobID, "Clipped_Counties"); GPResultImageLayer gpImageLayer = resultImageLayer; gpImageLayer.Opacity = 0.5; mapView.Map.Layers.Add(gpImageLayer); txtStatus.Text = "Greater than 500 features returned. Results drawn using map service."; return; } resultLayer.Graphics.AddRange(gpLayer.FeatureSet.Features); } } } catch (Exception ex) { MessageBox.Show(ex.Message, "Sample Error"); } finally { uiPanel.IsEnabled = true; progress.Visibility = Visibility.Collapsed; } }
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(); }
private async void StartButton_Click(object sender, RoutedEventArgs e) { StartButton.IsEnabled = false; ClearResultsButton.Visibility = Visibility.Collapsed; //get the user's input point var inputPoint = await mapView1.Editor.RequestPointAsync(); //update UI elements MyProgressRing.Visibility = Windows.UI.Xaml.Visibility.Visible; MyProgressRing.IsActive = true; viewShedLayer.Graphics.Clear(); inputLayer.Graphics.Clear(); inputLayer.Graphics.Add(new Graphic() { Geometry = inputPoint }); Geoprocessor task = new Geoprocessor(new Uri("http://serverapps101.esri.com/arcgis/rest/services/ProbabilisticViewshedModel/GPServer/ProbabilisticViewshedModel")); var parameter = new GPInputParameter() { OutSpatialReference = new SpatialReference(102100) }; parameter.GPParameters.Add(new GPFeatureRecordSetLayer("Input_Features", inputPoint)); parameter.GPParameters.Add(new GPString("Height", HeightTextBox.Text)); parameter.GPParameters.Add(new GPLinearUnit("Distance", LinearUnits.Miles, Convert.ToDouble(MilesTextBox.Text))); var result = await task.SubmitJobAsync(parameter); //Poll the server for results every 2 seconds. while (result.JobStatus != GPJobStatus.Cancelled && result.JobStatus != GPJobStatus.Deleted && result.JobStatus != GPJobStatus.Succeeded && result.JobStatus != GPJobStatus.TimedOut) { result = await task.CheckJobStatusAsync(result.JobID); //show the status StatusTextBlock.Text = string.Join(Environment.NewLine, result.Messages.Select(x => x.Description)); await Task.Delay(2000); } if (result.JobStatus == GPJobStatus.Succeeded) { //get the results as a ArcGISDynamicMapServiceLayer StatusTextBlock.Text = "Finished processing. Retrieving results..."; var viewshedResult = await task.GetResultDataAsync(result.JobID, "View") as GPFeatureRecordSetLayer; var rangeResult = await task.GetResultDataAsync(result.JobID, "Range") as GPFeatureRecordSetLayer; if (viewshedResult != null && viewshedResult.FeatureSet != null && viewshedResult.FeatureSet.Features != null) { foreach (var feature in viewshedResult.FeatureSet.Features) { viewShedLayer.Graphics.Add((Graphic)feature); } } //Reset the UI StatusTextBlock.Visibility = Windows.UI.Xaml.Visibility.Collapsed; StartButton.IsEnabled = true; ClearResultsButton.Visibility = Visibility.Visible; MyProgressRing.Visibility = Windows.UI.Xaml.Visibility.Collapsed; MyProgressRing.IsActive = false; } }
private async void StartButton_Click(object sender, RoutedEventArgs e) { StartButton.IsEnabled = false; ClearResultsButton.Visibility = Visibility.Collapsed; //get the user's input point var inputPoint = await MyMapView.Editor.RequestPointAsync(); //update UI elements MyProgressRing.Visibility = Windows.UI.Xaml.Visibility.Visible; MyProgressRing.IsActive = true; viewshedLayer.Graphics.Clear(); inputLayer.Graphics.Clear(); inputLayer.Graphics.Add(new Graphic() { Geometry = inputPoint }); Geoprocessor task = new Geoprocessor(new Uri("http://serverapps101.esri.com/arcgis/rest/services/ProbabilisticViewshedModel/GPServer/ProbabilisticViewshedModel")); var parameter = new GPInputParameter() { OutSpatialReference = new SpatialReference(102100) }; parameter.GPParameters.Add(new GPFeatureRecordSetLayer("Input_Features", inputPoint)); parameter.GPParameters.Add(new GPString("Height", HeightTextBox.Text)); parameter.GPParameters.Add(new GPLinearUnit("Distance", LinearUnits.Miles, Convert.ToDouble(MilesTextBox.Text))); var result = await task.SubmitJobAsync(parameter); //Poll the server for results every 2 seconds. while (result.JobStatus != GPJobStatus.Cancelled && result.JobStatus != GPJobStatus.Deleted && result.JobStatus != GPJobStatus.Succeeded && result.JobStatus != GPJobStatus.TimedOut) { result = await task.CheckJobStatusAsync(result.JobID); //show the status StatusTextBlock.Text = string.Join(Environment.NewLine, result.Messages.Select(x => x.Description)); await Task.Delay(2000); } if (result.JobStatus == GPJobStatus.Succeeded) { //get the results as a ArcGISDynamicMapServiceLayer StatusTextBlock.Text = "Finished processing. Retrieving results..."; var viewshedResult = await task.GetResultDataAsync(result.JobID, "View") as GPFeatureRecordSetLayer; var rangeResult = await task.GetResultDataAsync(result.JobID, "Range") as GPFeatureRecordSetLayer; if (viewshedResult != null && viewshedResult.FeatureSet != null && viewshedResult.FeatureSet.Features != null) { foreach (var feature in viewshedResult.FeatureSet.Features) { viewshedLayer.Graphics.Add((Graphic)feature); } } //Reset the UI StatusTextBlock.Visibility = Windows.UI.Xaml.Visibility.Collapsed; StartButton.IsEnabled = true; ClearResultsButton.Visibility = Visibility.Visible; MyProgressRing.Visibility = Windows.UI.Xaml.Visibility.Collapsed; MyProgressRing.IsActive = false; } }
// Waits for the user to draw a line, then performs the buffer and clip operation private async void getInputLineAndClip() { if (m_firstPointAdded) { return; } // Get line from user var clipLine = await Editor.RequestShapeAsync(DrawShape.Polyline, new SimpleLineSymbol() { Color = Colors.Red, Width = 2, Style = SimpleLineStyle.Dash }); ClipLines.Add(new Graphic() { Geometry = clipLine }); // Show busy UI BusyVisibility = Visibility.Visible; StatusText = "Executing..."; string error = null; // Initialize the Geoprocessing task with the buffer and clip service endpoint Geoprocessor task = new Geoprocessor(new Uri("http://serverapps10.esri.com/ArcGIS/rest/services/SamplesNET/" + "USA_Data_ClipTools/GPServer/ClipCounties")); // Initialize input parameters var parameter = new GPInputParameter() { OutSpatialReference = SpatialReferences.WebMercator }; parameter.GPParameters.Add(new GPFeatureRecordSetLayer("Input_Features", clipLine)); // input geometry parameter.GPParameters.Add(new GPLinearUnit("Linear_unit", LinearUnits.Miles, BufferDistance)); // buffer distance try { // Submit the job and await the results var result = await task.SubmitJobAsync(parameter); // Poll the server every two seconds for the status of the job. while (result.JobStatus != GPJobStatus.Cancelled && result.JobStatus != GPJobStatus.Deleted && result.JobStatus != GPJobStatus.Failed && result.JobStatus != GPJobStatus.Succeeded && result.JobStatus != GPJobStatus.TimedOut) { result = await task.CheckJobStatusAsync(result.JobID); // show the status var descriptions = result.Messages.Select(msg => msg.Description); var status = string.Join(Environment.NewLine, descriptions); if (!string.IsNullOrEmpty(status)) { StatusText = status; } await Task.Delay(2000); } if (result.JobStatus == GPJobStatus.Succeeded) { // Get the results var resultData = await task.GetResultDataAsync(result.JobID, "Clipped_Counties"); if (resultData is GPFeatureRecordSetLayer) { GPFeatureRecordSetLayer resultsLayer = resultData as GPFeatureRecordSetLayer; if (resultsLayer.FeatureSet != null && resultsLayer.FeatureSet.Features != null && resultsLayer.FeatureSet.Features.Count != 0) { // Results were returned as graphics. Add them to the ClippedCounties collection ClippedCounties = new ObservableCollection <Graphic>(resultsLayer.FeatureSet.Features); } else // Try to get results as a GPResultImageLayer { StatusText = "Clip operation complete. Retrieving results..."; m_clippedCountiesLayer = await task.GetResultImageLayerAsync(result.JobID, "Clipped_Counties"); // If successful, add the layer to the layers collection if (m_clippedCountiesLayer != null) { m_clippedCountiesLayer.Opacity = 0.5; // Insert the layer below the input layer Layers.Insert(Layers.IndexOf(m_clipLinesLayer), m_clippedCountiesLayer); // Wait until the result layer is initialized await m_clippedCountiesLayer.InitializeAsync(); } else { error = "No results found"; } } } else { error = "Clip operation failed"; } } else { error = "Clip operation failed"; } } catch (Exception ex) { error = "Clip operation failed: " + ex.Message; } // If operation did not succeed, notify user if (error != null) { MessageBox.Show(error); } // Hide busy UI BusyVisibility = StatusVisibility = Visibility.Collapsed; StatusText = ""; m_firstPointAdded = false; getInputLineAndClip(); }
public async void Clip() { // get the local GP server's URL this.gpUrl = this.localGPService.UrlGeoprocessingService; // start the GP this.gpTask = new Geoprocessor(new Uri(this.gpUrl + "/ClipFeatures")); //get the user's input line var inputLine = await this.mapView.Editor.RequestShapeAsync(DrawShape.Polyline) as Polyline; // clear the graphics layers this.resultGraphicsLayer.Graphics.Clear(); this.inputGraphicsLayer.Graphics.Clear(); // add new graphic to layer this.inputGraphicsLayer.Graphics.Add(new Graphic { Geometry = inputLine, Symbol = this.simpleInputLineSymbol }); // add the parameters var parameter = new GPInputParameter(); parameter.GPParameters.Add(new GPFeatureRecordSetLayer("Input", inputLine)); parameter.GPParameters.Add(new GPLinearUnit("Linear_Unit", LinearUnits.Miles, this.Distance)); // poll the task var result = await SubmitAndPollStatusAsync(parameter); // add successful results to the map if (result.JobStatus == GPJobStatus.Succeeded) { this.Status = "Finished processing. Retrieving results..."; var resultData = await gpTask.GetResultDataAsync(result.JobID, "Clipped_Counties"); if (resultData is GPFeatureRecordSetLayer) { GPFeatureRecordSetLayer gpLayer = resultData as GPFeatureRecordSetLayer; if (gpLayer.FeatureSet.Features.Count == 0) { // the the map service results var resultImageLayer = await gpTask.GetResultImageLayerAsync(result.JobID, "Clipped_Counties"); // make the result image layer opaque GPResultImageLayer gpImageLayer = resultImageLayer; gpImageLayer.Opacity = 0.5; this.mapView.Map.Layers.Add(gpImageLayer); this.Status = "Greater than 500 features returned. Results drawn using map service."; return; } // get the result features and add them to the GraphicsLayer var features = gpLayer.FeatureSet.Features; foreach (Feature feature in features) { this.resultGraphicsLayer.Graphics.Add(feature as Graphic); } } this.Status = "Success!!!"; } }
void gp_JobCompleted(object sender, Client.Tasks.JobInfoEventArgs e) { if (e.JobInfo.JobStatus == esriJobStatus.esriJobFailed) { IsExecuting = false; ExecutingText = ESRI.ArcGIS.Mapping.GP.Resources.Strings.JobFailed; asyncErrors.AddRange(e.JobInfo.Messages.Where(p => p.MessageType == GPMessageType.Error).Select(p => new Exception(p.Description))); fireAsyncCompleteEvent(); } else { ExecutingText = ESRI.ArcGIS.Mapping.GP.Resources.Strings.GettingResults; asyncResultsExpected = Configuration.OutputParameters.Count; JobID = e.JobInfo.JobId; foreach (ParameterSupport.ParameterConfig param in Configuration.OutputParameters) { if (!resultRequestedParams.Contains(param.Name)) { if (param.Type == GPParameterType.MapServiceLayer) { asyncResultsExpected--; asyncResults.Add(null); if (asyncResultsExpected == 0) fireAsyncCompleteEvent(); } else { Geoprocessor gp = new Geoprocessor(ServiceEndpoint.AbsoluteUri); gp.Failed += gp_FailedAsync; gp.GetResultDataCompleted += gp2_GetResultDataCompleted; // Initialize proxy gp.ProxyURL = Configuration.UseProxy ? Configuration.ProxyUrl : null; gp.GetResultDataAsync(e.JobInfo.JobId, param.Name); } } } } }
} // 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)
void MyMap_MouseClick(object sender, Map.MouseEventArgs e) { /* * Add a graphic at the user input location */ MyMap.MouseClick -= MyMap_MouseClick; if (inputGraphicsLayer == null) { inputGraphicsLayer = new GraphicsLayer(); MyMap.Layers.Add(inputGraphicsLayer); } // Add a Graphic at the click point Graphic graphic = new Graphic() { Symbol = MainGrid.Resources["IncidentMarkerSymbol"] as Symbol, Geometry = e.MapPoint }; inputGraphicsLayer.Graphics.Add(graphic); /* * Reproject the mouseclick into the GP coordinate system */ // Declare the ProjectCompleted Handler EventHandler<GraphicsEventArgs> ProjectCompletedHandler = null; // Handle the event ProjectCompletedHandler = (sender2, graphicsEventArgs) => { // Unregister the handler geometryTask.ProjectCompleted -= ProjectCompletedHandler; // Cancel any existing Jobs geoprocessorTask.CancelAsync(); // Handle the JobCompleted geoprocessorTask.JobCompleted += (sender3, jobInfoEventArgs) => { // Check whether it succeeded if (jobInfoEventArgs.JobInfo.JobStatus != esriJobStatus.esriJobSucceeded) { //Do Something }; /* * Create two new Geoprocessor Tasks to fetch the result data (thereby allowing them to run concurrently) * Each will use the same event handler and we'll choose based on the Parameter Name. * Alternatively could use the overload which takes an object (userToken). */ Geoprocessor gpTaskSysvalves_Layer = new Geoprocessor(traceNetworkLocalGpService.Tasks[0].Url); gpTaskSysvalves_Layer.GetResultDataCompleted += geoprocessorTask_GetResultDataCompleted; gpTaskSysvalves_Layer.GetResultDataAsync( jobInfoEventArgs.JobInfo.JobId, "Sysvalves_Layer"); Geoprocessor gpTaskDistribMains_Layer = new Geoprocessor(traceNetworkLocalGpService.Tasks[0].Url); gpTaskDistribMains_Layer.GetResultDataCompleted += geoprocessorTask_GetResultDataCompleted; gpTaskDistribMains_Layer.GetResultDataAsync( jobInfoEventArgs.JobInfo.JobId, "DistribMains_Layer"); }; // Create the GP Parameter List List<GPParameter> parameters = new List<GPParameter>(); parameters.Add(new GPFeatureRecordSetLayer("Flags", graphicsEventArgs.Results[0].Geometry)); geoprocessorTask.SubmitJobAsync(parameters); }; // Register the handler for the ProjectCompleted event. geometryTask.ProjectCompleted += ProjectCompletedHandler; // Project the input point into the coordinate system of the data geometryTask.ProjectAsync(new List<Graphic>() { new Graphic() { Geometry = e.MapPoint } }, waterNetworkLocalMapService.SpatialReference); }
/// <summary> /// マップビュータップ時の処理 /// </summary> private async void mainMapView_MapViewTapped(object sender, Esri.ArcGISRuntime.Controls.MapViewInputEventArgs e) { //解析手順のメッセージを非表示 analyzeTextBox.Visibility = System.Windows.Visibility.Collapsed; //プログレスバーを表示 analyzeProgressBar.Visibility = System.Windows.Visibility.Visible; //マップビュータップ時のイベントハンドラを解除 mainMapView.MapViewTapped -= mainMapView_MapViewTapped; //カーソルを矢印に変更 mainMapView.Cursor = Cursors.Arrow; //クリックした位置からグラフィックを作成 Graphic clickPoint = new Graphic(e.Location) { Symbol = layoutRoot.Resources["greenMarkerSymbol"] as SimpleMarkerSymbol, ZIndex = 2 }; //到達圏解析結果表示用のグラフィックスレイヤにクリック位置のグラフィックを追加 serviceAreaResultLayer.Graphics.Add(clickPoint); try { //到達圏解析用パラメーターの作成 GPInputParameter parameter = new GPInputParameter(); parameter.GPParameters.Add(new GPFeatureRecordSetLayer("facilities", e.Location)); //解析の中心点 parameter.GPParameters.Add(new GPString("break_values", "10")); //到達圏の範囲(10分) parameter.GPParameters.Add(new GPString("env:outSR", "102100")); //結果の空間参照(Web メルカトル) parameter.GPParameters.Add(new GPString("travel_mode", "Walking")); //"徒歩"で到達できる範囲を解析 //到達圏の解析を開始 GPJobInfo result = await serviceAreaGp.SubmitJobAsync(parameter); //到達圏の解析結果が"成功"、"失敗"、"時間切れ"、"キャンセル"のいずれかになるまで //2秒ごとに ArcGIS Online にステータスを確認 while (result.JobStatus != GPJobStatus.Succeeded && result.JobStatus != GPJobStatus.Failed && result.JobStatus != GPJobStatus.TimedOut && result.JobStatus != GPJobStatus.Cancelled) { result = await serviceAreaGp.CheckJobStatusAsync(result.JobID); await Task.Delay(2000); } //到達圏解析の結果が成功した場合は結果を表示 if (result.JobStatus == GPJobStatus.Succeeded) { //到達圏解析の結果を取得 GPParameter resultData = await serviceAreaGp.GetResultDataAsync(result.JobID, "Service_Areas"); //到達圏解析結果レイヤのグラフィックを結果グラフィックとして取得 GPFeatureRecordSetLayer gpLayer = resultData as GPFeatureRecordSetLayer; serviceAreaGraphic = gpLayer.FeatureSet.Features[0] as Graphic; //グラフィックにシンボルを設定 serviceAreaGraphic.Symbol = layoutRoot.Resources["greenFillSymbol"] as SimpleFillSymbol; //結果グラフィックが解析の中心点のグラフィックより下に表示されるように表示順序を設定 serviceAreaGraphic.ZIndex = 1; //到達圏解析結果表示用のグラフィックスレイヤにグラフィックを追加 serviceAreaResultLayer.Graphics.Add(serviceAreaGraphic); } } //エラーが発生した場合の処理 catch (Exception ex) { MessageBox.Show(string.Format("到達圏解析:{0}", ex.Message)); //到達圏解析の結果をクリア ClearAnalysisResult(); } finally { //プログレスバーを非表示 analyzeProgressBar.Visibility = System.Windows.Visibility.Collapsed; //到達圏解析ボタンを表示 analyzePanel.Visibility = System.Windows.Visibility.Visible; } }
// Waits for the user to draw a line, then performs the buffer and clip operation private async void getInputLineAndClip() { if (m_firstPointAdded) return; // Get line from user var clipLine = await Editor.RequestShapeAsync(DrawShape.Polyline, new SimpleLineSymbol() { Color = Colors.Red, Width = 2, Style = SimpleLineStyle.Dash }); ClipLines.Add(new Graphic() { Geometry = clipLine }); // Show busy UI BusyVisibility = Visibility.Visible; StatusText = "Executing..."; string error = null; // Initialize the Geoprocessing task with the buffer and clip service endpoint Geoprocessor task = new Geoprocessor(new Uri("http://serverapps10.esri.com/ArcGIS/rest/services/SamplesNET/" + "USA_Data_ClipTools/GPServer/ClipCounties")); // Initialize input parameters var parameter = new GPInputParameter() { OutSpatialReference = SpatialReferences.WebMercator }; parameter.GPParameters.Add(new GPFeatureRecordSetLayer("Input_Features", clipLine)); // input geometry parameter.GPParameters.Add(new GPLinearUnit("Linear_unit", LinearUnits.Miles, BufferDistance)); // buffer distance try { // Submit the job and await the results var result = await task.SubmitJobAsync(parameter); // Poll the server every two seconds for the status of the job. while (result.JobStatus != GPJobStatus.Cancelled && result.JobStatus != GPJobStatus.Deleted && result.JobStatus != GPJobStatus.Failed && result.JobStatus != GPJobStatus.Succeeded && result.JobStatus != GPJobStatus.TimedOut) { result = await task.CheckJobStatusAsync(result.JobID); // show the status var descriptions = result.Messages.Select(msg => msg.Description); var status = string.Join(Environment.NewLine, descriptions); if (!string.IsNullOrEmpty(status)) StatusText = status; await Task.Delay(2000); } if (result.JobStatus == GPJobStatus.Succeeded) { // Get the results var resultData = await task.GetResultDataAsync(result.JobID, "Clipped_Counties"); if (resultData is GPFeatureRecordSetLayer) { GPFeatureRecordSetLayer resultsLayer = resultData as GPFeatureRecordSetLayer; if (resultsLayer.FeatureSet != null && resultsLayer.FeatureSet.Features != null && resultsLayer.FeatureSet.Features.Count != 0) { // Results were returned as graphics. Add them to the ClippedCounties collection ClippedCounties = new ObservableCollection<Graphic>(resultsLayer.FeatureSet.Features); } else // Try to get results as a GPResultImageLayer { StatusText = "Clip operation complete. Retrieving results..."; m_clippedCountiesLayer = await task.GetResultImageLayerAsync(result.JobID, "Clipped_Counties"); // If successful, add the layer to the layers collection if (m_clippedCountiesLayer != null) { m_clippedCountiesLayer.Opacity = 0.5; // Insert the layer below the input layer Layers.Insert(Layers.IndexOf(m_clipLinesLayer), m_clippedCountiesLayer); // Wait until the result layer is initialized await m_clippedCountiesLayer.InitializeAsync(); } else { error = "No results found"; } } } else { error = "Clip operation failed"; } } else { error = "Clip operation failed"; } } catch (Exception ex) { error = "Clip operation failed: " + ex.Message; } // If operation did not succeed, notify user if (error != null) MessageBox.Show(error); // Hide busy UI BusyVisibility = StatusVisibility = Visibility.Collapsed; StatusText = ""; m_firstPointAdded = false; getInputLineAndClip(); }
// *********************************************************************************** // * ..ERGChemcial GP Tool Job Completed Successfully... Get the Result // *********************************************************************************** void ergGPTask_GetResultDataCompleted(object sender, GPParameterEventArgs e) { try { if (e.Parameter.Name == "output_areas") { _ergZoneGraphicsLayer.Graphics.Clear(); ESRI.ArcGIS.Client.Geometry.Polygon sharedPolygon = null; //add the erg zone polygons on the map GPFeatureRecordSetLayer gpLayer = e.Parameter as GPFeatureRecordSetLayer; foreach (client.Graphic graphic in gpLayer.FeatureSet.Features) { string zone = graphic.Attributes["ERGZone"].ToString(); switch (zone) { case "Initial Isolation Zone": graphic.Symbol = _mydictionary["sfsZone2"] as client.Symbols.SimpleFillSymbol; break; case "Protective Action Zone": graphic.Symbol = _mydictionary["sfsZone1"] as client.Symbols.SimpleFillSymbol; break; case "Combined Zone": graphic.Symbol = _mydictionary["sfsZone3"] as client.Symbols.SimpleFillSymbol; sharedPolygon = (ESRI.ArcGIS.Client.Geometry.Polygon)graphic.Geometry; break; } _ergZoneGraphicsLayer.Graphics.Add(graphic); } //zoom to the result if (chkZoomToMap.IsChecked == true) { _mapWidget.Map.Extent = sharedPolygon.Extent.Expand(1.2); } selectFeaturesOnTheMap(sharedPolygon); Geoprocessor geoprocessorTask = sender as Geoprocessor; geoprocessorTask.GetResultDataAsync(_gpJobId, "output_lines"); } else { //add the erg zone polygons on the map GPFeatureRecordSetLayer gpLayer = e.Parameter as GPFeatureRecordSetLayer; foreach (client.Graphic graphic in gpLayer.FeatureSet.Features) { string lineType = graphic.Attributes["LineType"].ToString(); switch (lineType) { case "Arc": graphic.Symbol = _mydictionary["ArcLineSymbol"] as client.Symbols.SimpleLineSymbol; break; case "Radial": graphic.Symbol = _mydictionary["RadialSymbol"] as client.Symbols.SimpleLineSymbol; break; } _ergZoneGraphicsLayer.Graphics.Add(graphic); } } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); MessageBox.Show("Error processing ERG Task Results!", "Error"); return; } }
void MyMap_MouseClick(object sender, Map.MouseEventArgs e) { /* * Add a graphic at the user input location */ MyMap.MouseClick -= MyMap_MouseClick; if (inputGraphicsLayer == null) { inputGraphicsLayer = new GraphicsLayer(); MyMap.Layers.Add(inputGraphicsLayer); } // Add a Graphic at the click point Graphic graphic = new Graphic() { Symbol = MainGrid.Resources["IncidentMarkerSymbol"] as Symbol, Geometry = e.MapPoint }; inputGraphicsLayer.Graphics.Add(graphic); /* * Reproject the mouseclick into the GP coordinate system */ // Declare the ProjectCompleted Handler EventHandler <GraphicsEventArgs> ProjectCompletedHandler = null; // Handle the event ProjectCompletedHandler = (sender2, graphicsEventArgs) => { // Unregister the handler geometryTask.ProjectCompleted -= ProjectCompletedHandler; // Cancel any existing Jobs geoprocessorTask.CancelAsync(); // Handle the JobCompleted geoprocessorTask.JobCompleted += (sender3, jobInfoEventArgs) => { // Check whether it succeeded if (jobInfoEventArgs.JobInfo.JobStatus != esriJobStatus.esriJobSucceeded) { //Do Something } ; /* * Create two new Geoprocessor Tasks to fetch the result data (thereby allowing them to run concurrently) * Each will use the same event handler and we'll choose based on the Parameter Name. * Alternatively could use the overload which takes an object (userToken). */ Geoprocessor gpTaskSysvalves_Layer = new Geoprocessor(traceNetworkLocalGpService.Tasks[0].Url); gpTaskSysvalves_Layer.GetResultDataCompleted += geoprocessorTask_GetResultDataCompleted; gpTaskSysvalves_Layer.GetResultDataAsync( jobInfoEventArgs.JobInfo.JobId, "Sysvalves_Layer"); Geoprocessor gpTaskDistribMains_Layer = new Geoprocessor(traceNetworkLocalGpService.Tasks[0].Url); gpTaskDistribMains_Layer.GetResultDataCompleted += geoprocessorTask_GetResultDataCompleted; gpTaskDistribMains_Layer.GetResultDataAsync( jobInfoEventArgs.JobInfo.JobId, "DistribMains_Layer"); }; // Create the GP Parameter List List <GPParameter> parameters = new List <GPParameter>(); parameters.Add(new GPFeatureRecordSetLayer("Flags", graphicsEventArgs.Results[0].Geometry)); geoprocessorTask.SubmitJobAsync(parameters); }; // Register the handler for the ProjectCompleted event. geometryTask.ProjectCompleted += ProjectCompletedHandler; // Project the input point into the coordinate system of the data geometryTask.ProjectAsync(new List <Graphic>() { new Graphic() { Geometry = e.MapPoint } }, waterNetworkLocalMapService.SpatialReference); }
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(); } }