void myDrawObject_DrawComplete(object sender, DrawEventArgs e) { myDrawObject.IsEnabled = false; GraphicsLayer graphicsLayer = MyMap.Layers["MyGraphicsLayer"] as GraphicsLayer; graphicsLayer.ClearGraphics(); Graphic graphic = new ESRI.ArcGIS.Client.Graphic() { Geometry = e.Geometry, Symbol = LayoutRoot.Resources["DefaultClickSymbol"] as ESRI.ArcGIS.Client.Symbols.Symbol }; graphic.SetZIndex(1); graphicsLayer.Graphics.Add(graphic); GeometryService geometryService = new GeometryService("http://serverapps101.esri.com/arcgis/rest/services/Geometry/GeometryServer"); geometryService.BufferCompleted += GeometryService_BufferCompleted; geometryService.Failed += GeometryService_Failed; BufferParameters bufferParams = new BufferParameters() { Unit = LinearUnit.StatuteMile, OutSpatialReference = MyMap.SpatialReference, Geodesic = true }; bufferParams.Features.Add(graphic); bufferParams.Distances.Add(5); geometryService.BufferAsync(bufferParams); }
internal static void ShowPopup(Graphic graphic, Layer layer, int? layerId = null) { OnClickPopupInfo popupInfo = GetPopup(new[]{graphic}, layer, layerId); if (graphic.Geometry is MapPoint) ShowPopup(popupInfo, (MapPoint)graphic.Geometry); else if (graphic.Geometry is Polygon) { if (!string.IsNullOrEmpty(MapApplication.Current.Urls.GeometryServiceUrl)) { GeometryService geometryService = new GeometryService(MapApplication.Current.Urls.GeometryServiceUrl); geometryService.LabelPointsCompleted += (s, args) => { if (args.Results != null && args.Results.Count > 0) ShowPopup(popupInfo, (MapPoint)args.Results[0].Geometry); else ShowPopup(popupInfo, graphic.Geometry); }; geometryService.Failed += (s, args) => { ShowPopup(popupInfo,graphic.Geometry); }; geometryService.LabelPointsAsync(new[] { graphic }); } else { ShowPopup(popupInfo,graphic.Geometry); } } SyncPreviousDisplayMode(popupInfo); }
private void CacheSnapObjects(ESRI.ArcGIS.Client.Geometry.Geometry geometryObject, double snapDistance) { // For the given geometry (line or circle), find all the features that fall within the snapDistance. // First we need to issue a buffer in this method. GeometryService_LineBufferCompleted will // do the feature query. _snapObjects.Clear(); GeometryService geometryServiceScaleRotate = new GeometryService(_xmlConfiguation.GeometryServerUrl); if (geometryServiceScaleRotate == null) return; geometryServiceScaleRotate.BufferCompleted += GeometryService_LineBufferCompleted; geometryServiceScaleRotate.Failed += GeometryService_Failed; geometryServiceScaleRotate.CancelAsync(); Graphic clickGraphic = new Graphic(); clickGraphic.Symbol = LayoutRoot.Resources["DefaultMarkerSymbol"] as ESRI.ArcGIS.Client.Symbols.Symbol; clickGraphic.Geometry = geometryObject; // Input spatial reference for buffer operation defined by first feature of input geometry array clickGraphic.Geometry.SpatialReference = ParcelMap.SpatialReference; // If buffer spatial reference is GCS and unit is linear, geometry service will do geodesic buffering ESRI.ArcGIS.Client.Tasks.BufferParameters bufferParams = new ESRI.ArcGIS.Client.Tasks.BufferParameters() { BufferSpatialReference = ParcelMap.SpatialReference, OutSpatialReference = ParcelMap.SpatialReference, }; bufferParams.Distances.Add(snapDistance); bufferParams.Features.Add(clickGraphic); System.Diagnostics.Debug.WriteLine("Async: Buffering potential candidates for snapping."); geometryServiceScaleRotate.BufferAsync(bufferParams, snapDistance); }
private void MyMap_MouseClick(object sender, ESRI.ArcGIS.Client.Map.MouseEventArgs e) { GraphicsLayer graphicsLayer = MyMap.Layers["MyGraphicsLayer"] as GraphicsLayer; graphicsLayer.ClearGraphics(); e.MapPoint.SpatialReference = MyMap.SpatialReference; Graphic graphic = new ESRI.ArcGIS.Client.Graphic() { Geometry = e.MapPoint, Symbol = LayoutRoot.Resources["DefaultClickSymbol"] as ESRI.ArcGIS.Client.Symbols.Symbol }; graphic.SetZIndex(1); graphicsLayer.Graphics.Add(graphic); GeometryService geometryService = new GeometryService("http://serverapps101.esri.com/arcgis/rest/services/Geometry/GeometryServer"); geometryService.BufferCompleted += GeometryService_BufferCompleted; geometryService.Failed += GeometryService_Failed; // If buffer spatial reference is GCS and unit is linear, geometry service will do geodesic buffering BufferParameters bufferParams = new BufferParameters() { Unit = chkGeodesic.IsChecked.HasValue && chkGeodesic.IsChecked.Value ? LinearUnit.StatuteMile : (LinearUnit?)null, BufferSpatialReference = new SpatialReference(4326), OutSpatialReference = MyMap.SpatialReference }; bufferParams.Features.Add(graphic); bufferParams.Distances.Add(5); bufferParams.Geodesic = chkGeodesic.IsChecked == true ? true : false; geometryService.BufferAsync(bufferParams); }
private void ExecuteRelationButton_Click(object sender, System.Windows.RoutedEventArgs e) { MyDrawObject.IsEnabled = false; ExecuteRelationButton.Visibility = Visibility.Collapsed; geometryService = new GeometryService("http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer"); geometryService.RelationCompleted += GeometryService_RelationCompleted; geometryService.SimplifyCompleted += GeometryService_SimplifyCompleted; geometryService.Failed += GeometryService_Failed; if (pointLayer.Graphics.Count < 1) { MessageBox.Show("No points available"); ExecuteRelationButton.Visibility = Visibility.Visible; return; } foreach (Graphic graphic in pointLayer.Graphics) graphic.Attributes["Relation"] = null; foreach (Graphic graphic in polygonLayer.Graphics) graphic.Attributes["Relation"] = null; // Call simplify operation to correct orientation of rings in a polygon (clockwise = ring, counterclockwise = hole) geometryService.SimplifyAsync(polygonLayer.Graphics); }
public Intersect() { InitializeComponent(); MyMap.Layers.LayersInitialized += Layers_LayersInitialized; MyMap.MinimumResolution = double.Epsilon; MyDrawObject = new Draw(MyMap) { DrawMode = DrawMode.Polygon, IsEnabled = false, FillSymbol = LayoutRoot.Resources["CyanFillSymbol"] as ESRI.ArcGIS.Client.Symbols.FillSymbol }; MyDrawObject.DrawComplete += MyDrawObject_DrawComplete; parcelGraphicsLayer = MyMap.Layers["ParcelsGraphicsLayer"] as GraphicsLayer; intersectGraphicsLayer = MyMap.Layers["IntersectGraphicsLayer"] as GraphicsLayer; geometryService = new GeometryService("http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer"); geometryService.SimplifyCompleted += GeometryService_SimplifyCompleted; geometryService.IntersectCompleted += GeometryService_IntersectCompleted; geometryService.Failed += GeometryService_Failed; random = new Random(); }
private void MyDrawObject_DrawComplete(object sender, DrawEventArgs args) { args.Geometry.SpatialReference = MyMap.SpatialReference; Graphic graphic = new Graphic(){ Geometry = args.Geometry }; if (args.Geometry is Polyline) graphic.Symbol = LayoutRoot.Resources["DefaultLineSymbol"] as ESRI.ArcGIS.Client.Symbols.Symbol; else graphic.Symbol = LayoutRoot.Resources["DefaultMarkerSymbol"] as ESRI.ArcGIS.Client.Symbols.Symbol; graphicsLayer.Graphics.Add(graphic); if (graphicsLayer.Graphics.Count == 1) MyDrawObject.DrawMode = DrawMode.Point; else if (graphicsLayer.Graphics.Count == 2) { MyDrawObject.IsEnabled = false; GeometryService geometryService = new GeometryService("http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer"); geometryService.DistanceCompleted += GeometryService_DistanceCompleted; geometryService.Failed += GeometryService_Failed; MyDrawObject.DrawMode = DrawMode.Polyline; DistanceParameters distanceParameters = new DistanceParameters() { DistanceUnit = LinearUnit.SurveyMile, Geodesic = true }; geometryService.DistanceAsync(graphicsLayer.Graphics[0].Geometry, graphicsLayer.Graphics[1].Geometry,distanceParameters); ResponseTextBlock.Text = "The distance between geometries is... "; } }
public QueryHelper(OpsDashboard.MapWidget mapWidget, IList<OpsDashboard.DataSource> dataSources, IEnumerable<Graphic> sourceFeatures) { //A geometry service contains utility methods that provide access to sophisticated and frequently used geometric operations //such as buffer, calculate areas and lengths for geometry etc geometryService = new GeometryService("http://sampleserver6.arcgisonline.com/ArcGIS/rest/services/Utilities/Geometry/GeometryServer"); MapWidget = mapWidget; SourceFeatures = sourceFeatures; TargetDataSources = dataSources; }
public Project() { InitializeComponent(); geometryService = new GeometryService("http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer"); geometryService.ProjectCompleted += geometryService_ProjectCompleted; geometryService.Failed += geometryService_Failed; graphicsLayer = MyMap.Layers["MyGraphicsLayer"] as GraphicsLayer; }
public BufferQueryTaskAsync() { InitializeComponent(); _geometryService = new GeometryService("http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer"); _queryTask = new QueryTask("http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/BloomfieldHillsMichigan/Parcels/MapServer/2"); _pointAndBufferGraphicsLayer = MyMap.Layers["MyBufferPointGraphicsLayer"] as GraphicsLayer; _resultsGraphicsLayer = MyMap.Layers["MyResultsGraphicsLayer"] as GraphicsLayer; }
private void ConvexButton_Click(object sender, RoutedEventArgs e) { ConvexButton.IsEnabled = false; outputGraphicsLayer.ClearGraphics(); GeometryService geometryService = new GeometryService("http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer"); geometryService.ConvexHullCompleted += GeometryService_ConvexHullCompleted; geometryService.Failed += GeometryService_Failed; geometryService.ConvexHullAsync(inputGraphicsLayer.ToList()); }
public MainWindow() { // License setting and ArcGIS Runtime initialization is done in Application.xaml.cs. //Converting from WGS1984(WKID4326) to Web Mercator(WKID 102100) //Expected output: //outstring "contains 9 points\n //-16760359.2704728 17285613.0087787\n //-47750.2729367931 -382002.488729203\n //18479370.4320312 -18240618.8875065\n //18192868.5717715 16999110.8145016\n //-15900853.6896935 -17476613.9857872\n //-10552818.7793126 10696069.8481236\n //12653832.4583238 10791570.3324641\n //-9979815.0587931 -11937577.7150823\n //13417837.4932295 -11651075.9091873\n InitializeComponent(); geometryService = new GeometryService("http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer"); geometryService.ProjectCompleted += geometryService_ProjectCompleted; geometryService.Failed += geometryService_Failed; graphicsLayer = MyMap.Layers["MyGraphicsLayer"] as GraphicsLayer; List<Graphic> listgraphic = new List<Graphic>(); MapPoint inp1 = new MapPoint(-150.560869, 82.387691, new SpatialReference(4326)); MapPoint inp2 = new MapPoint(-0.428948, -3.429537, new SpatialReference(4326)); MapPoint inp3 = new MapPoint(166.003009, -83.443769, new SpatialReference(4326)); MapPoint inp4 = new MapPoint(163.429319, 82.039054, new SpatialReference(4326)); MapPoint inp5 = new MapPoint(-142.839799, -82.61164, new SpatialReference(4326)); MapPoint inp6 = new MapPoint(-94.797584, 68.823145, new SpatialReference(4326)); MapPoint inp7 = new MapPoint(113.671311, 69.130903, new SpatialReference(4326)); MapPoint inp8 = new MapPoint(-89.650204, -72.504886, new SpatialReference(4326)); MapPoint inp9 = new MapPoint(120.534485, -71.714384, new SpatialReference(4326)); listgraphic.Add(new Graphic() { Geometry = inp1 }); listgraphic.Add(new Graphic() { Geometry = inp2 }); listgraphic.Add(new Graphic() { Geometry = inp3 }); listgraphic.Add(new Graphic() { Geometry = inp4 }); listgraphic.Add(new Graphic() { Geometry = inp5 }); listgraphic.Add(new Graphic() { Geometry = inp6 }); listgraphic.Add(new Graphic() { Geometry = inp7 }); listgraphic.Add(new Graphic() { Geometry = inp8 }); listgraphic.Add(new Graphic() { Geometry = inp9 }); geometryService.ProjectAsync(listgraphic, new SpatialReference(102100)); }
private void MyDrawObject_DrawComplete(object sender, DrawEventArgs args) { MyDrawObject.IsEnabled = false; ESRI.ArcGIS.Client.Geometry.Polyline polyline = args.Geometry as ESRI.ArcGIS.Client.Geometry.Polyline; polyline.SpatialReference = MyMap.SpatialReference; GeometryService geometryService = new GeometryService("http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer"); geometryService.CutCompleted += GeometryService_CutCompleted; geometryService.Failed += GeometryService_Failed; geometryService.CutAsync(parcelGraphicsLayer.Graphics.ToList(), polyline); }
public IntersectTaskAsync() { InitializeComponent(); _myDrawObject = new Draw(MyMap) { DrawMode = DrawMode.Polygon, IsEnabled = false, FillSymbol = LayoutRoot.Resources["CyanFillSymbol"] as ESRI.ArcGIS.Client.Symbols.FillSymbol }; _myDrawObject.DrawComplete += MyDrawObject_DrawComplete; _myDrawObject.IsEnabled = true; _intersectGraphicsLayer = MyMap.Layers["IntersectGraphicsLayer"] as GraphicsLayer; _geometryService = new GeometryService("http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer"); }
private void ConvexButton_Click(object sender, RoutedEventArgs e) { ConvexButton.IsEnabled = false; outputGraphicsLayer.ClearGraphics(); GeometryService geometryService = new GeometryService("http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer"); geometryService.ConvexHullCompleted += GeometryService_ConvexHullCompleted; geometryService.Failed += GeometryService_Failed; List<Graphic> graphicsList = new List<Graphic>(); foreach (Graphic g in inputGraphicsLayer.Graphics) { graphicsList.Add(g); } geometryService.ConvexHullAsync(graphicsList); }
private void MyDrawObject_DrawComplete(object sender, DrawEventArgs args) { ESRI.ArcGIS.Client.Geometry.Polyline polyline = args.Geometry as ESRI.ArcGIS.Client.Geometry.Polyline; polyline.SpatialReference = MyMap.SpatialReference; Graphic graphic = new Graphic() { Symbol = LayoutRoot.Resources["DefaultLineSymbol"] as ESRI.ArcGIS.Client.Symbols.Symbol, Geometry = polyline }; GeometryService geometryService = new GeometryService("http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer"); geometryService.LengthsCompleted += GeometryService_LengthsCompleted; geometryService.Failed += GeometryService_Failed; GraphicsLayer graphicsLayer = MyMap.Layers["MyGraphicsLayer"] as GraphicsLayer; graphicsLayer.Graphics.Add(graphic); geometryService.LengthsAsync(graphicsLayer.Graphics.ToList(), LinearUnit.SurveyMile, CalculationType.Geodesic, null); }
private void MyDrawObject_DrawComplete(object sender, DrawEventArgs args) { MyDrawObject.IsEnabled = false; resultsLayer.ClearGraphics(); Polyline polyline = args.Geometry as Polyline; polyline.SpatialReference = MyMap.SpatialReference; geometryService = new GeometryService("http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer"); geometryService.TrimExtendCompleted += GeometryService_TrimExtendCompleted; geometryService.Failed += GeometryService_Failed; List<Polyline> polylineList = new List<Polyline>(); foreach (Graphic g in polylineLayer.Graphics) polylineList.Add(g.Geometry as Polyline); geometryService.TrimExtendAsync(polylineList, polyline, CurveExtension.DefaultCurveExtension); }
private void GeneralizeButton_Click(object sender, RoutedEventArgs e) { GeneralizeButton.IsEnabled = false; SliderStackPanel.Visibility = Visibility.Collapsed; GraphicsLayer originalGraphicsLayer = MyMap.Layers["OriginalLineGraphicsLayer"] as GraphicsLayer; GeometryService geometryService = new GeometryService("http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer"); geometryService.GeneralizeCompleted += GeometryService_GeneralizeCompleted; geometryService.Failed += GeometryService_Failed; GeneralizeParameters generalizeParameters = new GeneralizeParameters() { DeviationUnit = LinearUnit.SurveyMile, MaxDeviation = 0.000001 }; geometryService.GeneralizeAsync(new List<Graphic>() { originalGraphicsLayer.Graphics[0] }, generalizeParameters); }
private void DensifyButton_Click(object sender, RoutedEventArgs e) { DensifyButton.IsEnabled = false; GraphicsLayer graphicsLayerPolygon = MyMap.Layers["PolygonGraphicsLayer"] as GraphicsLayer; GeometryService geometryService = new GeometryService("http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer"); geometryService.DensifyCompleted += GeometryService_DensifyCompleted; geometryService.Failed += GeometryService_Failed; DensifyParameters densityParameters = new DensifyParameters() { LengthUnit = LinearUnit.Meter, Geodesic = true, MaxSegmentLength = MyMap.Resolution * 10 }; geometryService.DensifyAsync(graphicsLayerPolygon.Graphics.ToList(), densityParameters); }
public LabelPoints() { InitializeComponent(); MyDrawObject = new Draw(MyMap) { FillSymbol = LayoutRoot.Resources["DefaultPolygonSymbol"] as ESRI.ArcGIS.Client.Symbols.FillSymbol, DrawMode = DrawMode.Polygon, IsEnabled = true }; MyDrawObject.DrawComplete += MyDrawObject_DrawComplete; geometryService = new GeometryService("http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer"); geometryService.SimplifyCompleted += GeometryService_SimplifyCompleted; geometryService.LabelPointsCompleted += GeometryService_LabelPointsCompleted; geometryService.Failed += GeometryService_Failed; graphicsLayer = MyMap.Layers["MyGraphicsLayer"] as GraphicsLayer; }
public Difference() { InitializeComponent(); geometryService = new GeometryService("http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer"); geometryService.DifferenceCompleted += GeometryService_DifferenceCompleted; geometryService.SimplifyCompleted += GeometryService_SimplifyCompleted; geometryService.Failed += GeometryService_Failed; inputGraphicsLayer = MyMap.Layers["InputGraphicsLayer"] as GraphicsLayer; MyDrawObject = new Draw(MyMap) { DrawMode = DrawMode.Polygon, IsEnabled = false, FillSymbol = LayoutRoot.Resources["DrawFillSymbol"] as ESRI.ArcGIS.Client.Symbols.FillSymbol }; MyDrawObject.DrawComplete += MyDrawObject_DrawComplete; }
public Difference() { InitializeComponent(); geometryService = new GeometryService("http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer"); geometryService.DifferenceCompleted += GeometryService_DifferenceCompleted; geometryService.SimplifyCompleted += GeometryService_SimplifyCompleted; geometryService.Failed += GeometryService_Failed; inputGraphicsLayer = MyMap.Layers["InputGraphicsLayer"] as GraphicsLayer; MyDrawObject = new Draw(MyMap) { DrawMode = DrawMode.Polygon, IsEnabled = true, FillSymbol = LayoutRoot.Resources["DrawFillSymbol"] as ESRI.ArcGIS.Client.Symbols.FillSymbol }; MyDrawObject.DrawComplete += MyDrawObject_DrawComplete; }
private void MyDrawObject_DrawComplete(object sender, DrawEventArgs args) { ESRI.ArcGIS.Client.Geometry.Polyline polyline = args.Geometry as ESRI.ArcGIS.Client.Geometry.Polyline; polyline.SpatialReference = MyMap.SpatialReference; Graphic graphic = new Graphic() { Symbol = LayoutRoot.Resources["DefaultLineSymbol"] as ESRI.ArcGIS.Client.Symbols.Symbol, Geometry = polyline }; GeometryService geometryService = new GeometryService("http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer"); geometryService.LengthsCompleted += GeometryService_LengthsCompleted; geometryService.Failed += GeometryService_Failed; GraphicsLayer graphicsLayer = MyMap.Layers["MyGraphicsLayer"] as GraphicsLayer; graphicsLayer.Graphics.Add(graphic); geometryService.LengthsAsync(graphicsLayer.Graphics.ToList(), LinearUnit.SurveyMile, true, null); }
private void DensifyButton_Click(object sender, RoutedEventArgs e) { DensifyButton.IsEnabled = false; GraphicsLayer graphicsLayerPolygon = MyMap.Layers["PolygonGraphicsLayer"] as GraphicsLayer; GeometryService geometryService = new GeometryService("http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer"); geometryService.DensifyCompleted += GeometryService_DensifyCompleted; geometryService.Failed += GeometryService_Failed; DensifyParameters densityParameters = new DensifyParameters() { LengthUnit = LinearUnit.Meter, Geodesic = true, MaxSegmentLength = MyMap.Resolution * 10 }; geometryService.DensifyAsync(graphicsLayerPolygon.Graphics.ToList(), densityParameters); }
public LabelPoints() { InitializeComponent(); MyDrawObject = new Draw(MyMap) { FillSymbol = LayoutRoot.Resources["DefaultPolygonSymbol"] as ESRI.ArcGIS.Client.Symbols.FillSymbol, DrawMode = DrawMode.Polygon, IsEnabled = true }; MyDrawObject.DrawComplete += MyDrawObject_DrawComplete; geometryService = new GeometryService("http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer"); geometryService.SimplifyCompleted += GeometryService_SimplifyCompleted; geometryService.LabelPointsCompleted += GeometryService_LabelPointsCompleted; geometryService.Failed += GeometryService_Failed; graphicsLayer = MyMap.Layers["MyGraphicsLayer"] as GraphicsLayer; }
public void DownloadTile_BBox(string datasetName) { var datasets = DEMDataSet.RegisteredDatasets; Assert.True(datasets.Any(), "No datasets found"); DEMDataSet dataset = datasets.FirstOrDefault(d => d.Name == datasetName); Assert.NotNull(dataset); const string WKT_BBOX_AIX_PUYRICARD = "POLYGON ((5.429993 43.537854, 5.459132 43.537854, 5.459132 43.58151, 5.429993 43.58151, 5.429993 43.537854))"; BoundingBox bbox = GeometryService.GetBoundingBox(WKT_BBOX_AIX_PUYRICARD); _elevationService.DownloadMissingFiles(dataset, bbox); var report = _rasterService.GenerateReport(dataset, bbox); Assert.NotNull(report); Assert.True(report.Count > 0); Assert.True(report.First().IsExistingLocally); }
public IHttpActionResult GetPathElevation(Location[] path, int samples, ResponseFormat format = ResponseFormat.Google) { try { var geoPoints = ModelFactory.Create(path); var geom = GeometryService.ParseGeoPointAsGeometryLine(geoPoints); _elevationService.DownloadMissingFiles(DEMDataSet.AW3D30, geom.GetBoundingBox()); geoPoints = _elevationService.GetLineGeometryElevation(geom, DEMDataSet.AW3D30, InterpolationMode.Bilinear); ElevationMetrics metrics = GeometryService.ComputeMetrics(ref geoPoints); if (samples > 2) { double ratio = 4 / 2; double tolerance = (metrics.MaxElevation - metrics.MinElevation) / (samples / ratio); geoPoints = DouglasPeucker.DouglasPeuckerReduction(geoPoints, tolerance); } // Model ElevationMetricsModel metricsModel = ModelFactory.CreateElevationMetricsModel(geoPoints, metrics); switch (format) { case ResponseFormat.GeoJSON: var feature = ModelFactory.CreateFeature(geoPoints, metricsModel); return(Ok(feature)); case ResponseFormat.Google: default: return(Ok(ModelFactory.CreateElevationResults(geoPoints, metricsModel))); } return(BadRequest()); } catch (Exception ex) { return(InternalServerError(new Exception(ex.Message))); } }
static void LineDEMTest(ElevationService elevationService, DEMDataSet dataSet, string wkt, int numSamples) { Stopwatch sw = Stopwatch.StartNew(); elevationService.DownloadMissingFiles(dataSet, GetBoundingBox(wkt)); var lineElevationData = elevationService.GetLineGeometryElevation(wkt, dataSet, InterpolationMode.Bilinear); ElevationMetrics metrics = GeometryService.ComputeMetrics(ref lineElevationData); var lineElevationData_Reduced = DouglasPeucker.DouglasPeuckerReduction(lineElevationData, (metrics.MaxElevation - metrics.MinElevation) / numSamples); sw.Stop(); Console.WriteLine($"LineDEMTest performed in {sw.Elapsed:g}."); SpatialTrace.Enable(); SpatialTrace.Clear(); SpatialTraceLine(lineElevationData, $"Full resolution line ({lineElevationData.Count} points)"); SpatialTraceLine(lineElevationData_Reduced, $"Reduced line ({lineElevationData_Reduced.Count} points)"); SpatialTrace.ShowDialog(); }
public void LineLineIntersectionTest() { string wkt1 = "LINESTRING(-5.888671875 47.90161354142077,3.4716796875 44.11914151643737)"; string wkt2 = "LINESTRING(-2.8564453125 44.30812668488613,5.625 48.166085419012525)"; Geometry geom1 = GeometryService.ParseWKTAsGeometry(wkt1); Geometry geom2 = GeometryService.ParseWKTAsGeometry(wkt2); Geometry intersection = geom1.Intersection(geom2); GeoSegment seg1 = geom1.Segments().First(); GeoSegment seg2 = geom2.Segments().First(); GeoPoint intersectionResult = GeoPoint.Zero; bool intersects = GeometryService.LineLineIntersection(out intersectionResult, seg1, seg2); double dist = intersection.Coordinate.ToGeoPoint().DistanceTo(intersectionResult); Assert.True(dist < 0.05d, "Problem in intersection calculation."); }
private void CacheSnapObjects(ESRI.ArcGIS.Client.Geometry.Geometry geometryObject, double snapDistance) { // For the given geometry (line or circle), find all the features that fall within the snapDistance. // First we need to issue a buffer in this method. GeometryService_LineBufferCompleted will // do the feature query. _snapObjects.Clear(); GeometryService geometryServiceScaleRotate = new GeometryService(_xmlConfiguation.GeometryServerUrl); if (geometryServiceScaleRotate == null) { return; } geometryServiceScaleRotate.BufferCompleted += GeometryService_LineBufferCompleted; geometryServiceScaleRotate.Failed += GeometryService_Failed; geometryServiceScaleRotate.CancelAsync(); Graphic clickGraphic = new Graphic(); clickGraphic.Symbol = LayoutRoot.Resources["DefaultMarkerSymbol"] as ESRI.ArcGIS.Client.Symbols.Symbol; clickGraphic.Geometry = geometryObject; // Input spatial reference for buffer operation defined by first feature of input geometry array clickGraphic.Geometry.SpatialReference = ParcelMap.SpatialReference; // If buffer spatial reference is GCS and unit is linear, geometry service will do geodesic buffering ESRI.ArcGIS.Client.Tasks.BufferParameters bufferParams = new ESRI.ArcGIS.Client.Tasks.BufferParameters() { BufferSpatialReference = ParcelMap.SpatialReference, OutSpatialReference = ParcelMap.SpatialReference, }; bufferParams.Distances.Add(snapDistance); bufferParams.Features.Add(clickGraphic); System.Diagnostics.Debug.WriteLine("Async: Buffering potential candidates for snapping."); geometryServiceScaleRotate.BufferAsync(bufferParams, snapDistance); }
public void Run() { // DjebelMarra var bbox = GeometryService.GetBoundingBox("POLYGON((7.713614662985839 46.03014517094771,7.990332802634277 46.03014517094771,7.990332802634277 45.86877753239648,7.713614662985839 45.86877753239648,7.713614662985839 46.03014517094771))"); var dataset = DEMDataSet.NASADEM; string modelName = $"{dataset.Name}_{DateTime.Now:yyyyMMdd_HHmmss}"; string outputDir = Directory.GetCurrentDirectory(); //var modelTest = _sharpGltfService.CreateNewModel(); //var triangulation = CreateText("20 km", VectorsExtensions.CreateColor(255, 255, 255)); //_sharpGltfService.AddMesh(modelTest, "Text", triangulation); //// Save model //modelTest.SaveGLB(Path.Combine(outputDir, modelName + ".glb")); var modelAndBbox = GenerateSampleModel(bbox, dataset, withTexture: true); if (modelAndBbox.Model != null) { var model = modelAndBbox.Model; // add adornments Stopwatch swAdornments = Stopwatch.StartNew(); TriangulationList <Vector3> adornments = _adornmentsService.CreateModelAdornments(dataset, ImageryProvider.MapBoxSatellite, bbox, modelAndBbox.projectedBbox); model = _sharpGltfService.AddMesh(model, "Adornments", adornments, default(Vector4), doubleSided: true); swAdornments.Stop(); _logger.LogInformation($"Adornments generation: {swAdornments.ElapsedMilliseconds:N1} ms"); // Save model model.SaveGLB(Path.Combine(outputDir, modelName + ".glb")); _logger.LogInformation($"Model exported as {Path.Combine(outputDir, modelName + ".glb")}"); } }
public void LineLineIntersectionTest() { string wkt1 = "LINESTRING(-5.888671875 47.90161354142077,3.4716796875 44.11914151643737)"; string wkt2 = "LINESTRING(-2.8564453125 44.30812668488613,5.625 48.166085419012525)"; SqlGeometry geom1 = GeometryService.ParseWKTAsGeometry(wkt1); SqlGeometry geom2 = GeometryService.ParseWKTAsGeometry(wkt2); SqlGeometry intersection = geom1.STIntersection(geom2); GeoSegment seg1 = new GeoSegment(new GeoPoint(geom1.STStartPoint().STY.Value, geom1.STStartPoint().STX.Value), new GeoPoint(geom1.STEndPoint().STY.Value, geom1.STEndPoint().STX.Value)); GeoSegment seg2 = new GeoSegment(new GeoPoint(geom2.STStartPoint().STY.Value, geom2.STStartPoint().STX.Value), new GeoPoint(geom2.STEndPoint().STY.Value, geom2.STEndPoint().STX.Value)); GeoPoint intersectionResult = GeoPoint.Zero; bool intersects = GeometryService.LineLineIntersection(out intersectionResult, seg1, seg2); SqlGeography geog1 = null; intersection.TryToGeography(out geog1); SqlGeography geog2 = SqlGeography.Point(intersectionResult.Latitude, intersectionResult.Longitude, 4326); double dist = geog1.STDistance(geog2).Value; Assert.IsTrue(dist < 0.05d, "Problem in intersection calculation."); }
public BufferQuery() { InitializeComponent(); myDrawObject = new Draw(MyMap) { DrawMode = DrawMode.Point, IsEnabled = true }; myDrawObject.DrawComplete += myDrawObject_DrawComplete; _geometryService = new GeometryService("http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer"); _geometryService.BufferCompleted += GeometryService_BufferCompleted; _geometryService.Failed += GeometryService_Failed; _queryTask = new QueryTask("http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/BloomfieldHillsMichigan/Parcels/MapServer/2"); _queryTask.ExecuteCompleted += QueryTask_ExecuteCompleted; _queryTask.Failed += QueryTask_Failed; _pointAndBufferGraphicsLayer = MyMap.Layers["MyGraphicsLayer"] as GraphicsLayer; _resultsGraphicsLayer = MyMap.Layers["MyResultsGraphicsLayer"] as GraphicsLayer; }
public BufferQuery() { InitializeComponent(); myDrawObject = new Draw(MyMap) { DrawMode = DrawMode.Point, IsEnabled = true }; myDrawObject.DrawComplete += myDrawObject_DrawComplete; _geometryService = new GeometryService("http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer"); _geometryService.BufferCompleted += GeometryService_BufferCompleted; _geometryService.Failed += GeometryService_Failed; _queryTask = new QueryTask("http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/BloomfieldHillsMichigan/Parcels/MapServer/2"); _queryTask.ExecuteCompleted += QueryTask_ExecuteCompleted; _queryTask.Failed += QueryTask_Failed; _pointAndBufferGraphicsLayer = MyMap.Layers["MyGraphicsLayer"] as GraphicsLayer; _resultsGraphicsLayer = MyMap.Layers["MyResultsGraphicsLayer"] as GraphicsLayer; }
protected override void OnDownloadConfigXMLCompleted(object sender, DownloadStringCompletedEventArgs e) { string xmlConfig = e.Result; widgetConfig = (SearchNearbyConfig)SearchNearbyConfig.Deserialize(xmlConfig, typeof(SearchNearbyConfig)); if (widgetConfig != null && widgetConfig.SearchLayers != null) { ArcGISQueryLayer[] searchLayers = widgetConfig.SearchLayers; for (int i = 0; i < searchLayers.Length; i++) { ArcGISLayerInfo layerInfo = new ArcGISLayerInfo(searchLayers[i].RESTURL); lstSearchLayer.Items.Add(new ComboBoxItem() { Content = searchLayers[i].Title, Tag = layerInfo }); } geometryService = new GeometryService(this.AppConfig.GeometryService); geometryService.BufferCompleted += new EventHandler <GraphicsEventArgs>(GeometryService_BufferCompleted); } }
internal static void ShowPopup(Graphic graphic, Layer layer, int?layerId = null) { OnClickPopupInfo popupInfo = GetPopup(new[] { graphic }, layer, layerId); if (graphic.Geometry is MapPoint) { ShowPopup(popupInfo, (MapPoint)graphic.Geometry); } else if (graphic.Geometry is Polygon) { if (!string.IsNullOrEmpty(MapApplication.Current.Urls.GeometryServiceUrl)) { GeometryService geometryService = new GeometryService(MapApplication.Current.Urls.GeometryServiceUrl); geometryService.LabelPointsCompleted += (s, args) => { if (args.Results != null && args.Results.Count > 0) { ShowPopup(popupInfo, (MapPoint)args.Results[0].Geometry); } else { ShowPopup(popupInfo, graphic.Geometry); } }; geometryService.Failed += (s, args) => { ShowPopup(popupInfo, graphic.Geometry); }; geometryService.LabelPointsAsync(new[] { graphic }); } else { ShowPopup(popupInfo, graphic.Geometry); } } SyncPreviousDisplayMode(popupInfo); }
public List <BeanPoint_internal> GetPointsTestsByBBox(string p_bbox, DEMDataSet dataset, int sridCible) { List <BeanPoint_internal> v_pointsToTest = new List <BeanPoint_internal>(); try { IRasterService v_rasterService = new RasterService(null); IElevationService v_elevationService = new ElevationService(v_rasterService, null); BoundingBox v_bbox = GeometryService.GetBoundingBox(p_bbox); v_elevationService.DownloadMissingFiles(dataset, v_bbox); // HeightMap v_hMap; v_hMap = v_elevationService.GetHeightMap(ref v_bbox, dataset); v_hMap = v_hMap.ReprojectTo(4326, sridCible); v_pointsToTest = GetGeoPointsByHMap(v_hMap, sridCible); } catch (Exception) { throw; } return(v_pointsToTest); }
internal void Run(Microsoft.Extensions.DependencyInjection.ServiceProvider serviceProvider) { //======================= // Normal map Console.WriteLine("Height map..."); var bbox = GeometryService.GetBoundingBox(_bbox); HeightMap hMap = _elevationService.GetHeightMap(bbox, DEMDataSet.SRTM_GL3); var coords1 = hMap.Coordinates.ToList(); var coords2 = hMap.Coordinates.ToList(); Logger.RestartPerf("Projection with count"); for (int i = 0; i < 5; i++) { coords2.ReprojectTo(4326, Reprojection.SRID_PROJECTED_MERCATOR, coords2.Count).ToList(); } Logger.StopPerf("Projection with count"); Logger.RestartPerf("Projection without count"); for (int i = 0; i < 5; i++) { coords1.ReprojectTo(4326, Reprojection.SRID_PROJECTED_MERCATOR, null).ToList(); } Logger.StopPerf("Projection without count"); }
public void BoudingBoxConservationTest() { string bboxWKT = "POLYGON((5.54888 43.519525, 5.61209 43.519525, 5.61209 43.565225, 5.54888 43.565225, 5.54888 43.519525))"; BoundingBox bbox = GeometryService.GetBoundingBox(bboxWKT); Assert.NotNull(bbox); Assert.Equal(bboxWKT, bbox.WKT); HeightMap heightMap = _elevationService.GetHeightMap(bbox, DEMDataSet.SRTM_GL1); heightMap = heightMap.ReprojectGeodeticToCartesian().BakeCoordinates(); Assert.True(heightMap.BoundingBox == heightMap.Coordinates.GetBoundingBox()); heightMap = heightMap.ZScale(2.5f).BakeCoordinates(); Assert.True(heightMap.BoundingBox == heightMap.Coordinates.GetBoundingBox()); heightMap = heightMap.CenterOnOrigin().BakeCoordinates(); Assert.True(heightMap.BoundingBox == heightMap.Coordinates.GetBoundingBox()); heightMap = heightMap.FitInto(30f).BakeCoordinates(); Assert.True(heightMap.BoundingBox == heightMap.Coordinates.GetBoundingBox()); }
void buffer(string agsGeometryServerUrl, BufferParameters bufferParams, FindNearbyEventArgs findNearbyRequest) { if (string.IsNullOrEmpty(agsGeometryServerUrl)) { return; } GeometryService geomService = new GeometryService { Url = agsGeometryServerUrl }; geomService.BufferCompleted += GeometryService_BufferCompleted; geomService.Failed += (o, e) => { if (findNearbyToolWindow != null) { findNearbyToolWindow.StopBusyIndicator(); MapApplication.Current.HideWindow(findNearbyToolWindow); } MessageBoxDialog.Show(Resources.Strings.MsgErrorExecutingBufferOperation + Environment.NewLine + e.Error.ToString()); }; geomService.BufferAsync(bufferParams, findNearbyRequest); }
private void GeneralizeButton_Click(object sender, RoutedEventArgs e) { GeneralizeButton.IsEnabled = false; SliderStackPanel.Visibility = Visibility.Collapsed; GraphicsLayer originalGraphicsLayer = MyMap.Layers["OriginalLineGraphicsLayer"] as GraphicsLayer; GeometryService geometryService = new GeometryService("http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer"); geometryService.GeneralizeCompleted += GeometryService_GeneralizeCompleted; geometryService.Failed += GeometryService_Failed; GeneralizeParameters generalizeParameters = new GeneralizeParameters() { DeviationUnit = LinearUnit.SurveyMile, MaxDeviation = 0.000001 }; geometryService.GeneralizeAsync(new List <Graphic>() { originalGraphicsLayer.Graphics[0] }, generalizeParameters); }
void geoprocessorTask_GetResultDataCompleted(object sender, GPParameterEventArgs gpParameterEventArgs) { // Get the result features from the parameter GPFeatureRecordSetLayer gpLayer; gpLayer = gpParameterEventArgs.Parameter as GPFeatureRecordSetLayer; // Check the parameter name, reproject and add to the appropriate graphics layer. // again - two separate tasks are created allowing them to run conncurrently. switch (gpParameterEventArgs.Parameter.Name) { case "Sysvalves_Layer": GeometryService valvesProjectTask = new GeometryService(localGeometryService.UrlGeometryService); valvesProjectTask.ProjectCompleted += (sender2, graphicsEventArgs) => { valvesGraphicsLayer.Graphics.AddRange(graphicsEventArgs.Results); }; valvesProjectTask.ProjectAsync(gpLayer.FeatureSet.Features, new SpatialReference(3857)); break; case "DistribMains_Layer": GeometryService mainsProjectTask = new GeometryService(localGeometryService.UrlGeometryService); mainsProjectTask.ProjectCompleted += (sender2, graphicsEventArgs) => { mainsGraphicsLayer.Graphics.AddRange(graphicsEventArgs.Results); }; mainsProjectTask.ProjectAsync(gpLayer.FeatureSet.Features, new SpatialReference(3857)); break; } }
private void MyMap_MouseClick(object sender, ESRI.ArcGIS.Client.Map.MouseEventArgs e) { GraphicsLayer graphicsLayer = MyMap.Layers["MyGraphicsLayer"] as GraphicsLayer; graphicsLayer.Graphics.Clear(); e.MapPoint.SpatialReference = MyMap.SpatialReference; Graphic graphic = new ESRI.ArcGIS.Client.Graphic() { Geometry = e.MapPoint, Symbol = LayoutRoot.Resources["DefaultClickSymbol"] as ESRI.ArcGIS.Client.Symbols.Symbol }; graphic.SetZIndex(1); graphicsLayer.Graphics.Add(graphic); GeometryService geometryService = new GeometryService("http://serverapps101.esri.com/arcgis/rest/services/Geometry/GeometryServer"); geometryService.BufferCompleted += GeometryService_BufferCompleted; geometryService.Failed += GeometryService_Failed; // If buffer spatial reference is GCS and unit is linear, geometry service will do geodesic buffering BufferParameters bufferParams = new BufferParameters() { Unit = chkGeodesic.IsChecked.HasValue && chkGeodesic.IsChecked.Value ? LinearUnit.StatuteMile : (LinearUnit?)null, BufferSpatialReference = new SpatialReference(4326), OutSpatialReference = MyMap.SpatialReference }; bufferParams.Features.Add(graphic); bufferParams.Distances.Add(5); bufferParams.Geodesic = chkGeodesic.IsChecked == true ? true : false; geometryService.BufferAsync(bufferParams); }
public List <BeanPoint_internal> GetPointsTestsByBBox(string p_bbox, DEMDataSet dataset, int sridCible) { List <BeanPoint_internal> v_pointsToTest = new List <BeanPoint_internal>(); try { // fix issue #86 to work with opentopography files without proper DI injection RasterIndexServiceResolver rasterIndexServiceResolver = dataSourceType => { switch (dataSourceType) { case DEMDataSourceType.GDALVrt: return(new GDALVRTFileService(null, null)); default: throw new KeyNotFoundException(); // or maybe return null, up to you } }; RasterService v_rasterService = new RasterService(rasterIndexServiceResolver); ElevationService v_elevationService = new ElevationService(v_rasterService, null); BoundingBox v_bbox = GeometryService.GetBoundingBox(p_bbox); v_elevationService.DownloadMissingFiles(dataset, v_bbox); // HeightMap v_hMap; v_hMap = v_elevationService.GetHeightMap(ref v_bbox, dataset); v_hMap = v_hMap.ReprojectTo(4326, sridCible); v_pointsToTest = GetGeoPointsByHMap(v_hMap, sridCible); } catch (Exception) { throw; } return(v_pointsToTest); }
private void MyDrawObject_DrawComplete(object sender, DrawEventArgs args) { MyDrawObject.IsEnabled = false; resultsLayer.ClearGraphics(); Polyline polyline = args.Geometry as Polyline; polyline.SpatialReference = MyMap.SpatialReference; geometryService = new GeometryService("http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer"); geometryService.TrimExtendCompleted += GeometryService_TrimExtendCompleted; geometryService.Failed += GeometryService_Failed; List <Polyline> polylineList = new List <Polyline>(); foreach (Graphic g in polylineLayer.Graphics) { polylineList.Add(g.Geometry as Polyline); } geometryService.TrimExtendAsync(polylineList, polyline, CurveExtension.DefaultCurveExtension); }
private void handleGeographicResults(List<LocatorResultViewModel> results) { WebMercator mercator = new WebMercator(); MapPoint extentCenter = null; double extentHeight = _extentWidthInMapUnits / 3; if (results[0].Candidate.Location.SpatialReference.IsGeographic()) { foreach (LocatorResultViewModel result in results) { extentCenter = (MapPoint)mercator.FromGeographic(result.Candidate.Location); Envelope extentInMeters = extentCenter.ToEnvelope(_extentWidthInMapUnits, extentHeight); result.Extent = (Envelope)mercator.ToGeographic(extentInMeters); _results.Add(result); } // Refresh paged collection to update pagination PagedResults.Refresh(); IsSearching = false; // Reset busy state OnSearchCompleted(); // Raise completed event } else if (!string.IsNullOrEmpty(GeometryServiceUrl)) { GeometryService geomService = new GeometryService(GeometryServiceUrl); List<Graphic> graphicsToProject = new List<Graphic>(); foreach (LocatorResultViewModel result in results) graphicsToProject.Add(new Graphic() { Geometry = result.Candidate.Location }); EventHandler<GraphicsEventArgs> projectCompleted = null; EventHandler<TaskFailedEventArgs> projectFailed = null; projectCompleted = (o, e) => { geomService.ProjectCompleted -= projectCompleted; graphicsToProject.Clear(); foreach (Graphic g in e.Results) { extentCenter = (MapPoint)g.Geometry; Envelope extentInMeters = extentCenter.ToEnvelope(_extentWidthInMapUnits, extentHeight); graphicsToProject.Add(new Graphic() { Geometry = extentInMeters }); } projectCompleted = (s, a) => { geomService.ProjectCompleted -= projectCompleted; geomService.Failed -= projectFailed; for (int i = 0; i < a.Results.Count; i++) { LocatorResultViewModel result = results[i]; result.Extent = (Envelope)a.Results[i].Geometry; _results.Add(result); } // Refresh paged collection to update pagination PagedResults.Refresh(); IsSearching = false; // Reset busy state OnSearchCompleted(); // Raise completed event }; geomService.ProjectCompleted += projectCompleted; // Project extents into map spatial reference geomService.ProjectAsync(graphicsToProject, _map.SpatialReference); }; projectFailed = (o, e) => { geomService.ProjectCompleted -= projectCompleted; geomService.Failed -= projectFailed; // Refresh paged collection to update pagination PagedResults.Refresh(); IsSearching = false; // Reset busy state OnSearchCompleted(); // Raise completed event }; geomService.ProjectCompleted += projectCompleted; geomService.Failed += projectFailed; // Project result locations to web mercator geomService.ProjectAsync(graphicsToProject, new SpatialReference(3857)); } }
private void MarkerSymbols_QueryTask_ExecuteCompleted(object sender, QueryEventArgs e) { //Create centroid for all US States FeatureSet featureSet = e.FeatureSet; GraphicsLayer graphicsLayer = null; // layerDemo6.Layer as GraphicsLayer; if (featureSet != null && featureSet.Features.Count > 0) { foreach (Graphic feature in featureSet.Features) { ESRI.ArcGIS.Client.Geometry.Polygon polygon = feature.Geometry as ESRI.ArcGIS.Client.Geometry.Polygon; if (polygon == null) { return; } polygon.SpatialReference = new ESRI.ArcGIS.Client.Geometry.SpatialReference(4326); Graphic graphic; //Getting the center point of the polygon MBR: ESRI.ArcGIS.Client.Geometry.MapPoint featureCentroid = feature.Geometry.Extent.GetCenter(); bool pointInPolygon = featureCentroid.IsWithin(polygon); if (pointInPolygon) { graphic = new Graphic() { Geometry = featureCentroid, }; } else { graphic = new Graphic() { Geometry = polygon, Symbol = null }; } //Assigning attributes from the feature to the graphic: foreach (string key in feature.Attributes.Keys) { //for (int i = 0; i < pieChartMarkerSymbol.Fields.Count; i++) //{ // if (pieChartMarkerSymbol.Fields[i].FieldName == key) // graphic.Attributes.Add(key, feature.Attributes[key]); //} } graphicsLayer.Graphics.Add(graphic); //Using the geometry service to find a new centroid in the case the //calculated centroid is not inside of the polygon: if (!pointInPolygon) { GeometryService geometryService = new GeometryService("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer"); List <Graphic> graphicsList = new List <Graphic>(); graphicsList.Add(graphic); geometryService.LabelPointsCompleted += MarkerSymbols_GeometryService_LabelPointsCompleted; geometryService.LabelPointsAsync(graphicsList); } } } }
private void UnionButton_Click(object sender, RoutedEventArgs e) { UnionButton.IsEnabled = false; MyDrawObject.IsEnabled = false; GeometryService geometryService = new GeometryService("http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer"); geometryService.UnionCompleted += GeometryService_UnionCompleted; geometryService.Failed += GeometryService_Failed; geometryService.UnionAsync(selectedGraphics); }
public PlacesController() { _dataContext = new DataContext(); geometryService = new GeometryService(); placeQuery = new PlaceQuery(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString); }
private void Button_Load(object sender, System.Windows.RoutedEventArgs e) { try { FeatureSet featureSet = FeatureSet.FromJson(JsonTextBox.Text); GraphicsLayer graphicsLayerFromFeatureSet = new GraphicsLayer() { Graphics = new GraphicCollection(featureSet) }; if (!featureSet.SpatialReference.Equals(MyMap.SpatialReference)) { if (MyMap.SpatialReference.Equals(new SpatialReference(102100)) && featureSet.SpatialReference.Equals(new SpatialReference(4326))) foreach (Graphic g in graphicsLayerFromFeatureSet.Graphics) g.Geometry = _mercator.FromGeographic(g.Geometry); else if (MyMap.SpatialReference.Equals(new SpatialReference(4326)) && featureSet.SpatialReference.Equals(new SpatialReference(102100))) foreach (Graphic g in graphicsLayerFromFeatureSet.Graphics) g.Geometry = _mercator.ToGeographic(g.Geometry); else { GeometryService geometryService = new GeometryService("http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer"); geometryService.ProjectCompleted += (s, a) => { for (int i = 0; i < a.Results.Count; i++) graphicsLayerFromFeatureSet.Graphics[i].Geometry = a.Results[i].Geometry; }; geometryService.Failed += (s, a) => { MessageBox.Show("Projection error: " + a.Error.Message); }; geometryService.ProjectAsync(graphicsLayerFromFeatureSet.Graphics, MyMap.SpatialReference); } } SimpleRenderer simpleRenderer = new SimpleRenderer(); SolidColorBrush symbolColor = new SolidColorBrush(Colors.Blue); graphicsLayerFromFeatureSet.Renderer = simpleRenderer; if (featureSet.GeometryType == GeometryType.Polygon || featureSet.GeometryType == GeometryType.Polygon) { simpleRenderer.Symbol = new SimpleFillSymbol() { Fill = symbolColor }; } else if (featureSet.GeometryType == GeometryType.Polyline) { simpleRenderer.Symbol = new SimpleLineSymbol() { Color = symbolColor }; } else // Point { simpleRenderer.Symbol = new SimpleMarkerSymbol() { Color = symbolColor, Size = 12 }; } Border border = new Border() { Background = new SolidColorBrush(Colors.White), BorderBrush = new SolidColorBrush(Colors.Black), BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(10), Effect = new DropShadowEffect() }; StackPanel stackPanelParent = new StackPanel() { Orientation = Orientation.Vertical, Margin = new Thickness(12) }; foreach (KeyValuePair<string, string> keyvalue in featureSet.FieldAliases) { StackPanel stackPanelChild = new StackPanel() { Orientation = Orientation.Horizontal, Margin = new Thickness(0, 0, 0, 6) }; TextBlock textValue = new TextBlock() { Text = keyvalue.Value + ": " }; TextBlock textKey = new TextBlock(); Binding keyBinding = new Binding(string.Format("[{0}]", keyvalue.Key)); textKey.SetBinding(TextBlock.TextProperty, keyBinding); stackPanelChild.Children.Add(textValue); stackPanelChild.Children.Add(textKey); if (keyvalue.Key == featureSet.DisplayFieldName) { textKey.FontWeight = textValue.FontWeight = FontWeights.Bold; stackPanelParent.Children.Insert(0, stackPanelChild); } else stackPanelParent.Children.Add(stackPanelChild); } border.Child = stackPanelParent; graphicsLayerFromFeatureSet.MapTip = border; MyMap.Layers.Add(graphicsLayerFromFeatureSet); } catch (Exception ex) { MessageBox.Show(ex.Message, "GraphicsLayer creation failed", MessageBoxButton.OK); } }
protected async override void OnAttached() { try { base.OnAttached(); // Verify that the behavior is attached to a map with a valid WKID and that a // query string is present if (AssociatedObject != null && AssociatedObject.SpatialReference != null && AssociatedObject.SpatialReference.WKID > 0 && HtmlPage.Document != null && HtmlPage.Document.QueryString != null) { // Put query string values in a case-insensitive dictionary var queryString = new Dictionary <string, string>(HtmlPage.Document.QueryString, StringComparer.InvariantCultureIgnoreCase); // Check whether query string contains center if (queryString.ContainsKey("center")) { // get the center string string centerString = queryString["center"]; // get the list delimiter for the current culture (making sure to account for cultures that use delimiters other than comma) char listDelimiter = CultureInfo.CurrentCulture.TextInfo.ListSeparator[0]; // Split extent string into discrete values string[] centerPointVals = centerString.Split(listDelimiter); double x, y; // Verify that the expected number of values are present, that they are numeric, and convert the values to doubles IFormatProvider numericFormat = CultureInfo.CurrentCulture.NumberFormat; if ((centerPointVals.Length == 2 || centerPointVals.Length == 3) && double.TryParse(centerPointVals[0], NumberStyles.Number, numericFormat, out x) && double.TryParse(centerPointVals[1], NumberStyles.Number, numericFormat, out y)) { // get WKID from the map attached to the behavior int currentWkid = AssociatedObject.Extent.SpatialReference.WKID; int queryStringWkid = currentWkid; // Check whether a WKID was specified (will be the 3rd parameter if present) and grab it if so if (centerPointVals.Length == 3 && !int.TryParse(centerPointVals[2], out queryStringWkid)) { // invalid WKID specified, fire InitializationFailed and exit OnInitializationFailed(new Exception(Strings.InvalidWkid)); return; } // Initialize a point with the same spatial reference as the attached map MapPoint queryStringPoint = new MapPoint(x, y) { SpatialReference = new SpatialReference(queryStringWkid) }; // check whether the specified WKID is different than that of the attached map, meaning the point needs to be projected if (queryStringWkid != currentWkid) { WebMercator wm = new WebMercator(); // Use convenience methods to convert between WGS 84 and Web Mercator if possible if (isWebMercator(queryStringWkid) && isWgs84(currentWkid)) { queryStringPoint = (MapPoint)wm.ToGeographic(queryStringPoint); } else if (isWgs84(queryStringWkid) && isWgs84(currentWkid)) { queryStringPoint = (MapPoint)wm.FromGeographic(queryStringPoint); } else if (!string.IsNullOrEmpty(MapApplication.Current.Urls.GeometryServiceUrl)) { // Conversion is not between WGS 84 and Web Mercator, so a call to a geometry service is necessary to perform // the projection try { GeometryService gs = new GeometryService(MapApplication.Current.Urls.GeometryServiceUrl); var g = new Graphic() { Geometry = queryStringPoint }; var sr = new SpatialReference(currentWkid); var result = await gs.ProjectTaskAsync(new Graphic[] { g }, sr); queryStringPoint = (MapPoint)result.Results[0].Geometry; } catch (Exception ex) { // Projection failed. Fire InitializationFailed event and return. OnInitializationFailed(ex); return; } } } var panDuration = AssociatedObject.PanDuration; AssociatedObject.PanDuration = TimeSpan.FromSeconds(0); AssociatedObject.PanTo(queryStringPoint); AssociatedObject.PanDuration = panDuration; } } } // Fire Initialized event OnInitialized(); } catch (Exception ex) { // Raise InitializationFailed event OnInitializationFailed(ex); } }
private void Button_Load(object sender, System.Windows.RoutedEventArgs e) { try { FeatureSet featureSet = FeatureSet.FromJson(JsonTextBox.Text); GraphicsLayer graphicsLayerFromFeatureSet = new GraphicsLayer() { Graphics = new GraphicCollection(featureSet) }; if (!featureSet.SpatialReference.Equals(MyMap.SpatialReference)) { if (MyMap.SpatialReference.Equals(new SpatialReference(102100)) && featureSet.SpatialReference.Equals(new SpatialReference(4326))) { foreach (Graphic g in graphicsLayerFromFeatureSet.Graphics) { g.Geometry = _mercator.FromGeographic(g.Geometry); } } else if (MyMap.SpatialReference.Equals(new SpatialReference(4326)) && featureSet.SpatialReference.Equals(new SpatialReference(102100))) { foreach (Graphic g in graphicsLayerFromFeatureSet.Graphics) { g.Geometry = _mercator.ToGeographic(g.Geometry); } } else { GeometryService geometryService = new GeometryService("http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer"); geometryService.ProjectCompleted += (s, a) => { for (int i = 0; i < a.Results.Count; i++) { graphicsLayerFromFeatureSet.Graphics[i].Geometry = a.Results[i].Geometry; } }; geometryService.Failed += (s, a) => { MessageBox.Show("Projection error: " + a.Error.Message); }; geometryService.ProjectAsync(graphicsLayerFromFeatureSet.Graphics, MyMap.SpatialReference); } } SimpleRenderer simpleRenderer = new SimpleRenderer(); SolidColorBrush symbolColor = new SolidColorBrush(Colors.Blue); graphicsLayerFromFeatureSet.Renderer = simpleRenderer; if (featureSet.GeometryType == GeometryType.Polygon || featureSet.GeometryType == GeometryType.Polygon) { simpleRenderer.Symbol = new SimpleFillSymbol() { Fill = symbolColor }; } else if (featureSet.GeometryType == GeometryType.Polyline) { simpleRenderer.Symbol = new SimpleLineSymbol() { Color = symbolColor }; } else // Point { simpleRenderer.Symbol = new SimpleMarkerSymbol() { Color = symbolColor, Size = 12 }; } myInfoWindow = new InfoWindow() { Background = new SolidColorBrush(Colors.Black), BorderBrush = new SolidColorBrush(Colors.White), BorderThickness = new Thickness(1), CornerRadius = 10, Map = MyMap, }; myInfoWindow.MouseLeftButtonDown += myInfoWindow_MouseLeftButtonDown; StackPanel stackPanelParent = new StackPanel() { Orientation = System.Windows.Controls.Orientation.Vertical, Margin = new Thickness(12) }; foreach (KeyValuePair <string, string> keyvalue in featureSet.FieldAliases) { StackPanel stackPanelChild = new StackPanel() { Orientation = System.Windows.Controls.Orientation.Horizontal, Margin = new Thickness(0, 0, 0, 6) }; TextBlock textValue = new TextBlock() { Text = keyvalue.Value + ": " }; TextBlock textKey = new TextBlock(); Binding keyBinding = new Binding(string.Format("[{0}]", keyvalue.Key)); textKey.SetBinding(TextBlock.TextProperty, keyBinding); stackPanelChild.Children.Add(textValue); stackPanelChild.Children.Add(textKey); if (keyvalue.Key == featureSet.DisplayFieldName) { textKey.FontWeight = textValue.FontWeight = FontWeights.Bold; stackPanelParent.Children.Insert(0, stackPanelChild); } else { stackPanelParent.Children.Add(stackPanelChild); } } myInfoWindow.Content = stackPanelParent; ContentPanel.Children.Add(myInfoWindow); MyMap.Layers.Add(graphicsLayerFromFeatureSet); graphicsLayerFromFeatureSet.MouseLeftButtonDown += graphicsLayerFromFeatureSet_MouseLeftButtonDown; JsonPivot.Visibility = Visibility.Collapsed; } catch (Exception ex) { MessageBox.Show(ex.Message, "GraphicsLayer creation failed", MessageBoxButton.OK); } }
void locatorTask_AddressToLocationsCompleted(object sender, AddressToLocationsEventArgs e) { try { List <AddressCandidate> returnedCandidates = e.Results; int BuildingEvacDistance = 0; int OutdoorEvacDistance = 0; if (bombType.Text == "Pipe bomb") { BuildingEvacDistance = 70; OutdoorEvacDistance = 1200; } else if (bombType.Text == "Suicide vest") { BuildingEvacDistance = 110; OutdoorEvacDistance = 1750; } else if (bombType.Text == "Briefcase/suitcase bomb") { BuildingEvacDistance = 150; OutdoorEvacDistance = 1850; } else if (bombType.Text == "Sedan") { BuildingEvacDistance = 320; OutdoorEvacDistance = 1900; } else if (bombType.Text == "SUV/van") { BuildingEvacDistance = 400; OutdoorEvacDistance = 2400; } else if (bombType.Text == "Small delivery truck") { BuildingEvacDistance = 640; OutdoorEvacDistance = 3800; } else if (bombType.Text == "Container/water truck") { BuildingEvacDistance = 860; OutdoorEvacDistance = 5100; } else if (bombType.Text == "Semi-trailer") { BuildingEvacDistance = 1570; OutdoorEvacDistance = 9300; } if (BuildingEvacDistance == 0 || OutdoorEvacDistance == 0) { return; } if (e.Results.Count > 0) { AddressCandidate candidate = returnedCandidates[0]; ResourceDictionary mydictionary = new ResourceDictionary(); mydictionary.Source = new Uri("/BombThreatAddin;component/SymbolDictionary.xaml", UriKind.RelativeOrAbsolute); Graphic graphic = new ESRI.ArcGIS.Client.Graphic(); graphic.Geometry = candidate.Location; graphic.Symbol = mydictionary["DefaultClickSymbol"] as client.Symbols.MarkerSymbol; location = candidate.Location; graphic.SetZIndex(1); if (_graphicsLayer == null) { _graphicsLayer = new ESRI.ArcGIS.Client.GraphicsLayer(); _graphicsLayer.ID = "BombThreatGraphics"; client.AcceleratedDisplayLayers aclyrs = _mapWidget.Map.Layers.FirstOrDefault(lyr => lyr is client.AcceleratedDisplayLayers) as client.AcceleratedDisplayLayers; if (aclyrs.Count() > 0) { aclyrs.ChildLayers.Add(_graphicsLayer); } } _graphicsLayer.Graphics.Add(graphic); GeometryService geometryTask = new GeometryService(); geometryTask.Url = "http://sampleserver6.arcgisonline.com/arcgis/rest/services/Utilities/Geometry/GeometryServer"; geometryTask.BufferCompleted += GeometryService_BufferCompleted; geometryTask.Failed += GeometryService_Failed; // If buffer spatial reference is GCS and unit is linear, geometry service will do geodesic buffering BufferParameters bufferParams = new BufferParameters() { Unit = LinearUnit.SurveyFoot, BufferSpatialReference = new SpatialReference(102004), OutSpatialReference = _mapWidget.Map.SpatialReference }; bufferParams.Features.Add(graphic); double[] theDistances = new double[] { BuildingEvacDistance, OutdoorEvacDistance }; bufferParams.Distances.AddRange(theDistances); geometryTask.BufferAsync(bufferParams); } else { MessageBox.Show("No address found. Example schema: 380 New York Ave., Redlands, CA or click on the map"); } } catch (Exception ex) { MessageBox.Show("Error in Address location complete: " + ex.Message); } }
void buffer(string agsGeometryServerUrl, BufferParameters bufferParams, FindNearbyEventArgs findNearbyRequest) { if (string.IsNullOrEmpty(agsGeometryServerUrl)) return; GeometryService geomService = new GeometryService { Url = agsGeometryServerUrl }; geomService.BufferCompleted += GeometryService_BufferCompleted; geomService.Failed += (o, e) => { if (findNearbyToolWindow != null) { findNearbyToolWindow.StopBusyIndicator(); MapApplication.Current.HideWindow(findNearbyToolWindow); } MessageBoxDialog.Show(Resources.Strings.MsgErrorExecutingBufferOperation + Environment.NewLine + e.Error.ToString()); }; geomService.BufferAsync(bufferParams, findNearbyRequest); }
public StatisticsRenderOnMap() { InitializeComponent(); subRegionGraphicsLayer = MyMap.Layers["SumGraphicsLayer"] as GraphicsLayer; // Generate a unique value renderer on the server GenerateRendererTask generateRendererTask = new GenerateRendererTask(); generateRendererTask.Url = _layerUrl; generateRendererTask.ExecuteCompleted += (o, e) => { subRegionGraphicsLayer.Renderer = e.GenerateRendererResult.Renderer; }; UniqueValueDefinition uniqueValueDefinition = new UniqueValueDefinition() { Fields = new List<string>() { "SUB_REGION" } }; uniqueValueDefinition.ColorRamps.Add(new ColorRamp() { From = Colors.Purple, To = Colors.Yellow, Algorithm = Algorithm.LabLChAlgorithm }); GenerateRendererParameters rendererParams = new GenerateRendererParameters() { ClassificationDefinition = uniqueValueDefinition, }; generateRendererTask.ExecuteAsync(rendererParams); // When layers initialized, return all states, generate statistics for a group, // union graphics based on grouped statistics MyMap.Layers.LayersInitialized += (a, b) => { QueryTask queryTask1 = new QueryTask(_layerUrl); Query queryAllStates = new Query() { ReturnGeometry = true, OutSpatialReference = MyMap.SpatialReference, Where = "1=1" }; queryAllStates.OutFields.Add("SUB_REGION"); queryTask1.ExecuteCompleted += (c, d) => { // Return statistics for states layer. Population and total count of states grouped by sub-region. QueryTask queryTask2 = new QueryTask(_layerUrl); Query query = new Query() { GroupByFieldsForStatistics = new List<string> { "SUB_REGION" }, OutStatistics = new List<OutStatistic> { new OutStatistic(){ OnStatisticField = "POP2000", OutStatisticFieldName = "SubRegionPopulation", StatisticType = StatisticType.Sum }, new OutStatistic(){ OnStatisticField = "SUB_REGION", OutStatisticFieldName = "NumberOfStates", StatisticType = StatisticType.Count } } }; queryTask2.ExecuteCompleted += (e, f) => { // foreach group (sub-region) returned from statistic results foreach (Graphic regionGraphic in f.FeatureSet.Features) { // Collection of graphics based on sub-region IEnumerable<Graphic> toUnion = (f.UserState as FeatureSet).Features.Where(stateGraphic => (string)stateGraphic.Attributes["SUB_REGION"] == (string)regionGraphic.Attributes["SUB_REGION"]); // Union graphics based on sub-region, add to graphics layer GeometryService geometryService = new GeometryService("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Utilities/Geometry/GeometryServer"); geometryService.UnionCompleted += (g, h) => { Graphic unionedGraphic = h.UserState as Graphic; unionedGraphic.Geometry = h.Result; subRegionGraphicsLayer.Graphics.Add(unionedGraphic); }; geometryService.UnionAsync(toUnion.ToList(), regionGraphic); } // populate the ListBox FeatureSet featureSet = f.FeatureSet; if (featureSet != null && featureSet.Features.Count > 0) { OutStatisticsListBox.ItemsSource = featureSet.Features; } }; queryTask2.ExecuteAsync(query, d.FeatureSet); }; queryTask1.ExecuteAsync(queryAllStates); }; }
// Raised when the locator search completes private void AddressToLocationsCompleted(object sender, AddressToLocationsEventArgs args) { if (args.Results == null || args.Results.Count < 1) // No results found { IsSearching = false; // Reset busy state OnSearchCompleted(); // Raise completed event return; } // check that coordinates returned by extent fields are valid AddressCandidate result = args.Results[0]; double xMin, xMax, yMin, yMax; bool useExtentFields = UseExtentFields; if (UseExtentFields && getExtentFields(result, out xMin, out yMin, out xMax, out yMax)) { if (xMax <= xMin || yMax <= yMin) { // Extent fields are returning invalid coordinates. Disable use of extent fields. useExtentFields = false; } } // Check whether result extents will need to be reprojected using a geometry service SpatialReference locatorSRef = LocatorInfo.SpatialReference; bool needsGeometryServiceProjection = (useExtentFields && ((locatorSRef != null && !locatorSRef.IsWebMercator() && !locatorSRef.IsGeographic()) || (!_map.SpatialReference.IsWebMercator() && !_map.SpatialReference.IsGeographic()))) || (!useExtentFields && _mapUnits == LengthUnits.UnitsDecimalDegrees); List<Graphic> graphicsToProject = new List<Graphic>(); List<LocatorResultViewModel> geographicResults = new List<LocatorResultViewModel>(); foreach (AddressCandidate candidate in args.Results) { // Create the result ViewModel from the result returned from the service LocatorResultViewModel resultViewModel = new LocatorResultViewModel(candidate); // If extent fields are being used, initialize the extent on the service if (useExtentFields && getExtentFields(candidate, out xMin, out yMin, out xMax, out yMax)) { Envelope extent = new Envelope(xMin, yMin, xMax, yMax); if (LocatorInfo.SpatialReference != null) { extent.SpatialReference = locatorSRef; if (!needsGeometryServiceProjection) { // No geometry service needed, so set extent directly if (locatorSRef.IsWebMercator() && _map.SpatialReference.WKID == 4326) extent = (new WebMercator()).ToGeographic(extent) as Envelope; else if (locatorSRef.WKID == 4326 && _map.SpatialReference.IsWebMercator()) extent = (new WebMercator()).FromGeographic(extent) as Envelope; resultViewModel.Extent = extent; } else { // Since results need to be reprojected, add them to collection to be projected // once they've all been gone through graphicsToProject.Add(new Graphic() { Geometry = extent }); _queuedResults.Enqueue(resultViewModel); } } else { resultViewModel.Extent = extent; } } if (resultViewModel.Extent == null && !useExtentFields) { // Initialize the result extent based on the specified extent width if (_gotMapUnits) // check whether map units have been retrieved for the current search { if (!needsGeometryServiceProjection) { initializeResultExtent(resultViewModel); _results.Add(resultViewModel); } else if (_mapUnits != LengthUnits.UnitsDecimalDegrees) { initializeResultExtent(resultViewModel); graphicsToProject.Add(new Graphic() { Geometry = resultViewModel.Extent }); _queuedResults.Enqueue(resultViewModel); } else { // results in a geographic coordinate system (units of decimal degrees) require // special handling because an envelope around the result cannot be calculated // in the result's spatial reference. geographicResults.Add(resultViewModel); } } else { // map units are not yet known, so queue up the result to be added after map units are // determined. _queuedResults.Enqueue(resultViewModel); } } else if (!needsGeometryServiceProjection) { // No projection needed, so the result can be added now _results.Add(resultViewModel); } } if (!needsGeometryServiceProjection) // Check whether result extents need to be reprojected { // No projection needed, so the operation is complete. // Refresh paged collection to update pagination PagedResults.Refresh(); IsSearching = false; // Reset busy state OnSearchCompleted(); // Raise completed event } else if (graphicsToProject.Count > 0) { // result extents need to be reprojected if (_geometryService == null) { _geometryService = new GeometryService(GeometryServiceUrl); _geometryService.ProjectCompleted += GeometryService_ProjectCompleted; } _geometryService.ProjectAsync(graphicsToProject, _map.SpatialReference, _queuedResults); } else { // result extents need to be created in a spatial reference that uses linear units (i.e. // projected coordinate system), then projected back into the current spatial reference. handleGeographicResults(geographicResults); } }
public StatisticsRenderOnMap() { InitializeComponent(); subRegionGraphicsLayer = MyMap.Layers["SumGraphicsLayer"] as GraphicsLayer; // Generate a unique value renderer on the server GenerateRendererTask generateRendererTask = new GenerateRendererTask(); generateRendererTask.Url = _layerUrl; generateRendererTask.ExecuteCompleted += (o, e) => { subRegionGraphicsLayer.Renderer = e.GenerateRendererResult.Renderer; }; UniqueValueDefinition uniqueValueDefinition = new UniqueValueDefinition() { Fields = new List <string>() { "SUB_REGION" } }; uniqueValueDefinition.ColorRamps.Add(new ColorRamp() { From = Colors.Purple, To = Colors.Yellow, Algorithm = Algorithm.LabLChAlgorithm }); GenerateRendererParameters rendererParams = new GenerateRendererParameters() { ClassificationDefinition = uniqueValueDefinition, }; generateRendererTask.ExecuteAsync(rendererParams); // When layers initialized, return all states, generate statistics for a group, // union graphics based on grouped statistics MyMap.Layers.LayersInitialized += (a, b) => { QueryTask queryTask1 = new QueryTask(_layerUrl); Query queryAllStates = new Query() { ReturnGeometry = true, OutSpatialReference = MyMap.SpatialReference, Where = "1=1" }; queryAllStates.OutFields.Add("SUB_REGION"); queryTask1.ExecuteCompleted += (c, d) => { // Return statistics for states layer. Population and total count of states grouped by sub-region. QueryTask queryTask2 = new QueryTask(_layerUrl); Query query = new Query() { GroupByFieldsForStatistics = new List <string> { "SUB_REGION" }, OutStatistics = new List <OutStatistic> { new OutStatistic() { OnStatisticField = "POP2000", OutStatisticFieldName = "SubRegionPopulation", StatisticType = StatisticType.Sum }, new OutStatistic() { OnStatisticField = "SUB_REGION", OutStatisticFieldName = "NumberOfStates", StatisticType = StatisticType.Count } } }; queryTask2.ExecuteCompleted += (e, f) => { // foreach group (sub-region) returned from statistic results foreach (Graphic regionGraphic in f.FeatureSet.Features) { // Collection of graphics based on sub-region IEnumerable <Graphic> toUnion = (f.UserState as FeatureSet).Features.Where(stateGraphic => (string)stateGraphic.Attributes["SUB_REGION"] == (string)regionGraphic.Attributes["SUB_REGION"]); // Union graphics based on sub-region, add to graphics layer GeometryService geometryService = new GeometryService("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Utilities/Geometry/GeometryServer"); geometryService.UnionCompleted += (g, h) => { Graphic unionedGraphic = h.UserState as Graphic; unionedGraphic.Geometry = h.Result; subRegionGraphicsLayer.Graphics.Add(unionedGraphic); }; geometryService.UnionAsync(toUnion.ToList(), regionGraphic); } // populate the ListBox FeatureSet featureSet = f.FeatureSet; if (featureSet != null && featureSet.Features.Count > 0) { OutStatisticsListBox.ItemsSource = featureSet.Features; } }; queryTask2.ExecuteAsync(query, d.FeatureSet); }; queryTask1.ExecuteAsync(queryAllStates); }; }
// Raised when a property of the map changes. Used to check whether map units have changed. private void Map_PropertyChanged(object sender, PropertyChangedEventArgs e) { Map map = ((Map)sender); if (map.SpatialReference.WKID != _spatialRefWKID) { _gotMapUnits = false; _spatialRefWKID = map.SpatialReference.WKID; // Spatial reference has changed, so determine map units if (map.Layers.Count > 0) { map.GetMapUnitsAsync(OnGetMapUnitsCompleted, OnGetMapUnitsFailed); } else { NotifyCollectionChangedEventHandler collectionChanged = null; collectionChanged = (o, args) => { if (map.Layers.Count > 0) { map.Layers.CollectionChanged -= collectionChanged; map.GetMapUnitsAsync(OnGetMapUnitsCompleted, OnGetMapUnitsFailed); } }; map.Layers.CollectionChanged += collectionChanged; } // handle case where map's spatial reference has changed while there are results. Projection // of results will need to be changed to match that of the map. if (_results.Count > 0) { SpatialReference oldSRef = new SpatialReference(_spatialRefWKID); if (oldSRef.IsWebMercator() && map.SpatialReference.IsGeographic()) { // Transform result extents from Web Mercator to Geographic WGS 84 WebMercator mercator = new WebMercator(); foreach (LocatorResultViewModel result in _results) { result.Extent = (Envelope)mercator.ToGeographic(result.Extent); AddressCandidate oldCandidate = result.Candidate; MapPoint newLocation = (MapPoint)mercator.ToGeographic(result.Candidate.Location); result.Candidate = new AddressCandidate(oldCandidate.Address, newLocation, oldCandidate.Score, oldCandidate.Attributes); } } else if (oldSRef.IsGeographic() && map.SpatialReference.IsWebMercator()) { // Transform result exstents from Geographic WGS 84 to Web Mercator WebMercator mercator = new WebMercator(); foreach (LocatorResultViewModel result in _results) { result.Extent = (Envelope)mercator.FromGeographic(result.Extent); AddressCandidate oldCandidate = result.Candidate; MapPoint newLocation = (MapPoint)mercator.FromGeographic(result.Candidate.Location); result.Candidate = new AddressCandidate(oldCandidate.Address, newLocation, oldCandidate.Score, oldCandidate.Attributes); } } else if (!string.IsNullOrEmpty(GeometryServiceUrl)) { // Use a geometry service to project the result extents List<LocatorResultViewModel> resultsToProject = new List<LocatorResultViewModel>(); List<Graphic> extentsToProject = new List<Graphic>(); List<Graphic> locationsToProject = new List<Graphic>(); foreach (LocatorResultViewModel result in _results) { // Copy the results to a new collection (list) - necessary because the results // could change during the project operation, so maintaining these in a separate // collection ensures that the updated extents are applied to the proper results resultsToProject.Add(result); // Get the geometries to project. Both extent and candidate location must be re-projected. extentsToProject.Add(new Graphic() { Geometry = result.Extent }); locationsToProject.Add(new Graphic() { Geometry = result.Candidate.Location }); } GeometryService geomService = new GeometryService(GeometryServiceUrl); GeometryService geomService2 = new GeometryService(GeometryServiceUrl); EventHandler<GraphicsEventArgs> projectExtentsCompleted = null; EventHandler<GraphicsEventArgs> projectLocationsCompleted = null; EventHandler<TaskFailedEventArgs> projectFailed = null; // Update the result extents when the projection completes projectExtentsCompleted = (o, args) => { geomService.ProjectCompleted -= projectExtentsCompleted; geomService.Failed -= projectFailed; int count = args.Results.Count; for (int i = 0; i < count; i++) resultsToProject[i].Extent = (Envelope)args.Results[i].Geometry; }; // Update the result locations when the projection completes projectLocationsCompleted = (o, args) => { geomService2.ProjectCompleted -= projectLocationsCompleted; geomService2.Failed -= projectFailed; int count = args.Results.Count; LocatorResultViewModel result = null; for (int i = 0; i < count; i++) { result = resultsToProject[i]; AddressCandidate oldCandidate = result.Candidate; MapPoint newLocation = (MapPoint)args.Results[i].Geometry; result.Candidate = new AddressCandidate(oldCandidate.Address, newLocation, oldCandidate.Score, oldCandidate.Attributes); } }; // Just clear the results and remove handlers if the projection fails projectFailed = (o, args) => { geomService.ProjectCompleted -= projectExtentsCompleted; geomService.Failed -= projectFailed; geomService2.ProjectCompleted -= projectLocationsCompleted; geomService2.Failed -= projectFailed; _results.Clear(); }; geomService.ProjectCompleted += projectExtentsCompleted; geomService.Failed += projectFailed; geomService2.ProjectCompleted += projectLocationsCompleted; geomService2.Failed += projectFailed; geomService.ProjectAsync(extentsToProject, map.SpatialReference); geomService2.ProjectAsync(locationsToProject, map.SpatialReference); } } } }
void relationAsync(string agsGeometryServerUrl, IList<Graphic> graphics1, IList<Graphic> graphics2, object userToken) { GeometryService geomService = new GeometryService { Url = agsGeometryServerUrl }; geomService.RelationCompleted += geometryService_RelationCompleted; geomService.Failed += (o, e) => { MessageBoxDialog.Show(Resources.Strings.MsgErrorExecutingRelationAsyncOperation + Environment.NewLine + e.Error.ToString()); if (findNearbyToolWindow != null) { findNearbyToolWindow.StopBusyIndicator(); MapApplication.Current.HideWindow(findNearbyToolWindow); } }; geomService.RelationAsync(graphics1, graphics2, GeometryRelation.esriGeometryRelationIntersection, null, userToken); }
private void RunButton_Click_1(object sender, RoutedEventArgs e) { try { if (_graphicsLayer != null) { _graphicsLayer.Graphics.Clear(); } // Find the map layer in the map widget that contains the data source. IEnumerable <ESRI.ArcGIS.OperationsDashboard.DataSource> dataSources = OperationsDashboard.Instance.DataSources; foreach (ESRI.ArcGIS.OperationsDashboard.DataSource d in dataSources) { if (_mapWidget != null && d.IsSelectable == true) { // Get the feature layer in the map for the data source. client.FeatureLayer featureL = _mapWidget.FindFeatureLayer(d); //Clear Selection on Feature Layers in map featureL.ClearSelection(); } } if (txtAddress.Text == "Enter Address") { int BuildingEvacDistance = 0; int OutdoorEvacDistance = 0; if (bombType.Text == "Pipe bomb") { BuildingEvacDistance = 70; OutdoorEvacDistance = 1200; } else if (bombType.Text == "Suicide vest") { BuildingEvacDistance = 110; OutdoorEvacDistance = 1750; } else if (bombType.Text == "Briefcase/suitcase bomb") { BuildingEvacDistance = 150; OutdoorEvacDistance = 1850; } else if (bombType.Text == "Sedan") { BuildingEvacDistance = 320; OutdoorEvacDistance = 1900; } else if (bombType.Text == "SUV/van") { BuildingEvacDistance = 400; OutdoorEvacDistance = 2400; } else if (bombType.Text == "Small delivery truck") { BuildingEvacDistance = 640; OutdoorEvacDistance = 3800; } else if (bombType.Text == "Container/water truck") { BuildingEvacDistance = 860; OutdoorEvacDistance = 5100; } else if (bombType.Text == "Semi-trailer") { BuildingEvacDistance = 1570; OutdoorEvacDistance = 9300; } if (BuildingEvacDistance == 0 || OutdoorEvacDistance == 0) { return; } //e.MapPoint.SpatialReference = _mapWidget.Map.SpatialReference; //location = e.MapPoint; if (location == null) { return; } Graphic graphic = new ESRI.ArcGIS.Client.Graphic(); graphic.Geometry = location; GeometryService geometryTask = new GeometryService(); geometryTask.Url = _serviceURL; geometryTask.BufferCompleted += GeometryService_BufferCompleted; geometryTask.Failed += GeometryService_Failed; // If buffer spatial reference is GCS and unit is linear, geometry service will do geodesic buffering BufferParameters bufferParams = new BufferParameters() { Unit = LinearUnit.SurveyFoot, BufferSpatialReference = new SpatialReference(102004), OutSpatialReference = _mapWidget.Map.SpatialReference }; bufferParams.Features.Add(graphic); double[] theDistances = new double[] { BuildingEvacDistance, OutdoorEvacDistance }; bufferParams.Distances.AddRange(theDistances); geometryTask.BufferAsync(bufferParams); } else { findAddress(); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("error in run: " + ex.Message); } }