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.

For an entity to have an associated location, set a property named _geoloc to a location using an array with two values: longitude and latitude:

{
  _id: 'entity-id',
  _geoloc: [ -71, 42 ] // longitude: -71, latitude: 42.
}
{
  _id: 'entity-id',
  _geoloc: [ -71, 42 ] // longitude: -71, latitude: 42.
}

Queries

Location Queries are only available on fields named _geoloc. The value of this field should be an array holding two elements: longitude and latitude (in that order). We’ll index that attribute for you, so you can run location queries on it.

The following Location Operators are supported by Kinvey.Query:

  • near matches if the field is within the supplied radius (in miles) of the supplied coordinate.
  • withinBox matches if the field is within the box specified by the two supplied coordinates.
  • withinPolygon matches if the field is within the polygon specified by the supplied list of coordinates.

Example

To retrieve a users location you will need to install the nativescript-geolocation plugin.

tns plugin add nativescript-geolocation

A query to retrieve all restaurants close (10 mile radius) to a users’ current location could look as follows:

import { getCurrentLocation } from 'nativescript-geolocation';

const promise = getCurrentLocation()
  .then((location) => {
    const coord = [location.longitude, location.latitude];
    const query = new Kinvey.Query().near('_geoloc', coord, 10);
    const datastore = Kinvey.DataStore.collection('restaurants');
    const subscription = datastore.find(query)
      .subscribe((restaurants: {}[]) => {
        // ...
      }, (error: Kinvey.BaseError) => {
        // ...
      }, () => {

      });
  });
var geolocation = require('nativescript-geolocation');

var promise = geolocation.getCurrentLocation()
  .then(function(location) {
    var coord = [location.longitude, location.latitude];
    var query = new Kinvey.Query().near('_geoloc', coord, 10);
    var datastore = Kinvey.DataStore.collection('restaurants');
    var subscription = datastore.find(query)
      .subscribe(function(restaurants) {
        // ...
      }, function(error) {
        // ...
      }, function() {

      });
  });
Got a question?