Quick Tip - geometry.contains

Blog Post created by odoe on Oct 14, 2015


Pretty recently, there was a cool blog series on using the GeometryEngine in the ArcGIS JS API. If you haven't read it, I highly suggest you do.


But before we had the GeometryEngine, we had to do stuff the old fashioned way, manually checking geometries on our own.


I pulled this from a use case I found in an old repo of mine. The use-case is that I have a point, and before I can do anything with this point, I need to know if the point is contained in any other features.


For example, I have data being streamed real-time into my app, say service requests, but I only care about seeing the ones that are in some predefined service areas.


A simple utility could look something like this:


define([], function () {
  var geomUtil = {};
  geomUtil.graphicsContain = function (graphics, pt) {
    var len = graphics.length;
    while (len--) {
      var graphic = graphics[len];
      if (graphic.geometry.contains && graphic.geometry.contains(pt)) {
        return pt;
    return null;
  return geomUtil;


So basically, you iterate over the graphics and as soon as you find a graphic that contains the point, you return it. This saves some time as it doesn't need to iterate all the graphics to finish.


You could even tweak this a bit by finding the graphic in the graphics array that contains the point and instead of returning the point, return the graphic. To do it right, you'd need to iterate over all graphics though, which depending on your application could be expensive.


Here's a sample of what this might look like in action:

JS Bin - Collaborative JavaScript Debugging

To test it, draw some rectangles and polygons on the map and then try to add points. You should only be able to add points inside the polygons.


You could even get pretty function and start filtering out geometries that you can throw into the GeometryEngine and now you have a party!


For more geodev tips and tricks, check out my blog!