Select to view content in your preferred language

Quick Tip - geometry.contains

823
0
10-14-2015 10:34 AM
Labels (1)
ReneRubalcava
Esri Frequent Contributor
0 0 823

esri-target.jpg

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!

About the Author
Softwhere Developer at Esri working on cool stuff! Author: Introducing ArcGIS API 4 for JavaScript: Turn Awesome Maps into Awesome Apps https://amzn.to/2qwihrV ArcGIS Web Development - https://amzn.to/2EIxTOp Born and raised in East L.A.