geospock-apideprecated

Wraps the GeoSpock API in a simple-to-use JavaScript interface

Usage no npm install needed!

<script type="module">
  import geospockApi from 'https://cdn.skypack.dev/geospock-api';
</script>

README

GeoSpock API for JavaScript

GeoSpock provides a high performance cloud database service, optimized for geospatial data. This is the official JavaScript library for interacting with the GeoSpock REST API, providing a convenient JavaScript-native interface to the service, that hides the messy details of dealing with REST requests.

This is Version 3.0.0.

Supported Environments

The library is available as geospock-api on NPM, and can be used directly server-side in Node.js projects, or client-side as part of a Browserify bundle.

To install in your Node.js project:

$ npm install --save geospock-api

Then in your code:

var geospock = require("geospock-api");

For simple web projects, you can also import the prebuilt library (dist/geospock.min.js) directly into an HTML page with a script tag, either from your own server, or from this public URL:

<script src="http://geospock.com/lib/javascript/v3/geospock.min.js"></script>

The prebuilt library exposes itself via the global variable geospock.

GeoSpock REST API Versions

This library supports connecting to servers running either version 2, or version 3 of the GeoSpock REST API, and will hide the differences from you, avoiding the need for you to write multiple versions of your code. For GeoSpock servers, the API version is detected automatically from the base URL.

Example

In the examples directory is a simple web page, api-sandbox.html that demonstrates all the methods of the GeoSpock library. The page is completely self-contained (just open it directly in a browser), and the latest version is also available online. It serves as a convenient substitute for exploring the API itself using curl commands, and can also be used as a sandbox for experimenting with the JavaScript library. Just open up a copy in your editor of choice and start hacking.

Usage

For each GeoSpock dataset you want to interact with, create a new instance of the class geospock.DatasetConnection, specifying the GeoSpock server base URL, and an API key for the dataset (you can copy and paste from your GeoSpock dashboard):

var geospockServer = "https://geospock-cloud.appspot.com/locatables/v3";
var datasetKey = "<paste your API key here>"
var dataset = new geospock.DatasetConnection(geospockServer, datasetKey);

Use the methods of DatasetConnection to perform operations on Locatables in the dataset. Each method corresponds directly to one of the GeoSpock API endpoints, so keep the REST API documentation to hand for the details. All the methods complete asynchronously, and make use of promises to provide a natural way to handle delayed responses, and to make it easy to chain together sequences of operations, and handle errors. Here’s an example (searching around a point, and adding a tag to anything we find):

var geospock = require("geospock-api");
var when = require("when");

var geospockServer = "https://geospock-cloud.appspot.com/locatables/v3";
var datasetKey = "<paste your API key here>"
var centralLondon = {
    lat: 51.50999,
    lon: -0.11055
}

var dataset = new geospock.DatasetConnection(geospockServer, datasetKey);
dataset.findNearest(0, centralLondon).then(function(results) {
    var usedMark = {
        data: { used: new Date().toString() }
    }
    return when.map(results.locatables, function(locatable) {
        return dataset.update(locatable, usedMark);
    })
}).then(function(updatedLocatables) {
    console.log("Found and updated " + updatedLocatables.length + " locatables");
}).catch(function(error) {
    console.log("Something went wrong");
});

Note that this example makes use of the CujoJS when library for additional promise functionality. CujoJS/when is the library that geospock-api uses internally to handle promises.

Locatables

The GeoSpock JavaScript library provides a dedicated class, geospock.Locatable, for representing objects in your GeoSpock datasets. All results from the DatasetConnection methods will use instances of the Locatable class. A fully-populated locatable looks something like this:

{
    type: 6,
    id: "!--3----5-----2ppr3SIrxMV------3NuW3",
    location: {
        lat: 51.50999069213867,
        lon: -0.11055000126361847
    },
    data: {
        thedata: "I'm swimming in the Thames!"
    }
}

When you’re passing locatables into the methods of DatasetConnection, feel free to construct the JavaScript objects directly in your code, wherever that’s more convenient. So long as the object has the properties required by the method, everything will work fine.

Many of the dataset methods operate on a specific locatable. These methods make use of the same Locatable instances for identification, but only the type and id properties are required. If you already have a Locatable instance from the results of a query, you can simply pass this in as the locatable identifier (see the example above). If not, the Locatable constructor is the most convenient way to make a new identifier:

