3

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?

3 Answers 3

4

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);
)};
1
  • Yes, that is exactly what I needed. Thank you very much!
    – Irene
    Commented Nov 15, 2012 at 18:26
4

If you can't process the data beforehand, another method may be to add the layers as separate FeatureLayers in the map, and use the geometry of the selected polygon to query the point layer. When the selection is complete, do a count of the features using FeatureLayer::getSelectedFeatures and use that count to provide information in your popup.

Here is a sample where the FeaureLayer is selected using an extent as the query geometry.

0
2

One good way to do this would be to cheat:

Calculate Statistics for the polygon/point data apriori, adding the relevant field attributes. Use JS identify to simply pop up the relevant field information on click.

1
  • That's a good workaround - but a potential problem is that you'll need to re-calculate the statistics anytime either layer changes. If you can't guarantee that will happen (especially if you're building this site for someone else to maintain) it could lead to future problems Commented Jan 26, 2015 at 22:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.