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.
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",
});| Option | Type | Default | Description |
|---|---|---|---|
apiKey | string | required (createSphereServices only) | Your API key, with the services you call enabled. |
locale | "th" | "en" | "th" | Default language of results. Most methods also take locale. |
timeout | number | 15000 | Milliseconds 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). |
baseUrl | string | https://api.sphere.gistda.or.th/services | Service URL, e.g. your own proxy. |
fetch | typeof fetch | global fetch | Your own fetch implementation. |
referer | string | – | 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. |
headers | Record<string, string> | – | Extra headers for every request, such as for your own proxy. |
Services
| Namespace | Methods | Page |
|---|---|---|
search | search, suggest | Search and places |
poi | nearby, get, cluster | Search and places |
tags | categories | Search and places |
route | route, matrix | Routing |
geo | address, elevation | Addresses and elevation |
maps | staticMapUrl, embedUrl, rasterTileUrl, vectorTileUrl, vectorStyleUrl, wmtsCapabilitiesUrl | Maps and tiles |
agri, info (crops, land) | rice, maize, cassava, sugarcane, palm, rubber, crop, cropSuitability, landSuitability | Agriculture |
info (disasters) | flood, drought, hotspot, disasterRecurring, floodRecurrence, droughtRecurrence | Disasters |
population | get | Population |
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);
}
}code | Meaning |
|---|---|
"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:
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_.