gistda-sphere-react

Overview

A typed client for every Sphere REST web service, in the browser or on a server

Besides the map, Sphere offers REST web services for search, routing, geocoding, elevation, static maps, agriculture, disasters and population. This library includes a typed client for all of them.

Each button calls a Sphere web service around Victory Monument.

Getting a client

In React, under SphereProvider, useSphereServices uses the provider's key, and its language unless you pass locale:

import { useSphereServices } from "gistda-sphere-react";
import { useState } from "react";

function PlaceName() {
  const services = useSphereServices({ locale: "en" });
  const [name, setName] = useState("");

  const find = async () => {
    const { data } = await services.search.search("central world");
    setName(data[0]?.name ?? "Not found");
  };

  return (
    <button onClick={find} type="button">
      {name || "Find Central World"}
    </button>
  );
}

Anywhere else, including Node.js 18+ and serverless functions, create a client with your key. Import it from gistda-sphere-react/services, which leaves out React and the map code (the main entry exports it too):

import { createSphereServices } from "gistda-sphere-react/services";

const services = createSphereServices({
  apiKey: process.env.SPHERE_API_KEY!,
  locale: "en",
});
OptionTypeDefaultDescription
apiKeystringrequired (createSphereServices only)Your API key, with the services you call enabled.
locale"th" | "en""th"Default language of results. Most methods also take locale.
timeoutnumber15000Milliseconds before a request fails. 0 turns it off.
method"auto" | "get" | "post""auto""auto" sends GET, and switches to a form POST when the URL would be too long (large polygons, route matrices).
baseUrlstringhttps://api.sphere.gistda.or.th/servicesService URL, e.g. your own proxy.
fetchtypeof fetchglobal fetchYour own fetch implementation.
refererstring–A page URL on a domain your key allows, sent as the Referer header. Needed on servers when your key is limited to certain domains. See On a server.
headersRecord<string, string>–Extra headers for every request, such as for your own proxy.

Services

NamespaceMethodsPage
searchsearch, suggestSearch and places
poinearby, get, clusterSearch and places
tagscategoriesSearch and places
routeroute, matrixRouting
geoaddress, elevationAddresses and elevation
mapsstaticMapUrl, embedUrl, rasterTileUrl, vectorTileUrl, vectorStyleUrl, wmtsCapabilitiesUrlMaps and tiles
agri, info (crops, land)rice, maize, cassava, sugarcane, palm, rubber, crop, cropSuitability, landSuitabilityAgriculture
info (disasters)flood, drought, hotspot, disasterRecurring, floodRecurrence, droughtRecurrenceDisasters
populationgetPopulation

Locations and areas

Methods that look up a place take a { lon, lat } location. Many also accept a GeoJSON geometry, such as a polygon, to ask about an area instead:

await services.agri.rice({ lon: 100.5, lat: 14.2 });
await services.agri.rice({
  type: "Polygon",
  coordinates: [[[100.4, 14.1], [100.6, 14.1], [100.6, 14.3], [100.4, 14.1]]],
});

Errors

Every method throws a SphereServiceError when a call fails:

import { SphereServiceError } from "gistda-sphere-react";

try {
  await services.route.route({
    from: { lon: 100.5018, lat: 13.7563 },
    to: { lon: 100.5604, lat: 13.7466 },
  });
} catch (error) {
  if (error instanceof SphereServiceError) {
    console.log(error.code, error.service, error.status, error.message);
  }
}
codeMeaning
"key"The API key isn't allowed to use this service. Enable it for your key (Sphere answers with HTTP 200 and an error message, which the client detects). On a server, a key limited to certain domains also needs referer.
"http"The service returned an HTTP error. See status and body.
"timeout"No answer within timeout.
"aborted"You aborted the request with a signal.
"network"The request couldn't be sent, e.g. offline or blocked by CORS.
"parse"The response wasn't JSON.

Cancelling requests

Every method takes signal and timeout:

const controller = new AbortController();
const pending = services.search.suggest("วัดพ", { signal: controller.signal, timeout: 5000 });
controller.abort(); // pending rejects with code "aborted"

On a server

The client runs wherever fetch does, such as Node.js 18+, serverless functions, and Next.js route handlers or Server Components. This route handler searches with a key that only the server knows:

app/api/places/route.ts
import { createSphereServices } from "gistda-sphere-react/services";

const services = createSphereServices({
  apiKey: process.env.SPHERE_API_KEY!,
  locale: "en",
  // A page on a domain your key allows
  referer: "https://www.example.com/",
});

export async function GET(request: Request) {
  const keyword = new URL(request.url).searchParams.get("q") ?? "";
  const { data } = await services.search.search(keyword);
  return Response.json(data);
}

Sphere checks which site a request comes from by its Referer header. Browsers send it, but servers don't, so a key limited to certain domains fails on a server with code "key". Set referer to a page on a domain your key allows, or use a key without domain limits.

Each service has to be enabled for your API key in the Sphere console. Keep server keys out of client code: in Next.js, don't start their names with NEXT_PUBLIC_.

On this page