select layer by geometry

625
5
05-23-2022 08:49 AM
PeteVitt
Frequent Contributor

Hi - I would to select features from a specific layer using the map tool.  I've found the snippet below, but it selects features from the top-most layer in the toc only:

return QueuedTask.Run(() =>
{
var mapView = MapView.Active;
if (mapView == null)
return true;

//Get all the features that intersect the sketch geometry and flash them in the view.
var results = mapView.GetFeatures(geometry);
return true;
});

 

is there anyway to specify the layer by name like the code below and then perform the select/get features on the specified layer only:

 

var layer = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().First(l => l.Name.Equals("MSA_Class"));

 

Thanks

 

Pete

 

Tags (1)
0 Kudos
5 Replies
StephenRhea_NV5
Frequent Contributor

You could use a `SpatialQueryFilter` to search on the layer.

var layer = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().First(l => l.Name.Equals("MSA_Class"));

var spatialFilter = new SpatialQueryFilter
{
    FilterGeometry = geometry,
    SpatialRelationship = SpatialRelationship.Intersects
};

using (var featureCursor = layer.Search(spatialFilter, false))
{
    while (featureCursor .MoveNext())
    {
        using (var feature = featureCursor.Current)
        {
            // Feature-specific code here
        }
    }
}
0 Kudos
PeteVitt
Frequent Contributor

Thanks Stephen - I'm getting a called on wrong thread exception error  on the layer.Search method

 

return QueuedTask.Run(() =>
{
var mapView = MapView.Active;
if (mapView == null)
return true;
var layer = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().First(l => l.Name.Equals("MSA_Class"));

var spatialFilter = new SpatialQueryFilter
{
FilterGeometry = geometry,
SpatialRelationship = SpatialRelationship.Intersects
};

using (var featureCursor = layer.Search(spatialFilter, false))
{
while (featureCursor.MoveNext())
{
using (var feature = featureCursor.Current)
{
// Feature-specific code here
}
}
}

return true;
});

0 Kudos
StephenRhea_NV5
Frequent Contributor

Are you running that query within a background or worker thread? I'm pretty sure most map interaction has to be done on the main calling thread (MCT), and the QueuedTask runs its function there. However, if you're using this in a separate thread you've created, you may not be able to access the map.

0 Kudos
PeteVitt
Frequent Contributor

the exception went away when I changed:

using (var featureCursor = layer.Search(spatialFilter, false))

to 

using (var featureCursor = layer.Search(spatialFilter))

still only getting the top layer selected -- I'll take a look at the selectability of the layers as suggested below

0 Kudos
sjones_esriau
Esri Contributor

GetFeatures returns a collection of visible and selectable features that intersects a geometry.

If you're only getting the top layer, that may be the only layer selectable in the TOC.

0 Kudos