Location

Kinvey allows you to express the location of entities, including users, as longitude and latitude points on the coordinate system. Based on this, you can run proximity queries to find the closest restaurants, shops, or friends to a given location.

To perform queries based on geographical location -- for example, find restaurants near a user or track a user's run -- an app needs to perform operations on longitude and latitude number pairs. With Kinvey, all you need to do is add a top-level field named _geoloc to your entity, with a value of [lon,lat].

Queries

Kinvey utilizes MongoDB's geo query syntax. Specifically, when you create an entity with a _geoloc field containing coordinates, Kinvey will create a 2d index on this field.

For example, consider this data describing real estate properties:

# example data for real estate listings
[
  {
    "_id": "5508784846a8c0938a047581",
    "description" : "2000 sq feed small company office",
    "address" : "1 Main St, Cambridge, MA",
    "_geoloc" : [ -71.083934, 42.362474 ]
  },
  {
    "_id": "5508784846a8c0938a003622",
    "description" : "5000 sq feet in a commercial building",
    "address" : "1 Broadway, Cambridge, MA",
    "_geoloc" : [ -71.085438, 42.362688 ]
  },
  {
    "_id": "5508784846a8c0938a003303",
    "description" : "10000 sq feet of office space",
    "address" : "711 Atlantic Ave, Boston, MA",
    "_geoloc" : [-71.056416, 42.351018 ]
  }
]

To find the properties near a point (for example, the user's current location), run the following REST API query:

?query={"_geoloc": {"$nearSphere": [-71,41]}}

This will return all entities, ranked by the spherical distance to the coordinates [-71,42], reversely ordered. Of course, an app typically wants to only display the N closest items. You can restrict the number of results by using the limit modifier. For example:

?query={"_geoloc": {"$nearSphere": [-71,41]}}&limit=5

Another way to limit the result set is to specify a maximum radius. This is achieved by adding a $maxDistance parameter and passing a value in miles.

# the properties within half a mile of the coordinates provided
?query={"_geoloc": { "$nearSphere": [-71.05,42.35], "$maxDistance":"0.5" } }

The $nearSphere and $maxDistance operators assume that the region you are interested in is a circle. Alternatively, you can use the $within operator in combination with the $box or $polygon operators to specify a more complex region:

?query={"_geoloc": { "$within": { "$box": [[-70, 44], [-72, 42]]} } }

When using $box, the coordinates represent the lower-left and upper-right corners of the box.

To query for a polygon shape, similarly include in the array all the points that define it:

?query={"_geoloc": { "$within": { "$polygon": [[100,120], [100,100], [120,100], [240,200]]} } }