ArcGIS JavaScript – How to Count Point Features in Polygon Using ArcGIS API for JavaScript

arcgis-javascript-apiarcgis-serverfeature-layerinfowindow

I have published in my ArcGIS Server two layers: A polygon one and a point feature one. Points are contained in polygons.

I would like to know how to count the number of points belonging/contained to a polygon using ArcGIS Javascript API. So, the functionality would be, clicking in one of the polygons and then, present somewhere an integer (in an Infowindow or textbox in sidebar) saying "There are X points in this polygon".

Could you provide any ideas or examples?

Best Answer

Check out this post I just wrote on selecting a polygon and highlighting it. Once you have the polygon that was clicked on, you simply do a query with intersection. Clicking on feature to create particular new map using ArcGIS API for JavaScript?

You could substitute below into the mapOnClick(evt) function above...

var queryTask = new esri.tasks.QueryTask(YourServiceName),
    query = new esri.tasks.Query(),
    countOfFeatures = 0;

query.geometry = geom;
query.returnGeometry = true;
query.spatialRelationship = esri.tasks.Query.SPATIAL_REL_INTERSECTS;
queryTask.execute(query, function (results) {
    if (results.features && results.features.length > 0) {
        dojo.forEach(results.features, function (feature) {
            countOfFeatures++;
        )};
    }
    alert("Number of points in polygon " + countOfFeatures);
)};
Related Question