gistda-sphere-react

useRoute

Plan routes with several stops and travel modes, with status, totals and turn-by-turn directions

useRoute plans a route on the map and keeps its result in React state: status, error, totals and ready-to-show turn-by-turn steps. It works inside SphereMap and anywhere else under SphereProvider.

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

function Directions() {
  const route = useRoute();
  const { status, error, summary, steps } = route;

  const plan = () => {
    route.clear();
    route.addDestination({ lon: 100.5018, lat: 13.7563 }); // Bangkok
    route.addDestination({ lon: 98.9853, lat: 18.7883 });  // Chiang Mai
    route.search();
  };

  return (
    <div>
      <button onClick={plan} disabled={status === "calculating"}>Plan route</button>
      {error && <p>{error.message}</p>}
      {summary && (
        <p>{summary.distanceText} · {summary.intervalText}</p>
      )}
      <ol>
        {steps.map((step, index) => (
          <li key={index}>
            {step.instruction} ({step.distanceText})
          </li>
        ))}
      </ol>
    </div>
  );
}

The route and its stop markers are drawn on the map by Sphere. Users can drag the stops, and click one to remove it. destinations follows these changes, but the route is only recalculated when you call search(), or by itself with the auto option.

Result state

PropertyTypeDescription
status"idle" | "calculating" | "complete" | "error"Where the calculation is.
isCalculatingbooleanShortcut for status === "calculating".
summaryRouteSummary | nullTotals: distance (m), distanceText, interval (s), intervalText.
stepsRouteStep[]Turn-by-turn steps.
destinationsLocation[]Locations of the stops, in order. Updates when stops are added, removed, reordered or dragged.
routesRouteResult[]The raw legs from Sphere, one per pair of consecutive stops.
errorRouteErrorInfo | nullWhy the last calculation failed.
isReadybooleantrue once the map is ready.

Turn-by-turn directions

Each step is ready to display:

RouteStep fieldExampleDescription
instruction"Turn right to Sathon Nuea Rd"Readable instruction in the route language.
distanceText"640 m"Formatted step distance.
intervalText"1 min"Formatted step time (empty in Fly mode).
turn1Turn code. Compare it with ROUTE_TURN to pick an icon.
name"Sathon Nuea Rd"Road name.
distance, interval640, 60Raw meters and seconds.
legIndex0Which leg (pair of stops) the step belongs to.

Instructions and totals follow the route language, which is the map's language: Thai unless you set language on SphereProvider or SphereMap. To change only the route language, call setLanguage("en"). For Sphere's own styled panel instead, add <RouteGuide>.

Road names come from the routing service in the language used for the calculation, so after changing the language (with setLanguage or SphereMap's language prop), call search() again to update them.

Turn codes

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

const icons = {
  [ROUTE_TURN.TurnLeft]: "↰",
  [ROUTE_TURN.TurnRight]: "↱",
  [ROUTE_TURN.Straight]: "↑",
  [ROUTE_TURN.UTurn]: "↶",
  [ROUTE_TURN.Arrive]: "⚑",
};

ROUTE_TURN has TurnLeft, TurnRight, SlightLeft, SlightRight, HeadToward, Straight, EnterExpressway, UTurn, Arrive and Ferry. getTurnInstruction(turn, roadName, language) builds an instruction yourself, e.g. for data from the routing web service.

Errors

error.codeMeaning
a numberSphere's status code, e.g. 410 when there's no data for the selected time.
"timeout"The routing service didn't answer within timeout (20 s by default). This usually means your API key doesn't have the routing service enabled.
"exception"Sphere threw while planning the route. error.message has the details.

Options

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

const route = useRoute({
  auto: true,
  timeout: 15_000,
  onRouteComplete: (routes) => console.log("Done", routes),
  onError: (error) => toast(error.message),
});
OptionTypeDescription
autobooleanRecalculate whenever the stops change, including when users drag or remove them. Off by default, like Sphere.
timeoutnumberMilliseconds before reporting a "timeout" error. Default 20000, and 0 turns it off.
onRouteComplete(routes) => voidA route finished calculating.
onRouteError(status) => voidSphere reported a routing error code.
onError(error: RouteErrorInfo) => voidAny failure, including timeouts.

Stops

MethodDescription
addDestination(location, mode?)Add a stop (a location or a sphere.Marker), optionally with its own travel mode for the next leg.
insertDestination(index, location, mode?)Insert a stop at a position.
removeDestination(marker) / removeDestinationAt(index)Remove a stop.
listDestinations() / size()The stop markers / how many there are. For their locations as state, use destinations.
reverse()Reverse the order of the stops.
clearDestinations()Remove all stops.
clearPath()Remove the drawn route, keeping the stops.
clear()Remove stops and route, and reset the result state.
search()Calculate the route.

destinations holds the stops' locations as React state, so you can show them in your own list:

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

function StopList() {
  const { destinations, removeDestinationAt } = useRoute({ auto: true });

  return (
    <ol>
      {destinations.map((stop, index) => (
        <li key={`${stop.lon},${stop.lat},${index}`}>
          {stop.lat.toFixed(4)}, {stop.lon.toFixed(4)}
          <button onClick={() => removeDestinationAt(index)} type="button">
            Remove
          </button>
        </li>
      ))}
    </ol>
  );
}

Travel modes and options

MethodDescription
setMode(mode) / getMode()"Traffic" (the default: fastest, avoiding traffic jams), "Cost" (fastest by road, without traffic data), "Distance" (shortest) or "Fly" (straight lines).
setModeAt(index, mode) / getModeAt(index)Mode of the leg starting at a stop.
enableRouteType(type, state) / isRouteTypeEnabled(type)Allow or avoid "Road", "Ferry", "Tollway" or "All".
setRestrict("Bike", state) / isRestrictEnabled("Bike")Avoid roads closed to motorcycles.
setLabel(label) / getLabel()Label on the route: "Distance", "Time" or "Hide".
setLineStyle(part, style) / getLineStyle(part)Style of "Road", "Ferry", "Destination" or "Focus" lines.
setAuto(state) / getAuto()Recalculate automatically when stops change. You can also pass the auto option.
enableContextMenu()Add a "Direction to here" item to the right-click menu, which adds a stop there. Also turns on auto.
setLanguage(language) / getLanguage()Language of instructions and labels.
route.setMode("Distance");
route.enableRouteType("Tollway", false); // avoid tollways
route.setRestrict("Bike", true);         // motorcycle-friendly roads
route.setLineStyle("Road", { lineColor: "#2563eb", lineWidth: 6 });

Fly mode draws straight lines and works without the routing service. Sphere can't label straight-line legs (it throws), so useRoute hides route labels while Fly is used and restores your label setting afterwards.

Data and export

MethodDescription
getSteps()Steps of the current route, read on demand.
getDistance(format?) / getInterval(format?)Totals in meters / seconds, or formatted text.
getGuide(format?)Raw legs, or Sphere's formatted guide as a DocumentFragment.
exportRouteLine(style?)The whole route as one sphere.Polyline (not added to the map). Call .toJSON() for GeoJSON.
setPlaceholder(element)Render Sphere's guide panel into an element.

Routing needs the routing service enabled for your API key. Without it, Sphere gives no error of its own, so useRoute reports a "timeout" error instead of waiting forever.

On this page