// Calculates a geometric difference between features and user defined geometry private async void DifferenceButton_Click(object sender, RoutedEventArgs e) { try { _differenceGraphics.Graphics.Clear(); // wait for user to draw difference polygon var poly = await mapView.Editor.RequestShapeAsync(DrawShape.Polygon); // Adjust user polygon for backward digitization poly = GeometryEngine.Simplify(poly); // get intersecting features from the feature layer SpatialQueryFilter filter = new SpatialQueryFilter(); filter.Geometry = GeometryEngine.Project(poly, _statesLayer.FeatureTable.SpatialReference); filter.SpatialRelationship = SpatialRelationship.Intersects; filter.MaximumRows = 52; var stateFeatures = await _statesLayer.FeatureTable.QueryAsync(filter); // Calc difference between feature geometries and user polygon and add results to graphics layer var states = stateFeatures.Select(feature => feature.Geometry); var diffGraphics = states .Select(state => ((bool)useSymmetricDifference.IsChecked) ? GeometryEngine.SymmetricDifference(state, poly) : GeometryEngine.Difference(state, poly)) .Select(geo => new Graphic(geo, _fillSymbol)); _differenceGraphics.Graphics.AddRange(diffGraphics); } catch (Exception ex) { var _ = new MessageDialog("Difference Error: " + ex.Message, "Sample Error").ShowAsync(); } }
// Cuts feature geometries with a user defined cut polyline. private async void CutButton_Click(object sender, RoutedEventArgs e) { try { resultGraphics.Graphics.Clear(); // wait for user to draw cut line var cutLine = await mapView.Editor.RequestShapeAsync(DrawShape.Polyline, _cutLineSymbol) as Polyline; // get intersecting features from the feature layer SpatialQueryFilter filter = new SpatialQueryFilter(); filter.Geometry = GeometryEngine.Project(cutLine, _statesLayer.FeatureTable.SpatialReference); filter.SpatialRelationship = SpatialRelationship.Crosses; filter.MaximumRows = 52; var stateFeatures = await _statesLayer.FeatureTable.QueryAsync(filter); // Cut the feature geometries and add to graphics layer var states = stateFeatures.Select(feature => feature.Geometry); var cutGraphics = states .Where(geo => !GeometryEngine.Within(cutLine, geo)) .SelectMany(state => GeometryEngine.Cut(state, cutLine)) .Select(geo => new Graphic(geo, _cutFillSymbol)); resultGraphics.Graphics.AddRange(cutGraphics); } catch (TaskCanceledException) { } catch (Exception ex) { MessageBox.Show("Cut Error: " + ex.Message, "Cut Geometry"); } }
// Cuts feature geometries with a user defined cut polyline. private async void CutButton_Click(object sender, RoutedEventArgs e) { try { _resultGraphicsOverlay.Graphics.Clear(); // wait for user to draw cut line var cutLine = await MyMapView.Editor.RequestShapeAsync(DrawShape.Polyline, _cutLineSymbol) as Polyline; Polyline polyline = GeometryEngine.NormalizeCentralMeridian(cutLine) as Polyline; // get intersecting features from the feature layer SpatialQueryFilter filter = new SpatialQueryFilter(); filter.Geometry = GeometryEngine.Project(polyline, _statesLayer.FeatureTable.SpatialReference); filter.SpatialRelationship = SpatialRelationship.Crosses; filter.MaximumRows = 52; var stateFeatures = await _statesLayer.FeatureTable.QueryAsync(filter); // Cut the feature geometries and add to graphics layer var states = stateFeatures.Select(feature => feature.Geometry); var cutGraphics = states .Where(geo => !GeometryEngine.Within(polyline, geo)) .SelectMany(state => GeometryEngine.Cut(state, polyline)) .Select(geo => new Graphic(geo, _cutFillSymbol)); _resultGraphicsOverlay.Graphics.AddRange(cutGraphics); } catch (TaskCanceledException) { } catch (Exception ex) { var _x = new MessageDialog("Cut Error: " + ex.Message, "Sample Error").ShowAsync(); } }
private async void QueryOffline(FrameworkElement mapTipContainer, Geometry searchArea) { var featureLayer = this.MyMapView.Map.Layers["POI"] as FeatureLayer; if (featureLayer == null) { return; } var featureTable = featureLayer.FeatureTable as GeodatabaseFeatureTable; if (featureTable == null) { return; } var filter = new SpatialQueryFilter(); filter.Geometry = searchArea; var features = await featureTable.QueryAsync(filter); if (features.Count() == 0) { return; } mapTipContainer.DataContext = features.FirstOrDefault(); mapTipContainer.Visibility = System.Windows.Visibility.Visible; }
// Unions feature geometries with a user defined polygon. private async void UnionButton_Click(object sender, RoutedEventArgs e) { try { _resultGraphics.Graphics.Clear(); // wait for user to draw a polygon var poly = await mapView.Editor.RequestShapeAsync(DrawShape.Polygon); // get intersecting features from the feature layer SpatialQueryFilter filter = new SpatialQueryFilter(); filter.Geometry = GeometryEngine.Project(poly, _statesLayer.FeatureTable.SpatialReference); filter.SpatialRelationship = SpatialRelationship.Intersects; filter.MaximumRows = 52; var stateFeatures = await _statesLayer.FeatureTable.QueryAsync(filter); // Union the geometries and add to graphics layer var states = stateFeatures.Select(feature => feature.Geometry); var unionPolys = states.ToList(); unionPolys.Add(poly); var unionPoly = GeometryEngine.Union(unionPolys); var unionGraphic = new Graphic(unionPoly, _fillSymbol); _resultGraphics.Graphics.Add(unionGraphic); } catch (Exception ex) { var _ = new MessageDialog("Union Error: " + ex.Message, "Sample Error").ShowAsync(); } }
protected override Task <bool> OnSketchCompleteAsync(Geometry geometry) { List <long> oids = new List <long>(); var vm = OverlayEmbeddableControl as EmbeddedControlViewModel; POINT pt; GetCursorPos(out pt); _clickedPoint = new Point(pt.X, pt.Y); //Point on screen to show the context menu return(QueuedTask.Run(() => { SpatialQueryFilter spatialQueryFilter = new SpatialQueryFilter { FilterGeometry = geometry, SpatialRelationship = SpatialRelationship.Intersects, }; var selection = vm?.SelectedLayer.Select(spatialQueryFilter); if (selection == null) { return false; } oids.AddRange(selection.GetObjectIDs()); lock (LockSelection) { Selection.Add(vm?.SelectedLayer, oids); } Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => ShowContextMenu())); return true; })); }
protected override bool CanUseSelection(IEnumerable <Feature> selectedFeatures) { var found = false; if (WorkListLayer == null) { return(false); } //check if a selected feature is part of the worklist layer foreach (Feature selectedFeature in selectedFeatures) { var filter = new SpatialQueryFilter(); filter.FilterGeometry = selectedFeature.GetShape(); filter.SpatialRelationship = SpatialRelationship.Intersects; using (RowCursor cursor = WorkListLayer.Search(filter)) { while (cursor.MoveNext()) { var feature = cursor.Current as Feature; //if selected feature is a feature of the worklist layer if (feature.GetShape().ToJson() == selectedFeature.GetShape().ToJson()) { found = true; } } } } return(found); }
/// <summary> /// 選択範囲内にある物件フィーチャを選択 /// </summary> /// <param name="g">選択範囲を示すグラフィック</param> private async Task SelectFeatureWithIn(Graphic g) { //空間検索用のフィルタを作成 SpatialQueryFilter spatialQueryFilter = new SpatialQueryFilter() { Geometry = g.Geometry, SpatialRelationship = SpatialRelationship.Within, }; try { //物件レイヤのフィーチャテーブルに対して空間検索を実行 ServiceFeatureTable serviceFeatureTable = buildingLayer.FeatureTable as ServiceFeatureTable; IEnumerable <Feature> features = await serviceFeatureTable.QueryAsync(spatialQueryFilter); //空間検索結果のフィーチャを選択フィーチャコレクションに追加 foreach (Feature f in features) { selectedFeatures.Add(f); } //物件リストボックスの選択変更時のイベントハンドラを設定 selectedBuildingListBox.SelectionChanged += selectedBuildingListBox_SelectionChanged; } //エラーが発生した場合の処理 catch (Exception ex) { MessageBox.Show(string.Format("空間検索:{0}", ex.Message)); } }
/// <summary> /// Occurs once the user completed the sketch and select the information for the /// embeddable control /// </summary> /// <param name="geometry">Sketch geometry in map coordinates.</param> /// <returns></returns> protected override Task <bool> OnSketchCompleteAsync(Geometry geometry) { // select the first point feature layer in the active map var pointLayer = ActiveMapView.Map.GetLayersAsFlattenedList().OfType <FeatureLayer>(). Where(lyr => lyr.ShapeType == ArcGIS.Core.CIM.esriGeometryType.esriGeometryPoint).FirstOrDefault(); if (pointLayer == null) { return(Task.FromResult(true)); } // execute the select on the MCT QueuedTask.Run(() => { // define the spatial query filter var spatialQuery = new SpatialQueryFilter() { FilterGeometry = geometry, SpatialRelationship = SpatialRelationship.Contains }; // gather the selection var pointSelection = pointLayer.Select(spatialQuery); // set up a dictionary to store the layer and the object IDs of the selected features var selectionDictionary = new Dictionary <MapMember, List <long> >(); selectionDictionary.Add(pointLayer as MapMember, pointSelection.GetObjectIDs().ToList()); // assign the dictionary to the view model _attributeVM.SelectedMapFeatures = selectionDictionary; // load the first feature into the attribute inspector _attributeVM.AttributeInspector.Load(pointLayer, pointSelection.GetObjectIDs().First()); }); return(Task.FromResult(true)); }
// Clips feature geometries with a user defined clipping rectangle. private async void ClipButton_Click(object sender, RoutedEventArgs e) { try { _clippedGraphicsOverlay.Graphics.Clear(); // wait for user to draw clip rect var rect = await MyMapView.Editor.RequestShapeAsync(DrawShape.Rectangle); Polygon polygon = GeometryEngine.NormalizeCentralMeridian(rect) as Polygon; // get intersecting features from the feature layer SpatialQueryFilter filter = new SpatialQueryFilter(); filter.Geometry = GeometryEngine.Project(polygon, _statesLayer.FeatureTable.SpatialReference); filter.SpatialRelationship = SpatialRelationship.Intersects; filter.MaximumRows = 52; var stateFeatures = await _statesLayer.FeatureTable.QueryAsync(filter); // Clip the feature geometries and add to graphics layer var states = stateFeatures.Select(feature => feature.Geometry); var clipGraphics = states .Select(state => GeometryEngine.Clip(state, polygon.Extent)) .Select(geo => new Graphic(geo, _clipSymbol)); _clippedGraphicsOverlay.Graphics.AddRange(clipGraphics); } catch (TaskCanceledException) { } catch (Exception ex) { var _x = new MessageDialog("Clip Error: " + ex.Message, "Clip Geometry").ShowAsync(); } }
// Intersects feature geometries with a user defined polygon. private async void IntersectButton_Click(object sender, RoutedEventArgs e) { try { _resultGraphics.Graphics.Clear(); // wait for user to draw a polygon Polygon userpoly = await MyMapView.Editor.RequestShapeAsync(DrawShape.Polygon) as Polygon; Polygon poly = GeometryEngine.NormalizeCentralMeridian(userpoly) as Polygon; // get intersecting features from the feature layer SpatialQueryFilter filter = new SpatialQueryFilter(); filter.Geometry = GeometryEngine.Project(poly, _statesLayer.FeatureTable.SpatialReference); filter.SpatialRelationship = SpatialRelationship.Intersects; filter.MaximumRows = 52; var stateFeatures = await _statesLayer.FeatureTable.QueryAsync(filter); // Intersect the feature geometries and add to graphics layer var states = stateFeatures.Select(feature => feature.Geometry); var intersectGraphics = states .Select(state => GeometryEngine.Intersection(state, poly)) .Select(geo => new Graphic(geo, _fillSymbol)); _resultGraphics.Graphics.AddRange(intersectGraphics); } catch (Exception ex) { var _x = new MessageDialog("Intersection Error: " + ex.Message, "Sample Error").ShowAsync(); } }
// Unions feature geometries with a user defined polygon. private async void UnionButton_Click(object sender, RoutedEventArgs e) { try { resultGraphics.Graphics.Clear(); // wait for user to draw a polygon var poly = await mapView.Editor.RequestShapeAsync(DrawShape.Polygon); // get intersecting features from the feature layer SpatialQueryFilter filter = new SpatialQueryFilter(); filter.Geometry = GeometryEngine.Project(poly, _statesLayer.FeatureTable.SpatialReference); filter.SpatialRelationship = SpatialRelationship.Intersects; filter.MaximumRows = 52; var stateFeatures = await _statesLayer.FeatureTable.QueryAsync(filter); // Union the feature geometries and add to graphics layer var states = stateFeatures.Select(feature => feature.Geometry); var sourcePolys = states.ToList(); var unionPoly = GeometryEngine.Union(sourcePolys); var unionGraphic = new Graphic(unionPoly, _fillSymbol); resultGraphics.Graphics.Add(unionGraphic); } catch (Exception ex) { MessageBox.Show("Union Error: " + ex.Message, "Union Sample"); } }
// Unions feature geometries with a user defined polygon. private async void UnionButton_Click(object sender, RoutedEventArgs e) { try { _resultGraphics.Graphics.Clear(); // wait for user to draw a polygon var poly = await MyMapView.Editor.RequestShapeAsync(DrawShape.Polygon); // Take account of WrapAround var normalizedPoly = GeometryEngine.NormalizeCentralMeridian(poly) as Polygon; // get intersecting features from the feature layer SpatialQueryFilter filter = new SpatialQueryFilter(); filter.Geometry = GeometryEngine.Project(normalizedPoly, _statesLayer.FeatureTable.SpatialReference); filter.SpatialRelationship = SpatialRelationship.Intersects; filter.MaximumRows = 52; var stateFeatures = await _statesLayer.FeatureTable.QueryAsync(filter); // Union the geometries and add to graphics layer var states = stateFeatures.Select(feature => feature.Geometry); var unionPolys = states.ToList(); var unionPoly = GeometryEngine.Union(unionPolys); var unionGraphic = new Graphic(unionPoly, _fillSymbol); _resultGraphics.Graphics.Add(unionGraphic); } catch (Exception ex) { var _x = new MessageDialog("Union Error: " + ex.Message, "Sample Error").ShowAsync(); } }
public void ActivateRecord(Geometry geometry) { QueuedTask.Run(() => { try { var layers = MapView.Active.Map.GetLayersAsFlattenedList(); var pfL = layers.FirstOrDefault(l => l is ParcelLayer) as ParcelLayer; // if there is no fabric in the map then exit if (pfL == null) { return; } var recordsLayer = MapView.Active.Map.FindLayers("Records").FirstOrDefault() as BasicFeatureLayer; if (recordsLayer == null) { ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Records Layer is not found.", "Error", System.Windows.MessageBoxButton.OK, MessageBoxImage.Exclamation); return; } RowCursor rowCursor = null; // define a spatial query filter var spatialQueryFilter = new SpatialQueryFilter { // passing the search geometry to the spatial filter FilterGeometry = geometry, // define the spatial relationship between search geometry and feature class SpatialRelationship = SpatialRelationship.Intersects }; // apply the spatial filter to the feature layer in question rowCursor = recordsLayer.Search(spatialQueryFilter); RowHandle rowHandle = null; var featName = string.Empty; if (rowCursor.MoveNext()) { var row = rowCursor.Current; rowHandle = new RowHandle(row); featName = Convert.ToString(row["NAME"]); } if (rowHandle != null) { // Reference the parcel record and set it as the active record var parcelRecord = new ParcelRecord(rowHandle.Token); pfL.SetActiveRecord(parcelRecord); ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Record activated: " + featName, "Info", System.Windows.MessageBoxButton.OK, MessageBoxImage.Information); } } catch (Exception exc) { // Catch any exception found and display in a message box ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Exception caught: " + exc.Message); return; } }); }
private bool CheckSpatialQuery(SpatialQueryFilter sqf, Geometry geom) { if (geom == null) { return(false); } return(HasRelationship(GeometryEngine.Instance, sqf.FilterGeometry, geom, sqf.SpatialRelationship)); }
public override PluginCursorTemplate Search(SpatialQueryFilter spatialQueryFilter) { // Reset Cursor _tressuremapCursor.Reset(); // Do search, for demo not implemented. // Return cursor. return(_tressuremapCursor); }
private bool CheckSpatialQuery(SpatialQueryFilter sqf, object geomFromDb) { var geom = GetGeometryFromBuffer((byte [])geomFromDb, _spatialReference); if (geom == null) { return(false); } return(HasRelationship(GeometryEngine.Instance, sqf.FilterGeometry, geom, sqf.SpatialRelationship)); }
public async void SubscribeToStreamData() { Map map = MapView.Active.Map; FeatureLayer countyFeatureLayer = null; StreamLayer streamLayer = null; QueryFilter qfilter = null; #region Subscribe to Streaming Data //Note: with feature class we can also use a System Task to subscribe and //process rows await QueuedTask.Run(async() => { // or var rfc = realtimeDatastore.OpenTable(name) as RealtimeFeatureClass using (var rfc = streamLayer.GetFeatureClass()) { //non-recycling cursor - 2nd param "false" //subscribe, pre-existing rows are not searched using (var rc = rfc.Subscribe(qfilter, false)) { SpatialQueryFilter spatialFilter = new SpatialQueryFilter(); //waiting for new features to be streamed //default is no cancellation while (await rc.WaitForRowsAsync()) { while (rc.MoveNext()) { using (var row = rc.Current) { switch (row.GetRowSource()) { case RealtimeRowSource.EventInsert: //getting geometry from new events as they arrive Polygon poly = ((RealtimeFeature)row).GetShape() as Polygon; //using the geometry to select features from another feature layer spatialFilter.FilterGeometry = poly;//project poly if needed... countyFeatureLayer.Select(spatialFilter); continue; default: continue; } } } } }//row cursor is disposed. row cursor is unsubscribed } }); #endregion }
private async Task<long[]> FindIntersectingFeaturesAsync() { var rect = await mapView.Editor.RequestShapeAsync(DrawShape.Rectangle); SpatialQueryFilter filter = new SpatialQueryFilter(); filter.Geometry = GeometryEngine.Project(rect, cities.FeatureTable.SpatialReference); filter.SpatialRelationship = SpatialRelationship.Intersects; filter.MaximumRows = 1000; var features = await cities.FeatureTable.QueryAsync(filter); return features .Select(f => Convert.ToInt64(f.Attributes[cities.FeatureTable.ObjectIDField])) .ToArray(); }
protected async override void OnClick() { Map map = MapView.Active.Map; if ((_rtCursor != null) && (_rtCursor.GetState() == RealtimeCursorState.Subscribed)) { _rtCursor.Unsubscribe(); return; } StreamLayer streamFLyr = map.Layers[0] as StreamLayer; SpatialQueryFilter sf = new SpatialQueryFilter(); sf.SpatialRelationship = SpatialRelationship.Intersects; FeatureLayer countiesFLyr = map.Layers[1] as FeatureLayer; //var serviceConnectionProperties = // new RealtimeServiceConnectionProperties(new Uri("https://zihans.esri.com:6443/arcgis/rest/services/Florence-Polygon-Out/StreamServer"), RealtimeDatastoreType.StreamService); //RealtimeDatastore realtimeDatastore = null; //string tableName = ""; RealtimeFeatureClass realTimeFC = null; await QueuedTask.Run(async() => { realTimeFC = streamFLyr.GetFeatureClass(); _rtCursor = realTimeFC.SearchAndSubscribe(null, true); while (await _rtCursor.WaitForRowsAsync()) { while (_rtCursor.MoveNext()) { using (var rtFeature = _rtCursor.Current as RealtimeFeature) { switch (rtFeature.GetRowSource()) { case RealtimeRowSource.EventInsert: Polygon searchGeom = rtFeature.GetShape() as Polygon; sf.FilterGeometry = searchGeom; countiesFLyr.Select(sf); continue; default: continue; } } } } }); }
private async Task <long[]> FindIntersectingFeaturesAsync() { var rect = await MyMapView.Editor.RequestShapeAsync(DrawShape.Rectangle); SpatialQueryFilter filter = new SpatialQueryFilter(); filter.Geometry = GeometryEngine.Project(rect, _featureLayer.FeatureTable.SpatialReference); filter.SpatialRelationship = SpatialRelationship.Intersects; filter.MaximumRows = 1000; var features = await _featureLayer.FeatureTable.QueryAsync(filter); return(features .Select(f => Convert.ToInt64(f.Attributes[_featureLayer.FeatureTable.ObjectIDField])) .ToArray()); }
public override PluginCursorTemplate Search(SpatialQueryFilter spatialQueryFilter) { //TODO Perform a spatial search on this currently opened //plugin table/object //Where clause will always be empty if //PluginDatasourceTemplate.IsQueryLanguageSupported = false. Envelope ext = spatialQueryFilter.FilterGeometry.Extent; var parameters = String.Format("{0},{1},{2},{3},{4}", this.name, ext.XMin, ext.YMin, ext.XMax, ext.YMax); string result = client.CallAsync("squeryRows|" + parameters).GetAwaiter().GetResult(); var oids = JsonConvert.DeserializeObject <List <string> >(result); var columns = this.GetQuerySubFields(spatialQueryFilter); var cur = new ProPluginCursorTemplate(client, oids, columns, this); return(cur); }
/// <summary> /// Performs a spatial query against a feature layer. /// </summary> /// <remarks>It is assumed that the feature layer and the search geometry are using the same spatial reference.</remarks> /// <param name="searchLayer">The feature layer to be searched.</param> /// <param name="searchGeometry">The geometry used to perform the spatial query.</param> /// <param name="spatialRelationship">The spatial relationship used by the spatial filter.</param> /// <returns>Cursor containing the features that satisfy the spatial search criteria.</returns> public static RowCursor Search(this BasicFeatureLayer searchLayer, Geometry searchGeometry, SpatialRelationship spatialRelationship) { RowCursor rowCursor = null; // define a spatial query filter var spatialQueryFilter = new SpatialQueryFilter { // passing the search geometry to the spatial filter FilterGeometry = searchGeometry, // define the spatial relationship between search geometry and feature class SpatialRelationship = spatialRelationship }; // apply the spatial filter to the feature layer in question rowCursor = searchLayer.Search(spatialQueryFilter); return(rowCursor); }
/// <summary> /// Performs a spatial query against the table/feature class. /// </summary> /// <remarks>It is assumed that the feature class and the search geometry are using the same spatial reference.</remarks> /// <param name="searchTable">The table/feature class to be searched.</param> /// <param name="searchGeometry">The geometry used to perform the spatial query.</param> /// <param name="spatialRelationship">The spatial relationship used by the spatial filter.</param> /// <returns></returns> public static async Task <RowCursor> SearchAsync(this Table searchTable, Geometry searchGeometry, SpatialRelationship spatialRelationship) { RowCursor rowCursor = null; await QueuingTaskFactory.StartNew(() => { // TODO // define a spatial query filter using the provided spatial relationship and search geometry SpatialQueryFilter spatialQueryFilter = new SpatialQueryFilter(); // apply the spatial filter to the feature class in question rowCursor = searchTable.Search(spatialQueryFilter); }); return(rowCursor); }
protected override async Task <bool> OnSketchCompleteAsync(Geometry geometry) { if (_pointLayer == null) { return(true); } // execute the select on the MCT var result = await QueuedTask.Run(() => { // define the spatial query filter var spatialQuery = new SpatialQueryFilter() { FilterGeometry = geometry, SpatialRelationship = SpatialRelationship.Contains }; // gather the selection var pointSelection = _pointLayer.Select(spatialQuery); // get the list of oids List <long> oids = pointSelection.GetObjectIDs().ToList(); if (oids.Count == 0) { return(false); } // if some attributes aren't valid if (_attributesValid.ContainsValue(false)) { return(false); } // everything is valid - apply to the identified features var editOp = new EditOperation(); editOp.Name = "Apply edits"; foreach (var oid in oids) { editOp.Modify(_pointLayer, oid, _attributes); } editOp.Execute(); return(true); }); return(result); }
private async Task <List <long> > GetFeaturesWithinGeometryAsync(FeatureLayer featureLayer) { return(await QueuedTask.Run(() => { List <long> oids = new List <long>(); //Get the client point edges Point topLeft = new Point(_toolClickedPoint.X - PixelTolerance, _toolClickedPoint.Y + PixelTolerance); Point bottomRight = new Point(_toolClickedPoint.X + PixelTolerance, _toolClickedPoint.Y - PixelTolerance); //convert the client points to Map points MapPoint mapTopLeft = MapView.Active.ClientToMap(topLeft); MapPoint mapBottomRight = MapView.Active.ClientToMap(bottomRight); //create a geometry using these points Geometry envelopeGeometry = EnvelopeBuilder.CreateEnvelope(mapTopLeft, mapBottomRight); if (envelopeGeometry == null) { return null; } //Spatial query to gather the OIDs of the features within the geometry SpatialQueryFilter spatialQueryFilter = new SpatialQueryFilter { FilterGeometry = envelopeGeometry, SpatialRelationship = SpatialRelationship.Intersects, }; using (RowCursor rowCursor = featureLayer.Search(spatialQueryFilter)) { while (rowCursor.MoveNext()) { using (Row row = rowCursor.Current) { var id = row.GetObjectID(); oids.Add(id); } } } return oids; })); }
/// <summary> /// Implement querying with a query filter /// </summary> /// <param name="qf"></param> /// <returns></returns> private List <int> ExecuteQuery(QueryFilter qf) { List <int> result = new List <int>(); SpatialQueryFilter sqf = null; if (qf is SpatialQueryFilter) { sqf = qf as SpatialQueryFilter; } var whereClause = string.Empty; if (!string.IsNullOrEmpty(qf.WhereClause)) { whereClause = qf.WhereClause; } else { if (qf.ObjectIDs.Count() > 0) { whereClause = $@"{_tableInfo.FieldInfo.ObjectIdField} in ({string.Join (",", qf.ObjectIDs)})"; } } var subFields = string.IsNullOrEmpty(qf.SubFields) ? "*" : qf.SubFields; _dataTable.Clear(); int recCount = _sqlDb.QueryTable(_tableName, subFields, whereClause, qf.PostfixClause, _dataTable); _dataTable.PrimaryKey = new DataColumn[] { _dataTable.Columns[_tableInfo.FieldInfo.ObjectIdField] }; if (recCount == 0) { return(result); } if (sqf == null) { result = _dataTable.AsEnumerable().Select(row => (int)row[_tableInfo.FieldInfo.ObjectIdField]).ToList(); } else { result = _dataTable.AsEnumerable().Where(Row => CheckSpatialQuery(sqf, Row[_tableInfo.GeometryFieldName])).Select(row => (int)row[_tableInfo.FieldInfo.ObjectIdField]).ToList(); } return(result); }
private string GetUSNGID_Point(MapPoint point) { SpatialQueryFilter filter = new SpatialQueryFilter() { FilterGeometry = point, SpatialRelationship = SpatialRelationship.Intersects, SubFields = "GRID1MIL,GRID100K" }; RowCursor cursor = USNGLayer.Search(filter); cursor.MoveNext(); Row row = cursor.Current; string grid1mil = (string)row["GRID1MIL"]; string grid100k = (string)row["GRID100K"]; cursor.Dispose(); // this code is from gregs roads code: https://gist.github.com/gregbunce/1733a741d8b4343a7a60fc42acf5086b double dblMeterX = (double)point.X; double dblMeterY = (double)point.Y; // add .5 to so when we conver to long and the value gets truncated, it will still regain our desired value (if you need more info on this, talk to Bert) dblMeterX = dblMeterX + .5; dblMeterY = dblMeterY + .5; long lngMeterX = (long)dblMeterX; long lngMeterY = (long)dblMeterY; // trim the x and y meter values to get the needed four characters from each value string strMeterX_NoDecimal = lngMeterX.ToString(); string strMeterY_NoDecimal = lngMeterY.ToString(); // remove the begining characters strMeterX_NoDecimal = strMeterX_NoDecimal.Remove(0, 1); strMeterY_NoDecimal = strMeterY_NoDecimal.Remove(0, 2); //remove the ending characters strMeterY_NoDecimal = strMeterY_NoDecimal.Remove(strMeterY_NoDecimal.Length - 1); strMeterX_NoDecimal = strMeterX_NoDecimal.Remove(strMeterX_NoDecimal.Length - 1); // piece all the unique_id fields together return(grid1mil + grid100k + strMeterX_NoDecimal + strMeterY_NoDecimal); }
protected override async Task <bool> OnSketchCompleteAsync(Geometry geometry) { if (Module1.SelectedMapMember is BasicFeatureLayer layer) { // create a new spatial filter // to find features intersecting the sketch geometry var filter = new SpatialQueryFilter(); filter.FilterGeometry = geometry; filter.SpatialRelationship = SpatialRelationship.Intersects; long oid = -1; await QueuedTask.Run(() => { // search the layer using the filter // finding the first objectId using (var cursor = layer.Search(filter)) { if (cursor.MoveNext()) { using (var row = cursor.Current) { oid = row.GetObjectID(); } } } }); // if an objectID was found if (oid != -1) { // find the dockpane viewmodel var vm = FrameworkApplication.DockPaneManager.Find("TableControl_TableControlDockpane") as TableControlDockpaneViewModel; // call MoveTo if (vm != null) { vm.MoveTo(oid); } } } return(true); }
/// <summary> /// Returns features filtered by spatial relationship. Honors definition queries on the layer. /// </summary> public static IEnumerable <Feature> FilterLayerFeaturesByGeometry( BasicFeatureLayer layer, ArcGIS.Core.Geometry.Geometry filterGeometry, SpatialRelationship spatialRelationship = SpatialRelationship.Intersects) { var qf = new SpatialQueryFilter() { FilterGeometry = filterGeometry, SpatialRelationship = spatialRelationship }; var features = new List <Feature>(); using (RowCursor rowCursor = layer.Search(qf)) { while (rowCursor.MoveNext()) { features.Add((Feature)rowCursor.Current); } } return(features); }
/// <summary> /// Performs a spatial query against the table/feature class. /// </summary> /// <remarks>It is assumed that the feature class and the search geometry are using the same spatial reference.</remarks> /// <param name="searchTable">The table/feature class to be searched.</param> /// <param name="searchGeometry">The geometry used to perform the spatial query.</param> /// <param name="spatialRelationship">The spatial relationship used by the spatial filter.</param> /// <returns></returns> public static async Task <RowCursor> SearchAsync(this Table searchTable, Geometry searchGeometry, SpatialRelationship spatialRelationship) { RowCursor rowCursor = null; await QueuingTaskFactory.StartNew(() => { // define a spatial query filter var spatialQueryFilter = new SpatialQueryFilter { // passing the search geometry to the spatial filter FilterGeometry = searchGeometry, // define the spatial relationship between search geometry and feature class SpatialRelationship = spatialRelationship }; // apply the spatial filter to the feature class in question rowCursor = searchTable.Search(spatialQueryFilter); }); return(rowCursor); }
/// <summary> /// Returns oids of features filtered by spatial relationship. Honors definition queries on the layer. /// </summary> public static IEnumerable <long> FilterLayerOidsByGeometry( BasicFeatureLayer layer, ArcGIS.Core.Geometry.Geometry filterGeometry, SpatialRelationship spatialRelationship = SpatialRelationship.Intersects) { var qf = new SpatialQueryFilter() { FilterGeometry = filterGeometry, SpatialRelationship = spatialRelationship }; var oids = new List <long>(); using (RowCursor rowCursor = layer.Search(qf)) { while (rowCursor.MoveNext()) { oids.Add(rowCursor.Current.GetObjectID()); } } return(oids); }
public async void LoadFile(MapPoint point) { if (await CheckRequirements()) { await QueuedTask.Run(() => { SpatialQueryFilter spatialFilter = new SpatialQueryFilter(); spatialFilter.FilterGeometry = point; spatialFilter.SpatialRelationship = SpatialRelationship.Intersects; using (RowCursor cursor = _selectedFeatureLayer.GetFeatureClass().Search(spatialFilter, false)) { int fieldindex = cursor.FindField(_selectedField); while (cursor.MoveNext()) { using (Row row = cursor.Current) { string rowValue = Convert.ToString(row.GetOriginalValue(fieldindex)); string filePath = _fileWorkspace + @"\" + AddPrefixAndSuffix(rowValue) + _fileExtension; if (!File.Exists(filePath)) { MessageBox.Show("File Does Not Exist", "Hmm..."); return; } SaveFileExtensionsToDisk(_fileExtension); Process.Start(filePath); } return; } MessageBox.Show("Select a feature from the '" + _selectedFeatureLayer.Name + "' feature layer", "Woah Woah Woah"); } }); } }
/// <summary> /// Implement querying with a query filter /// </summary> /// <param name="qf"></param> /// <returns></returns> private List <int> ExecuteQuery(QueryFilter qf) { List <int> result = new List <int>(); SpatialQueryFilter sqf = null; if (qf is SpatialQueryFilter) { sqf = qf as SpatialQueryFilter; } var whereClause = string.Empty; if (!string.IsNullOrEmpty(qf.WhereClause)) { whereClause = qf.WhereClause; } else { if (qf.ObjectIDs.Count() > 0) { whereClause = $@"{ObjectIdFieldName} in ({string.Join(",", qf.ObjectIDs)})"; } } var subFields = string.IsNullOrEmpty(qf.SubFields) ? "*" : qf.SubFields; var selectRows = _dataTable.Select(whereClause, qf.PostfixClause); int recCount = selectRows.Length; if (recCount == 0) { return(result); } if (sqf == null) { result = selectRows.Select(row => (int)row[ObjectIdFieldName]).ToList(); } else { result = selectRows.Where(Row => CheckSpatialQuery(sqf, Row[GeometryFieldName] as Geometry)).Select(row => (int)row[ObjectIdFieldName]).ToList(); } return(result); }
/// <summary> /// Performs a spatial query against a feature layer. /// </summary> /// <remarks>It is assumed that the feature layer and the search geometry are using the same spatial reference.</remarks> /// <param name="searchTable">The feature layer to be searched.</param> /// <param name="searchGeometry">The geometry used to perform the spatial query.</param> /// <param name="spatialRelationship">The spatial relationship used by the spatial filter.</param> /// <returns>Cursor containing the features that satisfy the spatial search criteria.</returns> public static RowCursor Search(this BasicFeatureLayer searchLayer, Geometry searchGeometry, SpatialRelationship spatialRelationship) { RowCursor rowCursor = null; // define a spatial query filter var spatialQueryFilter = new SpatialQueryFilter { // passing the search geometry to the spatial filter FilterGeometry = searchGeometry, // define the spatial relationship between search geometry and feature class SpatialRelationship = spatialRelationship }; // apply the spatial filter to the feature layer in question rowCursor = searchLayer.Search(spatialQueryFilter); return rowCursor; }
/// <summary> /// Occurs once the user completed the sketch and select the information for the /// embeddable control /// </summary> /// <param name="geometry">Sketch geometry in map coordinates.</param> /// <returns></returns> protected override Task<bool> OnSketchCompleteAsync(Geometry geometry) { // select the first point feature layer in the active map var pointLayer = ActiveMapView.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>(). Where(lyr => lyr.ShapeType == ArcGIS.Core.CIM.esriGeometryType.esriGeometryPoint).FirstOrDefault(); if (pointLayer == null) return Task.FromResult(true); // execute the select on the MCT QueuedTask.Run(() => { // define the spatial query filter var spatialQuery = new SpatialQueryFilter() { FilterGeometry = geometry, SpatialRelationship = SpatialRelationship.Contains }; // gather the selection var pointSelection = pointLayer.Select(spatialQuery); // set up a dictionary to store the layer and the object IDs of the selected features var selectionDictionary = new Dictionary<MapMember, List<long>>(); selectionDictionary.Add(pointLayer as MapMember, pointSelection.GetObjectIDs().ToList()); // assign the dictionary to the view model _attributeVM.SelectedMapFeatures = selectionDictionary; // load the first feature into the attribute inspector _attributeVM.AttributeInspector.Load(pointLayer, pointSelection.GetObjectIDs().First()); }); return Task.FromResult(true); }
/// <summary> /// Get the selected Feature Layer and the corresponding FeatureClass /// If there are any features selected for that layer, Zoom to the extent and use the extent for a Spatial Query /// If there are no feature selected, perform a normal query on all the features for that FeatureClass /// List the selected Object Ids in the datagrid by assigning them to FeatureData property (bound to the datagrid) /// </summary> public async void Work() { var selectedLayer = MapView.Active.GetSelectedLayers()[0]; if (selectedLayer is FeatureLayer) { var featureLayer = selectedLayer as FeatureLayer; QueuedTask.Run(async () => { using (var table = featureLayer.GetTable()) { var whereClause = String.Format("{0} = '{1}'", SelectedField, FieldValue); using (var mapSelection = featureLayer.GetSelection()) { QueryFilter queryFilter; if (mapSelection.GetCount() > 0) { Envelope envelope = null; using (var cursor = mapSelection.Search()) { while (cursor.MoveNext()) { using (var feature = cursor.Current as Feature) { if (envelope == null) envelope = feature.GetShape().Extent; else envelope = envelope.Union(feature.GetShape().Extent); } } } queryFilter = new SpatialQueryFilter { FilterGeometry = new EnvelopeBuilder(envelope).ToGeometry(), SpatialRelationship = SpatialRelationship.Contains, WhereClause = whereClause }; } else { queryFilter = new QueryFilter {WhereClause = whereClause}; } try { using (var selection = table.Select(queryFilter)) { var readOnlyList = selection.GetObjectIDs(); FeatureData = new ObservableCollection<FeatureData>( readOnlyList.Select( objectId => new FeatureData {ObjectId = objectId.ToString()})); MapView.Active.Map.SetSelection(new Dictionary<MapMember, List<long>> { {featureLayer, new List<long>(readOnlyList)} }); } } catch (Exception) { } } } }); } }
private async Task<List<long>> GetFeaturesWithinGeometryAsync(FeatureLayer featureLayer) { return await QueuedTask.Run(() => { List<long> oids = new List<long>(); //Get the client point edges Point topLeft = new Point(_toolClickedPoint.X - PixelTolerance, _toolClickedPoint.Y + PixelTolerance); Point bottomRight = new Point(_toolClickedPoint.X + PixelTolerance, _toolClickedPoint.Y - PixelTolerance); //convert the client points to Map points MapPoint mapTopLeft = MapView.Active.ClientToMap(topLeft); MapPoint mapBottomRight = MapView.Active.ClientToMap(bottomRight); //create a geometry using these points Geometry envelopeGeometry = EnvelopeBuilder.CreateEnvelope(mapTopLeft, mapBottomRight); if (envelopeGeometry == null) return null; //Spatial query to gather the OIDs of the features within the geometry SpatialQueryFilter spatialQueryFilter = new SpatialQueryFilter { FilterGeometry = envelopeGeometry, SpatialRelationship = SpatialRelationship.Intersects, }; using (RowCursor rowCursor = featureLayer.Search(spatialQueryFilter)) { while (rowCursor.MoveNext()) { using (Row row = rowCursor.Current) { var id = row.GetObjectID(); oids.Add(id); } } } return oids; }); }
private async void MouseMoved(MouseEventArgs parameters) { if (!IsInitialized) return; Exception exceptionToHandle = null; try { // Gets cursors location as a MapPoint from MapView since MouseEventArgs is general // .NET framework event and doesn't contain location information directly // MapViewService abstracts reference to MapView and its ScreenToLocation method. var mouseMapPoint = MapViewService.GetLocation(parameters); _queryAreaLayer.Graphics.Clear(); // Buffering mouses location. Note that operation isn't async. var bufferResult = Esri.ArcGISRuntime.Geometry.GeometryEngine.GeodesicBuffer( mouseMapPoint, 100, LinearUnits.Miles); var bufferGraphic = new Graphic(bufferResult); _queryAreaLayer.Graphics.Add(bufferGraphic); // If buffer / guery is running, wait until its done if (_isQuerying) return; _isQuerying = true; // Execute Spatial Query against the GeodatabaseFeatureTable // that provides data access to local // geodatabase and its features. var query = new SpatialQueryFilter() { Geometry = bufferResult }; var queryResults = await _featureTable.QueryAsync(query); _statesLayer.Graphics.Clear(); if (queryResults.Count() < 1) { _isQuerying = false; return; } // Set features to the graphics layer as a graphics foreach (GeodatabaseFeature feature in queryResults) { _statesLayer.Graphics.Add(feature.AsGraphic()); } // Union all states and calculate total area var stateGeometries = new List<Esri.ArcGISRuntime.Geometry.Geometry>(); foreach (var state in _statesLayer.Graphics) { stateGeometries.Add(state.Geometry); } var totalAreaGeometry = Esri.ArcGISRuntime.Geometry.GeometryEngine.Union(stateGeometries); TotalArea = Esri.ArcGISRuntime.Geometry.GeometryEngine.Area(totalAreaGeometry); _isQuerying = false; } catch (Exception exception) { Debug.WriteLine(exception); exceptionToHandle = exception; _isQuerying = false; } if (exceptionToHandle != null) { // Initialization failed, show message and return await MessageService.Instance.ShowMessage(string.Format( "Something went wrong when buffering or querying data. Error = {0}", exceptionToHandle.ToString()), "An error occured"); } }