dataset.fetch(new geospock.Locatable(0, "test_id_0")).then(function(locatable) {
    console.log(JSON.stringify(locatable, null, 4));
});

Error Handling

Most of the DatasetConnection methods return a promise for a single object, containing the response data from the corresponding API operation. If the API returns an error, the promise will be rejected with an error object that looks something like this:

{
    error: {
        httpCode: 400,
        code: 40000,
        message: "Error specific message"
    }
}

Refer to the REST API documentation for a complete list of possible error codes.

DatasetConnection Reference

Construtor

Create a connection to a GeoSpock dataset. No REST requests are made by the constructor.

dataset = new geospock.DatasetConnection(baseUrl, apiKey, forceApiVersion);
  • Parameter baseUrl (string): Base URL of the GeoSpock REST API server (with or without a trailing slash).
  • Parameter apiKey (string): The API key (shown in the GeoSpock dashboard) for the dataset.
  • Parameter forceApiVersion (number): If specified, forces the library to use that major version of the REST API, rather than auto-detecting from the base URL (optional).
  • Returns (DatasetConnection): An instance for interacting with the dataset.

Method: create

Create one or more new locatables. The method returns a promise for an array of Locatable objects, and also an array of individual promises for each of the locatables in the batch. In the event of an error, the main array promise will be rejected, but some of the locatables may have been created successfully. You can inspect the individual locatable promises to determine exactly which ones failed or succeeded.

createdLocatables = dataset.create(locatables);
  • Parameter locatables (Locatable[]): Each locatable must specify a type, and optionally an id, location, and data.
  • Returns (Promise<Locatable[]>): A promise for an array of Locatables. createdLocatables.locatables is the array of individual locatable promises.

Note: In the event of an error, the individual promises (in createdLocatables.locatables[i]) for each new locatable that failed will be rejected, and the main array promise will also be rejected. In the case of the individual promises, the error objects will not contain a code property.

Example

var newLocatable = new geospock.Locatable(0); 
newLocatable.location = { lat: 52, lon: 1 };
newLocatable.data = { test: "test" };
dataset.create([newLocatable]).then(function(locatables) {
    console.log("new locatable created with id: " + locatables[0].id);
});

Method: fetch

Fetch an existing locatable. The locatable to fetch is identified with a Locatable object, which must contain a type, and an id.

fetchedLocatable = dataset.fetch(locatable);
  • Parameter locatable (Locatable): Identifies (type, id) which locatable to retrieve.
  • Returns (Promise<Locatable>): A promise for a Locatable object containing all properties (location, data) retrieved from the server.

Example

dataset.fetch(new geospock.Locatable(0, "test_id_0")).then(function(locatable) {
    console.log(JSON.stringify(locatable, null, 4));
});

Method: update

Update an existing locatable. Use a Locatable object (including type and id) to identify which locatable to update. The updates are specified with a second partial Locatable object, containing just the properties you want to modify. You can change either the location (both lat and lon), or one or more data properties, or both. You can delete data properties by updating their values to null. Note that the updated locatable isn’t fetched from the server – the returned object is generated locally, by combining the two objects you pass in.

updatedLocatable = dataset.update(locatable, updates);
  • Parameter locatable (Locatable): Identifies (type, id) which locatable to update.
  • Parameter updates (Locatable): Specifies the properties (location, data) to update.
  • Returns (Promise<Locatable>): A promise for the Locatable object, updated as specified.

Example

var locationUpdate = {
    location: {
        lat: newLat,
        lon: newLon
    }
}   
dataset.update(locatable, locationUpdate).then(function(locatable) {
    console.log(JSON.stringify(locatable, null, 4));
});

Method: delete

Delete an existing locatable. The locatable to delete is identified with a Locatable object, which must contain a type, and an id.

confirmation = dataset.delete(locatable);
  • Parameter locatable (Locatable): Identifies (type, id) which locatable to delete.
  • Returns (Promise<Object>): A promise for an empty object, indicating the locatable was deleted.

Example

dataset.delete(new geospock.Locatable(0, "test_id_0")).then(function() {
    console.log("Locatable \"test_id_0\" deleted");
});

Method: findInBox

Get locatables within a bounding box. The bounding box is specified as a latitude and longitude range (see example).

