DEV Community

Erik Hatcher
Erik Hatcher

Posted on • Edited on

Playing with geoWithin

Here's the geoWithin playground for this post.

Geographic points are annotated on documents (longitude first, then latitude):

{
  _id: 1,
  city: "Charlottesville",
  location: {
  type: "Point",
    coordinates: [-78.47668,38.02931]
  }
}
Enter fullscreen mode Exit fullscreen mode

GeoJSON objects are not automatically indexed with "dynamic": true mappings and must be explicitly mapped, like this:

{
  "mappings": {
    "dynamic": true,
    "fields": {
      "location": {
        "type": "geo"
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Now the geoWithin operator can be used to locate points within a shape, in this case a 100m radius circle centered near the location of our one document:

{
  $search: {
    index: "default",
    "geoWithin": {
      "circle": {
        "center": {
          "type": "Point",
          "coordinates": [-78.476,38.029]
        },
        "radius": 100
      },
      "path": "location"
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Press Run on the Playground (linked near the top of this post) and you'll see instead of an empty array [] that it returns the, one, matching document.

Top comments (0)