private void GenerateContours() { // Show the progress bar MyLoadingIndicator.Visibility = Visibility.Visible; MyLoadingIndicator.IsIndeterminate = false; // Create the geoprocessing parameters GeoprocessingParameters gpParams = new GeoprocessingParameters(GeoprocessingExecutionType.AsynchronousSubmit); // Add the interval parameter to the geoprocessing parameters gpParams.Inputs["ContourInterval"] = new GeoprocessingDouble(MyContourSlider.Value); // Create the job _gpJob = _gpTask.CreateJob(gpParams); // Update the UI when job progress changes _gpJob.ProgressChanged += (sender, args) => { Dispatcher.Invoke(() => { MyLoadingIndicator.Value = _gpJob.Progress; }); }; // Be notified when the task completes (or other change happens) _gpJob.JobChanged += GpJobOnJobChanged; // Start the job _gpJob.Start(); }
private async void btnGeoProcess_Click(object sender, RoutedEventArgs e) { //Get the local proprocessing package _gpService = new LocalGeoprocessingService(@"C:\Temp\tile_package_service.gpkx", GeoprocessingServiceType.AsynchronousSubmit); // Start the local service. try { await _gpService.StartAsync(); } catch (Exception exe) { MessageBox.Show(exe.Message); } // If the service is started, get the URL for the specific geoprocessing tool. string gpSvcUrl = _gpService.Url.AbsoluteUri + "/TP_Model"; // Create the geoprocessing task with the URL. _gpTask = await GeoprocessingTask.CreateAsync(new Uri(gpSvcUrl)); GeoprocessingParameters gpParams = new GeoprocessingParameters(GeoprocessingExecutionType.AsynchronousSubmit); //****************************************** //***This is the bit I think is wrong how do I pass a map obkect as a gpstring parameter?**** //********************************************* gpParams.Inputs["Input_Map"] = new GeoprocessingString(MyMapView.Name); _gpJob = _gpTask.CreateJob(gpParams); _gpJob.JobChanged += GeoprocessingJob_JobChanged; _gpJob.Start(); }
private async Task CalculateViewshed(MapPoint location) { // Create new geoprocessing task var viewshedTask = new GeoprocessingTask(new Uri(ViewshedUrl)); // Create input collection that contains the requested location var inputFeatures = new FeatureCollectionTable(new List <Field>(), GeometryType.Point, MyMapView.SpatialReference); Feature inputFeature = inputFeatures.CreateFeature(); inputFeature.Geometry = location; await inputFeatures.AddFeatureAsync(inputFeature); // Create parameters that are passed to the used geoprocessing task GeoprocessingParameters viewshedParameters = new GeoprocessingParameters(GeoprocessingExecutionType.SynchronousExecute); // Request output features in same SpatialReference as view. viewshedParameters.OutputSpatialReference = MyMapView.SpatialReference; // Add input location to geoprocessing parameters viewshedParameters.Inputs.Add("Input_Observation_Point", new GeoprocessingFeatures(inputFeatures)); // Create job that handles the communication between the application and the geoprocessing task var viewshedJob = viewshedTask.CreateJob(viewshedParameters); try { // Execute analysis and wait for the results GeoprocessingResult analysisResult = await viewshedJob.GetResultAsync(); // Get results from the outputs GeoprocessingFeatures viewshedResultFeatures = analysisResult.Outputs["Viewshed_Result"] as GeoprocessingFeatures; // Add all the results as a graphics to the map IFeatureSet viewshedAreas = viewshedResultFeatures.Features; foreach (var feature in viewshedAreas) { _resultOverlay.Graphics.Add(new Graphic(feature.Geometry)); } } catch (Exception ex) { if (viewshedJob.Status == JobStatus.Failed && viewshedJob.Error != null) { MessageBox.Show("Executing geoprocessing failed. " + viewshedJob.Error.Message, "Geoprocessing error"); } else { MessageBox.Show("An error occurred. " + ex.ToString(), "Sample error"); } } finally { SetBusy(false); } }
private async Task <IFeatureSet> GetGeodatabaseVersionsAsync() { // Start animating the activity indicator. _progressBar.StartAnimating(); // Results will be returned as a feature set. IFeatureSet results = null; // Create new geoprocessing task. GeoprocessingTask listVersionsTask = await GeoprocessingTask.CreateAsync(_listVersionsUrl); // Create default parameters that are passed to the geoprocessing task. GeoprocessingParameters listVersionsParameters = await listVersionsTask.CreateDefaultParametersAsync(); // Create job that handles the communication between the application and the geoprocessing task. GeoprocessingJob listVersionsJob = listVersionsTask.CreateJob(listVersionsParameters); try { // Execute analysis and wait for the results. GeoprocessingResult analysisResult = await listVersionsJob.GetResultAsync(); // Get results from the outputs. GeoprocessingFeatures listVersionsResults = (GeoprocessingFeatures)analysisResult.Outputs["Versions"]; // Set results. results = listVersionsResults.Features; } catch (Exception ex) { // Error handling if something goes wrong. if (listVersionsJob.Status == JobStatus.Failed && listVersionsJob.Error != null) { UIAlertController alert = new UIAlertController { Message = "Executing geoprocessing failed. " + listVersionsJob.Error.Message }; alert.ShowViewController(this, this); } else { UIAlertController alert = new UIAlertController { Message = "An error occurred. " + ex }; alert.ShowViewController(this, this); } } finally { // Stop the activity animation. _progressBar.StopAnimating(); } return(results); }
private async Task <IFeatureSet> GetGeodatabaseVersionsAsync() { // Results will be returned as a feature set IFeatureSet results = null; // Create new geoprocessing task var listVersionsTask = new GeoprocessingTask(new Uri(ListVersionsUrl)); // Create parameters that are passed to the used geoprocessing task GeoprocessingParameters listVersionsParameters = new GeoprocessingParameters(GeoprocessingExecutionType.SynchronousExecute); // Create job that handles the communication between the application and the geoprocessing task var listVersionsJob = listVersionsTask.CreateJob(listVersionsParameters); try { // Execute analysis and wait for the results GeoprocessingResult analysisResult = await listVersionsJob.GetResultAsync(); // Get results from the outputs GeoprocessingFeatures listVersionsResults = analysisResult.Outputs["Versions"] as GeoprocessingFeatures; // Set results results = listVersionsResults.Features; } catch (Exception ex) { // Error handling if something goes wrong if (listVersionsJob.Status == JobStatus.Failed && listVersionsJob.Error != null) { var alertBuilder = new AlertDialog.Builder(this); alertBuilder.SetTitle("Geoprocessing error"); alertBuilder.SetMessage("Executing geoprocessing failed. " + listVersionsJob.Error.Message); alertBuilder.Show(); } else { var alertBuilder = new AlertDialog.Builder(this); alertBuilder.SetTitle("Sample error"); alertBuilder.SetMessage("An error occurred. " + ex.ToString()); alertBuilder.Show(); } } finally { // Set the UI to indicate that the geoprocessing is not running SetBusy(false); } return(results); }
private async void something() { localServiceGP = new LocalGeoprocessingService(gpServiceUrl); localServiceGP.ServiceType = GeoprocessingServiceType.SynchronousExecute; localServiceGP.StatusChanged += async(svc, args) => { if (args.Status == LocalServerStatus.Started) { // 获取工具的本地地址 var gpSvcUrl = (svc as LocalGeoprocessingService).Url.AbsoluteUri + "/flowCount1"; // 在浏览器打开 toolUrl = gpSvcUrl; GeoprocessingTask gpRouteTask = new GeoprocessingTask(new Uri(gpSvcUrl)); GeoprocessingParameters para = new GeoprocessingParameters(GeoprocessingExecutionType.SynchronousExecute); para.Inputs.Add("i", new GeoprocessingRaster(new Uri(rasterPath), "GPRasterDataLayer")); if (rasterWeightPath != "") { para.Inputs.Add("w", new GeoprocessingRaster(new Uri(rasterWeightPath), "GPRasterDataLayer")); } para.Inputs.Add("dataType", new GeoprocessingString(dataType)); para.Inputs.Add("o", new GeoprocessingString(rasterResultPath)); GeoprocessingJob routeJob = gpRouteTask.CreateJob(para); try { t1.Text = "处理中..."; GeoprocessingResult geoprocessingResult = await routeJob.GetResultAsync(); t1.Text = "流量处理完成."; myUserControl.IsEnabled = true; } catch (Exception ex) { if (routeJob.Status == JobStatus.Failed && routeJob.Error != null) { MessageBox.Show("GP流处理错误:\n" + routeJob.Error.Message, "Geoprocessing error"); } else { MessageBox.Show("非GP流错误:\n" + ex.ToString() + "/**/", "Sample error"); } } } }; await localServiceGP.StartAsync(); }
private async Task <IFeatureSet> GetGeodatabaseVersionsAsync() { // Results will be returned as a feature set IFeatureSet results = null; // Create new geoprocessing task GeoprocessingTask listVersionsTask = await GeoprocessingTask.CreateAsync(new Uri(ListVersionsUrl)); // Create default parameters that are passed to the geoprocessing task GeoprocessingParameters listVersionsParameters = await listVersionsTask.CreateDefaultParametersAsync(); // Create job that handles the communication between the application and the geoprocessing task GeoprocessingJob listVersionsJob = listVersionsTask.CreateJob(listVersionsParameters); try { // Execute analysis and wait for the results GeoprocessingResult analysisResult = await listVersionsJob.GetResultAsync(); // Get results from the outputs GeoprocessingFeatures listVersionsResults = (GeoprocessingFeatures)analysisResult.Outputs["Versions"]; // Set results results = listVersionsResults.Features; } catch (Exception ex) { // Error handling if something goes wrong if (listVersionsJob.Status == JobStatus.Failed && listVersionsJob.Error != null) { MessageDialog message = new MessageDialog("Executing geoprocessing failed. " + listVersionsJob.Error.Message, "Geoprocessing error"); await message.ShowAsync(); } else { MessageDialog message = new MessageDialog("An error occurred. " + ex.ToString(), "Sample error"); await message.ShowAsync(); } } finally { // Set the UI to indicate that the geoprocessing is not running SetBusy(false); } return(results); }
private async Task CalculateViewshed(MapPoint location) { // This function will define a new geoprocessing task that performs a custom viewshed analysis based upon a // user click on the map and then display the results back as a polygon fill graphics overlay. If there // is a problem with the execution of the geoprocessing task an error message will be displayed // Create new geoprocessing task using the url defined in the member variables section GeoprocessingTask myViewshedTask = await GeoprocessingTask.CreateAsync(new Uri(_viewshedUrl)); // Create a new feature collection table based upon point geometries using the current map view spatial reference FeatureCollectionTable myInputFeatures = new FeatureCollectionTable(new List <Field>(), GeometryType.Point, MyMapView.SpatialReference); // Create a new feature from the feature collection table. It will not have a coordinate location (x,y) yet Feature myInputFeature = myInputFeatures.CreateFeature(); // Assign a physical location to the new point feature based upon where the user clicked in the map view myInputFeature.Geometry = location; // Add the new feature with (x,y) location to the feature collection table await myInputFeatures.AddFeatureAsync(myInputFeature); // Create the parameters that are passed to the used geoprocessing task GeoprocessingParameters myViewshedParameters = new GeoprocessingParameters(GeoprocessingExecutionType.SynchronousExecute) { // Request the output features to use the same SpatialReference as the map view OutputSpatialReference = MyMapView.SpatialReference }; // Add an input location to the geoprocessing parameters myViewshedParameters.Inputs.Add("Input_Observation_Point", new GeoprocessingFeatures(myInputFeatures)); // Create the job that handles the communication between the application and the geoprocessing task GeoprocessingJob myViewshedJob = myViewshedTask.CreateJob(myViewshedParameters); try { // Execute analysis and wait for the results GeoprocessingResult myAnalysisResult = await myViewshedJob.GetResultAsync(); // Get the results from the outputs GeoprocessingFeatures myViewshedResultFeatures = (GeoprocessingFeatures)myAnalysisResult.Outputs["Viewshed_Result"]; // Add all the results as a graphics to the map IFeatureSet myViewshedAreas = myViewshedResultFeatures.Features; foreach (Feature myFeature in myViewshedAreas) { _resultOverlay.Graphics.Add(new Graphic(myFeature.Geometry)); } } catch (Exception ex) { // Display an error message if there is a problem if (myViewshedJob.Status == JobStatus.Failed && myViewshedJob.Error != null) { MessageBox.Show("Executing geoprocessing failed. " + myViewshedJob.Error.Message, "Geoprocessing error"); } else { MessageBox.Show("An error occurred. " + ex.ToString(), "Sample error"); } } finally { // Indicate that the geoprocessing is not running SetBusy(false); } }
private async void OnRunAnalysisClicked(object sender, EventArgs e) { // Show the animating progress bar _myProgressBar.StartAnimating(); // Get the 'from' and 'to' dates from the date pickers for the geoprocessing analysis DateTime myFromDate; DateTime myToDate; try { myFromDate = Convert.ToDateTime(_startDateTextField.Text); myToDate = Convert.ToDateTime(_endDateTextField.Text); } catch (Exception) { // Handle badly formatted dates UIAlertController alert = UIAlertController.Create("Invalid date", "Please enter a valid date", UIAlertControllerStyle.Alert); alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); PresentViewController(alert, true, null); // Stop the progress bar from animating (which also hides it as well) _myProgressBar.StopAnimating(); return; } // The end date must be at least one day after the start date if (myToDate <= myFromDate.AddDays(1)) { // Show error message UIAlertController alert = UIAlertController.Create("Invalid date range", "Please enter a valid date range. There has to be at least one day in between To and From dates.", UIAlertControllerStyle.Alert); alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); PresentViewController(alert, true, null); // Stop the progress bar from animating (which also hides it as well) _myProgressBar.StopAnimating(); return; } // Create the parameters that are passed to the used geoprocessing task GeoprocessingParameters myHotspotParameters = new GeoprocessingParameters(GeoprocessingExecutionType.AsynchronousSubmit); // Construct the date query var myQueryString = string.Format("(\"DATE\" > date '{0} 00:00:00' AND \"DATE\" < date '{1} 00:00:00')", myFromDate.ToString("yyyy-MM-dd"), myToDate.ToString("yyyy-MM-dd")); // Add the query that contains the date range used in the analysis myHotspotParameters.Inputs.Add("Query", new GeoprocessingString(myQueryString)); // Create job that handles the communication between the application and the geoprocessing task _hotspotJob = _hotspotTask.CreateJob(myHotspotParameters); try { // Execute the geoprocessing analysis and wait for the results GeoprocessingResult myAnalysisResult = await _hotspotJob.GetResultAsync(); // Add results to a map using map server from a geoprocessing task // Load to get access to full extent await myAnalysisResult.MapImageLayer.LoadAsync(); // Add the analysis layer to the map view _myMapView.Map.OperationalLayers.Add(myAnalysisResult.MapImageLayer); // Zoom to the results await _myMapView.SetViewpointAsync(new Viewpoint(myAnalysisResult.MapImageLayer.FullExtent)); } catch (TaskCanceledException) { // This is thrown if the task is canceled. Ignore. } catch (Exception ex) { // Display error messages if the geoprocessing task fails if (_hotspotJob.Status == JobStatus.Failed && _hotspotJob.Error != null) { // Report error UIAlertController alert = UIAlertController.Create("Geoprocessing Error", _hotspotJob.Error.Message, UIAlertControllerStyle.Alert); alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); PresentViewController(alert, true, null); } else { // Report error UIAlertController alert = UIAlertController.Create("Sample error", ex.ToString(), UIAlertControllerStyle.Alert); alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); PresentViewController(alert, true, null); } } finally { // Stop the progress bar from animating (which also hides it as well) _myProgressBar.StopAnimating(); } }
private async Task CalculateViewshed(MapPoint location) { // This function will define a new geoprocessing task that performs a custom viewshed analysis based upon a // user click on the map and then display the results back as a polygon fill graphics overlay. If there // is a problem with the execution of the geoprocessing task an error message will be displayed. // Create new geoprocessing task using the URL defined in the member variables section. GeoprocessingTask viewshedTask = await GeoprocessingTask.CreateAsync(new Uri(ViewshedServiceUrl)); // Create a new feature collection table based upon point geometries using the current map view spatial reference. FeatureCollectionTable inputFeatures = new FeatureCollectionTable(new List <Field>(), GeometryType.Point, _myMapView.SpatialReference); // Create a new feature from the feature collection table. It will not have a coordinate location (x,y) yet. Feature inputFeature = inputFeatures.CreateFeature(); // Assign a physical location to the new point feature based upon where the user clicked in the map view. inputFeature.Geometry = location; // Add the new feature with (x,y) location to the feature collection table. await inputFeatures.AddFeatureAsync(inputFeature); // Create the parameters that are passed to the used geoprocessing task. GeoprocessingParameters viewshedParameters = new GeoprocessingParameters(GeoprocessingExecutionType.SynchronousExecute) { OutputSpatialReference = _myMapView.SpatialReference }; // Add an input location to the geoprocessing parameters. viewshedParameters.Inputs.Add("Input_Observation_Point", new GeoprocessingFeatures(inputFeatures)); // Create the job that handles the communication between the application and the geoprocessing task. GeoprocessingJob viewshedJob = viewshedTask.CreateJob(viewshedParameters); try { // Execute analysis and wait for the results. GeoprocessingResult analysisResult = await viewshedJob.GetResultAsync(); // Get the results from the outputs. GeoprocessingFeatures viewshedResultFeatures = (GeoprocessingFeatures)analysisResult.Outputs["Viewshed_Result"]; // Add all the results as a graphics to the map. foreach (Feature feature in viewshedResultFeatures.Features) { _resultOverlay.Graphics.Add(new Graphic(feature.Geometry)); } } catch (Exception ex) { // Display an error message if there is a problem. if (viewshedJob.Status == JobStatus.Failed && viewshedJob.Error != null) { // Report error UIAlertController alert = UIAlertController.Create("Geoprocessing Error", viewshedJob.Error.Message, UIAlertControllerStyle.Alert); alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); PresentViewController(alert, true, null); } else { // Report error UIAlertController alert = UIAlertController.Create("Sample Error", ex.ToString(), UIAlertControllerStyle.Alert); alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); PresentViewController(alert, true, null); } } }
private async void OnRunAnalysisClicked(object sender, EventArgs e) { // Get the 'from' and 'to' dates from the date edit text's for the geoprocessing analysis. DateTime myFromDate; DateTime myToDate; try { myFromDate = Convert.ToDateTime(_startDateButton.Text); myToDate = Convert.ToDateTime(_endDateButton.Text); } catch (Exception exception) { // Show error message and quit. new AlertDialog.Builder(this).SetMessage(exception.Message).Show(); return; } // Clear any existing results. _myMapView.Map.OperationalLayers.Clear(); // Show busy activity indication. _alert.Show(); // The end date must be at least one day after the start date. if (myToDate <= myFromDate.AddDays(1)) { _alert.Cancel(); // Show error message. AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this); alertBuilder.SetTitle("Invalid date range"); alertBuilder.SetMessage("Please select valid time range.There has to be at least one day in between To and From dates."); alertBuilder.Show(); return; } // Create the parameters that are passed to the used geoprocessing task. GeoprocessingParameters myHotspotParameters = new GeoprocessingParameters(GeoprocessingExecutionType.AsynchronousSubmit); // Construct the date query. string myQueryString = $"(\"DATE\" > date '{myFromDate:yyyy-MM-dd} 00:00:00' AND \"DATE\" < date '{myToDate:yyyy-MM-dd} 00:00:00')"; // Add the query that contains the date range used in the analysis. myHotspotParameters.Inputs.Add("Query", new GeoprocessingString(myQueryString)); // Create job that handles the communication between the application and the geoprocessing task. _hotspotJob = _hotspotTask.CreateJob(myHotspotParameters); try { // Execute the geoprocessing analysis and wait for the results. GeoprocessingResult myAnalysisResult = await _hotspotJob.GetResultAsync(); // Add results to a map using map server from a geoprocessing task. // Load to get access to full extent. await myAnalysisResult.MapImageLayer.LoadAsync(); // Add the analysis layer to the map view. _myMapView.Map.OperationalLayers.Add(myAnalysisResult.MapImageLayer); // Zoom to the results. await _myMapView.SetViewpointAsync(new Viewpoint(myAnalysisResult.MapImageLayer.FullExtent)); // Remove the loading alert dialog. _alert.Cancel(); } catch (TaskCanceledException) { // This is thrown if the task is canceled. Ignore. } catch (Exception ex) { // Remove the loading alert dialog. _alert.Cancel(); // Display error messages if the geoprocessing task fails. if (_hotspotJob.Status == JobStatus.Failed && _hotspotJob.Error != null) { AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this); alertBuilder.SetTitle("Geoprocessing error"); alertBuilder.SetMessage("Executing geoprocessing failed. " + _hotspotJob.Error.Message); alertBuilder.Show(); } else { AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this); alertBuilder.SetTitle("Sample error"); alertBuilder.SetMessage("An error occurred. " + ex.ToString()); alertBuilder.Show(); } } }
private async void OnRunAnalysisClicked(object sender, EventArgs e) { // Clear any existing results. _myMapView.Map.OperationalLayers.Clear(); // Show the animating progress bar . _progressBar.StartAnimating(); // Get the 'from' and 'to' dates from the date pickers for the geoprocessing analysis. DateTime fromDate = (DateTime)_selectionView.StartPicker.Date; DateTime toDate = (DateTime)_selectionView.EndPicker.Date; // The end date must be at least one day after the start date. if (toDate <= fromDate.AddDays(1)) { // Show error message. UIAlertController alert = UIAlertController.Create("Invalid date range", "Please enter a valid date range. There has to be at least one day in between To and From dates.", UIAlertControllerStyle.Alert); alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); PresentViewController(alert, true, null); // Stop the progress bar from animating (which also hides it as well). _progressBar.StopAnimating(); return; } // Create the parameters that are passed to the used geoprocessing task. GeoprocessingParameters hotspotParameters = new GeoprocessingParameters(GeoprocessingExecutionType.AsynchronousSubmit); // Construct the date query. string myQueryString = $"(\"DATE\" > date '{fromDate:yyyy-MM-dd 00:00:00}' AND \"DATE\" < date '{toDate:yyy-MM-dd 00:00:00}')"; // Add the query that contains the date range used in the analysis. hotspotParameters.Inputs.Add("Query", new GeoprocessingString(myQueryString)); // Create job that handles the communication between the application and the geoprocessing task. _hotspotJob = _hotspotTask.CreateJob(hotspotParameters); try { // Execute the geoprocessing analysis and wait for the results. GeoprocessingResult analysisResult = await _hotspotJob.GetResultAsync(); // Add results to a map using map server from a geoprocessing task. // Load to get access to full extent. await analysisResult.MapImageLayer.LoadAsync(); // Add the analysis layer to the map view. _myMapView.Map.OperationalLayers.Add(analysisResult.MapImageLayer); // Zoom to the results. await _myMapView.SetViewpointAsync(new Viewpoint(analysisResult.MapImageLayer.FullExtent)); } catch (TaskCanceledException) { // This is thrown if the task is canceled. Ignore. } catch (Exception ex) { // Display error messages if the geoprocessing task fails. if (_hotspotJob.Status == JobStatus.Failed && _hotspotJob.Error != null) { // Report error. UIAlertController alert = UIAlertController.Create("Geoprocessing Error", _hotspotJob.Error.Message, UIAlertControllerStyle.Alert); alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); PresentViewController(alert, true, null); } else { // Report error. UIAlertController alert = UIAlertController.Create("Sample error", ex.ToString(), UIAlertControllerStyle.Alert); alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); PresentViewController(alert, true, null); } } finally { // Stop the progress bar from animating (which also hides it). _progressBar.StopAnimating(); } }
private async void ExecuteGPService() { //加载DEM并且缩放到该区域 Map map = new Map(Basemap.CreateTopographic()); string pathToRaster = @"D:\work\github\ExecuteGPK\LasVegasNED13_geoid1.tif"; var myRaster = new Raster(pathToRaster); // create a RasterLayer using the Raster var newRasterLayer = new RasterLayer(myRaster); map.OperationalLayers.Add(newRasterLayer); Viewpoint viewPoint = new Viewpoint(36.131, -115.144, 800000); myMapView.Map = map; await myMapView.SetViewpointAsync(viewPoint, TimeSpan.FromSeconds(2)); StartLocalServer(); LocalGeoprocessingService localServiceGP = new LocalGeoprocessingService(@"D:\work\github\ExecuteGPK\InterpolateShape.gpk"); localServiceGP.ServiceType = GeoprocessingServiceType.SynchronousExecute; // Handle the status changed event to check when it's loaded localServiceGP.StatusChanged += async(svc, args) => { // If service started successfully, create a gp task if (args.Status == LocalServerStatus.Started) { // Get the URL for the specific geoprocessing tool var gpSvcUrl = (svc as LocalGeoprocessingService).Url.AbsoluteUri + "/InterpolateShape"; // Create the geoprocessing task GeoprocessingTask gpRouteTask = new GeoprocessingTask(new Uri(gpSvcUrl)); GeoprocessingParameters para = new GeoprocessingParameters(GeoprocessingExecutionType.SynchronousExecute); // Create the schema for a lines table (one text field to contain a name attribute) var inputFeatures = new FeatureCollectionTable(new List <Field>(), GeometryType.Polyline, myMapView.SpatialReference); Feature inputFeature = inputFeatures.CreateFeature(); var geometry = await myMapView.SketchEditor.StartAsync(SketchCreationMode.Polyline, false); inputFeature.Geometry = geometry; await inputFeatures.AddFeatureAsync(inputFeature); para.Inputs.Add("inputLine", new GeoprocessingFeatures(inputFeatures)); para.ReturnZ = true; para.OutputSpatialReference = myMapView.SpatialReference; GeoprocessingJob routeJob = gpRouteTask.CreateJob(para); try { // Execute analysis and wait for the results GeoprocessingResult geoprocessingResult = await routeJob.GetResultAsync(); GeoprocessingFeatures resultFeatures = geoprocessingResult.Outputs["outputLine"] as GeoprocessingFeatures; IFeatureSet interpolateShapeResult = resultFeatures.Features; Esri.ArcGISRuntime.Geometry.Polyline elevationLine = interpolateShapeResult.First().Geometry as Esri.ArcGISRuntime.Geometry.Polyline; MapPoint startPoint = elevationLine.Parts[0].Points[0]; int count = elevationLine.Parts[0].PointCount; MapPoint stopPoint = elevationLine.Parts[0].Points[count - 1]; double chazhi = stopPoint.Z - startPoint.Z; MessageBox.Show("终点的Z值为: " + stopPoint.Z.ToString() + ",起点的Z值为: " + startPoint.Z.ToString()); } catch (Exception ex) { if (routeJob.Status == JobStatus.Failed && routeJob.Error != null) { MessageBox.Show("Executing geoprocessing failed. " + routeJob.Error.Message, "Geoprocessing error"); } else { MessageBox.Show("An error occurred. " + ex.ToString(), "Sample error"); } } // Create parameters, run the task, process results, etc. // ... } }; // Start the local geoprocessing service await localServiceGP.StartAsync(); }
private async void OnAnalyzeHotspotsClicked(object sender, RoutedEventArgs e) { // Show busy indication ShowBusyOverlay(); var fromDate = FromDate.SelectedDate.Value; var toDate = ToDate.SelectedDate.Value; if (toDate <= fromDate.AddDays(1)) { // Show error message MessageBox.Show( "Please select valid time range. There has to be at least one day in between To and From dates.", "Invalid date range"); // Remove overlay ShowBusyOverlay(false); return; } // Create parameters that are passed to the used geoprocessing task GeoprocessingParameters hotspotParameters = new GeoprocessingParameters(GeoprocessingExecutionType.AsynchronousSubmit); // Construct used query var queryString = string.Format("(\"DATE\" > date '{0} 00:00:00' AND \"DATE\" < date '{1} 00:00:00')", fromDate.ToString("yyyy-MM-dd"), toDate.ToString("yyyy-MM-dd")); // Add query that contains the date range and the days of the week that are used in analysis hotspotParameters.Inputs.Add("Query", new GeoprocessingString(queryString)); // Create job that handles the communication between the application and the geoprocessing task _hotspotJob = _hotspotTask.CreateJob(hotspotParameters); try { // Execute analysis and wait for the results GeoprocessingResult analysisResult = await _hotspotJob.GetResultAsync(); // Add results to a map using map server from a geoprocessing task // Load to get access to full extent await analysisResult.MapImageLayer.LoadAsync(); // Add layers to the map view MyMapView.Map.OperationalLayers.Add(analysisResult.MapImageLayer); // Zoom to the results await MyMapView.SetViewpointAsync( new Viewpoint(analysisResult.MapImageLayer.FullExtent)); } catch (TaskCanceledException) { // This is thrown if the task is canceled. Ignore. } catch (Exception ex) { if (_hotspotJob.Status == JobStatus.Failed && _hotspotJob.Error != null) { MessageBox.Show("Executing geoprocessing failed. " + _hotspotJob.Error.Message, "Geoprocessing error"); } else { MessageBox.Show("An error occurred. " + ex.ToString(), "Sample error"); } } finally { // Remove overlay ShowBusyOverlay(false); } }
private async Task<IFeatureSet> GetGeodatabaseVersionsAsync() { // Results will be returned as a feature set IFeatureSet results = null; // Create new geoprocessing task var listVersionsTask = new GeoprocessingTask(new Uri(ListVersionsUrl)); // Create parameters that are passed to the used geoprocessing task GeoprocessingParameters listVersionsParameters = new GeoprocessingParameters(GeoprocessingExecutionType.SynchronousExecute); // Create job that handles the communication between the application and the geoprocessing task var listVersionsJob = listVersionsTask.CreateJob(listVersionsParameters); try { // Execute analysis and wait for the results GeoprocessingResult analysisResult = await listVersionsJob.GetResultAsync(); // Get results from the outputs GeoprocessingFeatures listVersionsResults = analysisResult.Outputs["Versions"] as GeoprocessingFeatures; // Set results results = listVersionsResults.Features; } catch (Exception ex) { // Error handling if something goes wrong if (listVersionsJob.Status == JobStatus.Failed && listVersionsJob.Error != null) MessageBox.Show("Executing geoprocessing failed. " + listVersionsJob.Error.Message, "Geoprocessing error"); else MessageBox.Show("An error occurred. " + ex.ToString(), "Sample error"); } finally { // Set the UI to indicate that the geoprocessing is not running SetBusy(false); } return results; }
private async Task CalculateViewshed(MapPoint location) { // This function will define a new geoprocessing task that performs a custom viewshed analysis based upon a // user click on the map and then display the results back as a polygon fill graphics overlay. If there // is a problem with the execution of the geoprocessing task an error message will be displayed // Create new geoprocessing task using the url defined in the member variables section var myViewshedTask = new GeoprocessingTask(new Uri(_viewshedUrl)); // Create a new feature collection table based upon point geometries using the current map view spatial reference var myInputFeatures = new FeatureCollectionTable(new List<Field>(), GeometryType.Point, MyMapView.SpatialReference); // Create a new feature from the feature collection table. It will not have a coordinate location (x,y) yet Feature myInputFeature = myInputFeatures.CreateFeature(); // Assign a physical location to the new point feature based upon where the user clicked in the map view myInputFeature.Geometry = location; // Add the new feature with (x,y) location to the feature collection table await myInputFeatures.AddFeatureAsync(myInputFeature); // Create the parameters that are passed to the used geoprocessing task GeoprocessingParameters myViewshedParameters = new GeoprocessingParameters(GeoprocessingExecutionType.SynchronousExecute); // Request the output features to use the same SpatialReference as the map view myViewshedParameters.OutputSpatialReference = MyMapView.SpatialReference; // Add an input location to the geoprocessing parameters myViewshedParameters.Inputs.Add("Input_Observation_Point", new GeoprocessingFeatures(myInputFeatures)); // Create the job that handles the communication between the application and the geoprocessing task var myViewshedJob = myViewshedTask.CreateJob(myViewshedParameters); try { // Execute analysis and wait for the results GeoprocessingResult myAnalysisResult = await myViewshedJob.GetResultAsync(); // Get the results from the outputs GeoprocessingFeatures myViewshedResultFeatures = myAnalysisResult.Outputs["Viewshed_Result"] as GeoprocessingFeatures; // Add all the results as a graphics to the map IFeatureSet myViewshedAreas = myViewshedResultFeatures.Features; foreach (var myFeature in myViewshedAreas) { _resultOverlay.Graphics.Add(new Graphic(myFeature.Geometry)); } } catch (Exception ex) { // Display an error message if there is a problem if (myViewshedJob.Status == JobStatus.Failed && myViewshedJob.Error != null) { var message = new MessageDialog("Executing geoprocessing failed. " + myViewshedJob.Error.Message, "Geoprocessing error"); await message.ShowAsync(); } else { var message = new MessageDialog("An error occurred. " + ex.ToString(), "Sample error"); await message.ShowAsync(); } } finally { // Indicate that the geoprocessing is not running SetBusy(false); } }
private async void OnRunAnalysisClicked(object sender, EventArgs e) { // Show busy activity indication MyActivityInidicator.IsVisible = true; MyActivityInidicator.IsRunning = true; // Get the 'from' and 'to' dates from the date pickers for the geoprocessing analysis DateTime myFromDate; DateTime myToDate; try { myFromDate = Convert.ToDateTime(StartDate.Text); myToDate = Convert.ToDateTime(EndDate.Text); } catch (Exception) { // Handle badly formatted dates await DisplayAlert("Invalid date", "Please enter a valid date", "OK"); // Remove the busy activity indication MyActivityInidicator.IsRunning = false; MyActivityInidicator.IsVisible = false; return; } // The end date must be at least one day after the start date if (myToDate <= myFromDate.AddDays(1)) { // Show error message await DisplayAlert("Invalid date range", "Please select valid time range. There has to be at least one day in between To and From dates.", "OK"); // Remove the busy activity indication MyActivityInidicator.IsRunning = false; MyActivityInidicator.IsVisible = false; return; } // Create the parameters that are passed to the used geoprocessing task GeoprocessingParameters myHotspotParameters = new GeoprocessingParameters(GeoprocessingExecutionType.AsynchronousSubmit); // Construct the date query var myQueryString = string.Format("(\"DATE\" > date '{0} 00:00:00' AND \"DATE\" < date '{1} 00:00:00')", myFromDate.ToString("yyyy-MM-dd"), myToDate.ToString("yyyy-MM-dd")); // Add the query that contains the date range used in the analysis myHotspotParameters.Inputs.Add("Query", new GeoprocessingString(myQueryString)); // Create job that handles the communication between the application and the geoprocessing task _hotspotJob = _hotspotTask.CreateJob(myHotspotParameters); try { // Execute the geoprocessing analysis and wait for the results GeoprocessingResult myAnalysisResult = await _hotspotJob.GetResultAsync(); // Add results to a map using map server from a geoprocessing task // Load to get access to full extent await myAnalysisResult.MapImageLayer.LoadAsync(); // Add the analysis layer to the map view MyMapView.Map.OperationalLayers.Add(myAnalysisResult.MapImageLayer); // Zoom to the results await MyMapView.SetViewpointAsync(new Viewpoint(myAnalysisResult.MapImageLayer.FullExtent)); } catch (TaskCanceledException) { // This is thrown if the task is canceled. Ignore. } catch (Exception ex) { // Display error messages if the geoprocessing task fails if (_hotspotJob.Status == JobStatus.Failed && _hotspotJob.Error != null) { await DisplayAlert("Geoprocessing error", "Executing geoprocessing failed. " + _hotspotJob.Error.Message, "OK"); } else { await DisplayAlert("Sample error", "An error occurred. " + ex.ToString(), "OK"); } } finally { // Remove the busy activity indication MyActivityInidicator.IsRunning = false; MyActivityInidicator.IsVisible = false; } }
private async void OnAnalyzeHotspotsClicked(object sender, RoutedEventArgs e) { // Clear any existing results MyMapView.Map.OperationalLayers.Clear(); // Show the waiting indication ShowBusyOverlay(); // Get the 'from' and 'to' dates from the date pickers for the geoprocessing analysis DateTime myFromDate = FromDate.SelectedDate.Value; DateTime myToDate = ToDate.SelectedDate.Value; // The end date must be at least one day after the start date if (myToDate <= myFromDate.AddDays(1)) { // Show error message MessageBox.Show( "Please select valid time range. There has to be at least one day in between To and From dates.", "Invalid date range"); // Remove the waiting ShowBusyOverlay(false); return; } // Create the parameters that are passed to the used geoprocessing task GeoprocessingParameters myHotspotParameters = new GeoprocessingParameters(GeoprocessingExecutionType.AsynchronousSubmit); // Construct the date query string myQueryString = string.Format("(\"DATE\" > date '{0:yyyy-MM-dd} 00:00:00' AND \"DATE\" < date '{1:yyyy-MM-dd} 00:00:00')", myFromDate, myToDate); // Add the query that contains the date range used in the analysis myHotspotParameters.Inputs.Add("Query", new GeoprocessingString(myQueryString)); // Create job that handles the communication between the application and the geoprocessing task _hotspotJob = _hotspotTask.CreateJob(myHotspotParameters); try { // Execute the geoprocessing analysis and wait for the results GeoprocessingResult myAnalysisResult = await _hotspotJob.GetResultAsync(); // Add results to a map using map server from a geoprocessing task // Load to get access to full extent await myAnalysisResult.MapImageLayer.LoadAsync(); // Add the analysis layer to the map view MyMapView.Map.OperationalLayers.Add(myAnalysisResult.MapImageLayer); // Zoom to the results await MyMapView.SetViewpointAsync(new Viewpoint(myAnalysisResult.MapImageLayer.FullExtent)); } catch (TaskCanceledException) { // This is thrown if the task is canceled. Ignore. } catch (Exception ex) { // Display error messages if the geoprocessing task fails if (_hotspotJob.Status == JobStatus.Failed && _hotspotJob.Error != null) { MessageBox.Show("Executing geoprocessing failed. " + _hotspotJob.Error.Message, "Geoprocessing error"); } else { MessageBox.Show("An error occurred. " + ex, "Sample error"); } } finally { // Remove the waiting ShowBusyOverlay(false); } }
private async void Initialize() { // Set paths that are relative to execution path string currentDir = Directory.GetCurrentDirectory(); int idx = currentDir.IndexOf("bin") - 1; appRootDir = currentDir.Substring(0, idx); appDataDir = appRootDir + @"\Data"; appTempDir = appRootDir + @"\temp"; // Set up files testImage = appDataDir + @"\sampleFile.tiff"; gpPackage = appDataDir + @"\CreateMapTilePackage.gpkx"; mapPackage = appDataDir + @"\emptyMapPackage.mpkx"; Debug.WriteLine(">> App Root Directory = " + appRootDir); Debug.WriteLine(">> App Data Directory = " + appDataDir); Debug.WriteLine(">> App Temp Directory = " + appTempDir); ////////////// start Q Basket set up ////////////////// // Create raster layer from a raster file (Geotiff) Debug.WriteLine("Loading raster layer from " + testImage); RasterLayer inRasterLayer = new RasterLayer(testImage); // Load Raster into Raster Layer try { await inRasterLayer.LoadAsync(); if (inRasterLayer.LoadStatus != Esri.ArcGISRuntime.LoadStatus.Loaded) { Debug.WriteLine("Error - Input Raster Layer not loaded "); } } catch (Exception ex) { string msg = "Unable to load the raster\n"; msg += "Raster file = " + testImage; msg += "Load status = " + inRasterLayer.LoadStatus.ToString(); msg += "\n\nMessage: " + ex.Message; MessageBox.Show(msg, "inRasterLayer.LoadAsync failed"); } // Create a new EnvelopeBuilder from the full extent of the raster layer. // Add a small zoom to make sure entire map is viewable EnvelopeBuilder envelopeBuilder = new EnvelopeBuilder(inRasterLayer.FullExtent); envelopeBuilder.Expand(0.75); // Create a basemap from the raster layer Basemap baseMap = new Basemap(inRasterLayer); // Create a new map using the new basemap Map newMap = new Map(baseMap); // Set the viewpoint of the map to the proper extent. newMap.InitialViewpoint = new Viewpoint(envelopeBuilder.ToGeometry().Extent); // Create a map and add it to the view MyMapView.Map = newMap; // Load new map to display basemap try { // Add map to the map view. MyMapView.Map = newMap; // Wait for the map to load. await newMap.LoadAsync(); } catch (Exception ex) { string msg = "Unable to load the Map\n"; msg += "\n\nMessage: " + ex.Message; MessageBox.Show(msg, "newMap.LoadAsync failed"); } // Wait for rendering to finish before taking the screenshot for the thumbnail await WaitForRenderCompleteAsync(MyMapView); ////////////// end Q Basket set up ////////////////// // Start the Local Server try { // LocalServer must not be running when setting the data path. if (LocalServer.Instance.Status == LocalServerStatus.Started) { await LocalServer.Instance.StopAsync(); } // Set the local data path - must be done before starting. // Avoid Windows path length limitations (260). // CreateDirectory won't overwrite if it already exists. Directory.CreateDirectory(appTempDir); LocalServer.Instance.AppDataPath = appTempDir; // Start the local server instance await LocalServer.Instance.StartAsync(); MessageBox.Show("Local Server started"); Debug.WriteLine(">> Local Server started"); // Get the URL for the localServer // localhost port is variable localServerURL = LocalServer.Instance.Url.AbsoluteUri; Debug.WriteLine("\n>> Local server url - " + localServerURL); Debug.WriteLine(">> Local server App Data Path - " + LocalServer.Instance.AppDataPath); } catch (Exception ex) { string msg = "Please ensure the local server is installed \nand configured correctly"; msg += String.Format("\nMessage: {0}", ex.Message); MessageBox.Show(msg, "Local Server failed to start"); Debug.WriteLine(msg); App.Current.Shutdown(); } // LOCAL MAP SERVICE INIT // Create and start the local map service try { _localMapService = new LocalMapService(mapPackage); } catch (Exception ex) { string msg = "Cannot create the local map service"; msg += "Map Package = " + mapPackage; msg += String.Format("\nMessage: {0}", ex.Message); MessageBox.Show(msg, "Local Map Server failed to start"); Debug.WriteLine(msg); App.Current.Shutdown(); } // RASTER WORKSPACE CREATION // Create the Raster workspace; this workspace name was chosen arbitrarily // Does workspace need to be the same directory as rasters? // setting to temp directory rasterWorkspace = new RasterWorkspace("raster_wkspc", appTempDir); Debug.WriteLine(">> raster workspace folder = " + rasterWorkspace.FolderPath); Debug.WriteLine(">> raster workspace id = " + rasterWorkspace.Id); // Create the layer source that represents the Raster on disk RasterSublayerSource source = new RasterSublayerSource(rasterWorkspace.Id, testImage); // Create a sublayer instance from the table source _rasterSublayer = new ArcGISMapImageSublayer(0, source); // Add the dynamic workspace to the map service _localMapService.SetDynamicWorkspaces(new List <DynamicWorkspace>() { rasterWorkspace }); // Register map service status chagne event handle _localMapService.StatusChanged += _localMapService_StatusChanged; // Start the map service try { await _localMapService.StartAsync(); } catch (Exception ex) { string msg = "Cannot start the local map service"; msg += "Map Package = " + mapPackage; msg += String.Format("\nMessage: {0}", ex.Message); MessageBox.Show(msg, "Local Map Server failed to start"); Debug.WriteLine(msg); App.Current.Shutdown(); } // Get the url to the local map service localMapServiceURL = _localMapService.Url.AbsoluteUri; MessageBox.Show("Local Map Service URL = " + localMapServiceURL); Debug.WriteLine("Local Map Service URL = " + localMapServiceURL); // LOCAL GEOPROCESSING SERVICE INIT // Create the geoprocessing service _localGPservice = new LocalGeoprocessingService(gpPackage, gpServiceType); // Ass GP service status chagned event handler _localGPservice.StatusChanged += GpServiceOnStatusChanged; // Try to start the service try { // Start the service await _localGPservice.StartAsync(); if (_localGPservice.Status == LocalServerStatus.Failed) { string msg = ("Geoprocessing service failed to start.\n"); MessageBox.Show(msg, "gpService.StartAsync failed"); App.Current.Shutdown(); } else if (_localGPservice.Status == LocalServerStatus.Started) { localGPserviceUrl = _localGPservice.Url.AbsoluteUri + "/CreateMapTilePackage"; string msg = ("Geoprocessing service started.\n"); msg += "\n>> GP Service URL: " + localGPserviceUrl; msg += ">> GP Service Max Records: " + _localGPservice.MaxRecords; msg += ">> GP Service Package Path: " + _localGPservice.PackagePath; msg += ">> GP Service Type: " + _localGPservice.ServiceType; MessageBox.Show(msg, "gpService.StartAsync started"); Debug.WriteLine("\n>> GP Service URL: " + localGPserviceUrl); Debug.WriteLine(">> GP Service Max Records: " + _localGPservice.MaxRecords); Debug.WriteLine(">> GP Service Package Path: " + _localGPservice.PackagePath); Debug.WriteLine(">> GP Service Type: " + _localGPservice.ServiceType); } } catch (Exception ex) { string msg = ("Geoprocessing service failed to start.\n"); msg += "\nGeoprocessing package - " + gpPackage + "\n"; msg += String.Format("\nMessage: {0}", ex.Message); MessageBox.Show(msg, "gpService.StartAsync failed"); return; } // GEOPROCESSING TASK INIT // Create the geoprocessing task from the service try { string url = _localGPservice.Url + "/CreateMapTilePackage"; _gpTask = await GeoprocessingTask.CreateAsync(new Uri(url)); } catch (Exception ex) { string msg = ("Geoprocessing task failed to start.\n"); msg += "\nlocalGPserviceUrl- " + localGPserviceUrl + "\n"; msg += String.Format("\nMessage: {0}", ex.Message); MessageBox.Show(msg, "GeoprocessingTask.CreateAsync failed"); return; } MessageBox.Show("GeoprocessingTask.CreateAsync created"); // GEOPROCESSING JOB // Create the geoprocessing parameters GeoprocessingParameters gpParams = new GeoprocessingParameters(gpExecutionType); // Add the interval parameter to the geoprocessing parameters //GeoprocessingString Input_Map = new GeoprocessingString("MyMapView.Map"); GeoprocessingString Input_Map = new GeoprocessingString("localMapServiceURL"); GeoprocessingDouble Max_LOD = new GeoprocessingDouble(10); GeoprocessingString Output_Package = new GeoprocessingString("C://Karen/Data/TilePackages/test.tpkx"); gpParams.Inputs.Add("Input_Map", Input_Map); gpParams.Inputs.Add("Max_LOD", Max_LOD); gpParams.Inputs.Add("Output_Package", Output_Package); // Create the job try { _gpJob = _gpTask.CreateJob(gpParams); } catch (Exception ex) { string msg = ("Geoprocessing job cannot be created.\n"); msg += String.Format("\nMessage: {0}", ex.Message); MessageBox.Show(msg, "_gpTask.CreateJob failed"); return; } MessageBox.Show("GeoprocessingTask.CreateJob created"); MyLoadingIndicator.Visibility = Visibility.Visible; // Update the UI when job progress changes _gpJob.ProgressChanged += (sender, args) => { Dispatcher.Invoke(() => { MyLoadingIndicator.Value = _gpJob.Progress; }); }; // Be notified when the task completes (or other change happens) _gpJob.JobChanged += GpJobOnJobChanged; // Start the job try { _gpJob.Start(); } catch (Exception ex) { string msg = ("Geoprocessing start job failed to start.\n"); msg += String.Format("\nMessage: {0}", ex.Message); MessageBox.Show(msg, "_gpjob.Start failed"); return; } MessageBox.Show("GeoprocessingTask job started"); }