locatablesInBox = dataset.findInBox(type, box, options);
  • Parameter type (number): The type of locatables to query, an integer (required).
  • Parameter box (Object): The bounding box to query (required, see example).
  • Parameter options (Object): Additional arguments (optional, see below).
  • Returns (Promise<Object>): A promise for the results object, containing an array of locatables (see below).

An options object can be passed in to specify additional behaviour. The defaults are:

var defaultOptions = {
    numResults: 299,     // The maximum number of locatables to return.
    downsample: 0,       // A specific downsample level, or "auto" (see REST API docs).
    locationsOnly: false // When true, data properties are omitted from the results.
};

The method returns a promise for an object with the following properties:

  • results.downsample (number): The downsample level that was used to retrieve the results.
  • results.locatables (Locatable[]) - An array of Locatable objects found in the bounding box.

Example

var box = {
    sw: { lat: 52, lon: 0 },
    ne: { lat: 53, lon: 1 }
};
dataset.findInBox(0, box, {numResults: 1000}).then(function(results) {
    console.log(JSON.stringify(results.locatables, null, 4));
});

Method: findDownsampledInBox

Get locatables within a bounding box, choosing a downsampling level automatically if more than numResults locatables are found. This is a convenience wrapper around findInBox. All parameters work the same way, except the downsample option will be ignored, if specified.

locatablesInBox = dataset.findDownsampledInBox(type, box, options);

Method: findInRadius

Return all the locatables within a specified earth-surface distance (in meters) from a central point (a latitude, longitude pair, see example), sorted by distance (closest first).

locatablesInCircle = dataset.findInRadius(type, location, radius, options);
  • Parameter type (number): The type of locatables to query, an integer (required).
  • Parameter location (Object): The central point (required, see example).
  • Parameter radius (number): The earth-surface radius, in meters (required).
  • Parameter options (Object): Additional arguments (optional, see below).
  • Returns (Promise<Object>): A promise for the results object, containing an array of locatables (see below).

An options object can be passed in to specify additional behaviour. The defaults are:

var defaultOptions = {
    numResults: 299,     // The maximum number of locatables to return.
    downsample: 0,       // A specific downsample level, or "auto" (see REST API docs).
    locationsOnly: false // When true, data properties are omitted from the results.
};

The method returns a promise for an object with the following properties:

  • results.box (Object): The bounding box the results were taken from (same format as for the findInBox parameter).
  • results.downsample (number): The downsample level that was used to retrieve the results.
  • results.locatables (Locatable[]) - An array of Locatable objects, sorted by distance (closest first). Each locatable will have an individual distance property, specified in meters.

Example

var location = { lat: 52, lon: 0 };
dataset.findInRadius(0, location, 1000, {numResults: 1000}).then(function(results) {
    console.log(JSON.stringify(results.locatables, null, 4));
});

Method: findNearest

Get the nearest locatables to a specified location (a latitude, longitude pair, see example).

locatablesNearest = dataset.findNearest(type, location, options);
  • Parameter type (number): The type of locatables to query, an integer (required).
  • Parameter location (Object): The point around which to search (required, see example).
  • Parameter options (Object): Additional arguments (optional, see below).
  • Returns (Promise<Object>): A promise for the results object, containing an array of locatables (see below).

An options object can be passed in to specify additional behaviour. The defaults are:

var defaultOptions = {
    numResults: 299,     // The maximum number of locatables to return.
    locationsOnly: false // When true, data properties are omitted from the results.
};

The method returns a promise for an object with the following properties:

  • results.box (Object): The bounding box the results were taken from (same format as for the findInBox parameter).
  • results.locatables (Locatable[]) - An array of Locatable objects found in the bounding box.

Example

var location = { lat: 52, lon: 0 };
dataset.findNearest(0, location, {numResults: 1000}).then(function(results) {
    console.log(JSON.stringify(results.locatables, null, 4));
});

Version History

  • 3.0.0: Fully support GeoSpock API v3.0.0.
  • 3.0.0-beta.4: There are no client-side changes in this GeoSpock release.
  • 3.0.0-beta.3: Remove downsample option for KNN search. Remove tracking of locatable hints.
  • 3.0.0-beta.2: Fixes a bug that was failing all creates with the v3 API.
  • 3.0.0-beta.1: Support v3 GeoSpock API. Add radius search.
  • 2.2.2: Documentation update.
  • 2.2.1: Fix a bug in API error handling.
  • 2.2.0: Initial release.