gistda-sphere-react

useRoute

Calculate and display routes between locations

Calculate and display routes between locations.

Bangkok → Chiang Mai
import { useRoute } from 'gistda-sphere-react';

function RouteComponent() {
  const { addDestination, search, getDistance, getInterval, clear, isReady } = useRoute();

  const calculateRoute = () => {
    addDestination({ lon: 100.5018, lat: 13.7563 });
    addDestination({ lon: 98.9853, lat: 18.7883 });
    search();
  };

  return (
    <div>
      <button onClick={calculateRoute}>Calculate Route</button>
      <button onClick={clear}>Clear</button>
    </div>
  );
}

Options

useRoute accepts an optional options object for route events:

OptionTypeDescription
onRouteComplete(routes: unknown[]) => voidCalled when route calculation finishes
onRouteError(errorCode: number) => voidCalled when route calculation fails
const { search, getDistance, getInterval, addDestination, clear } = useRoute({
  onRouteComplete() {
    console.log('Distance:', getDistance(true));
    console.log('Duration:', getInterval(true));
  },
  onRouteError(code) {
    console.error('Route error:', code);
  },
});

Turn-by-Turn Directions

Use getGuide() to retrieve step-by-step navigation instructions after a route is calculated.

  • getGuide() returns an array of RouteGuideStep objects
  • getGuide(true) returns an HTMLElement with formatted directions
import { useRoute, type RouteGuideStep } from 'gistda-sphere-react';

function TurnByTurnRoute() {
  const [steps, setSteps] = useState<RouteGuideStep[]>([]);

  const { addDestination, search, getGuide } = useRoute({
    onRouteComplete() {
      const guide = getGuide();
      if (Array.isArray(guide)) {
        setSteps(guide as RouteGuideStep[]);
      }
    },
  });

  return (
    <div>
      <button onClick={() => {
        addDestination({ lon: 100.5018, lat: 13.7563 });
        addDestination({ lon: 98.9853, lat: 18.7883 });
        search();
      }}>
        Get Directions
      </button>
      <ol>
        {steps.map((step, i) => (
          <li key={i}>
            <strong>{step.instruction}</strong>
            <span> — {String(step.distance)}</span>
            {step.duration && <span> · {String(step.duration)}</span>}
          </li>
        ))}
      </ol>
    </div>
  );
}

RouteGuideStep

PropertyTypeDescription
instructionstringTurn-by-turn instruction text
distancenumber | stringDistance for this step
durationnumber | stringDuration for this step
locationLocationGeographic coordinates of this step

Functions

FunctionParametersReturnsDescription
isReady-booleanRouting service initialized
addDestination(destination, mode?)voidAdd a destination
insertDestination(index, destination, mode?)voidInsert at index
removeDestination(marker)voidRemove by marker ref
removeDestinationAt(index)voidRemove by index
clearDestinations()voidRemove all destinations
clearPath()voidRemove route path only
clear()voidRemove entire route
reverse()voidReverse direction
search()voidCalculate and display route
getDistance(format?)number | stringTotal distance
getInterval(format?)number | stringEstimated travel time
getGuide(format?)RouteGuideStep[] | HTMLElementTurn-by-turn directions
exportRouteLine(options?)SpherePolyline | nullExport as Polyline
listDestinations()SphereMarker[]List destination markers
size()numberNumber of destinations
setMode(mode)voidSet routing mode
setModeAt(index, mode)voidSet mode for segment
enableRouteType(routeType, state)voidEnable/disable route type
setLabel(label)voidSet label display mode
setAuto(state)voidToggle auto-recalculation
setLanguage(lang: "th" | "en")voidSet routing language: "th" or "en"

RouteMode

ModeDescription
"Traffic"Fastest route using real-time traffic data
"Cost"Fastest route without traffic
"Distance"Shortest route by distance
"Fly"Direct straight line

RouteType

TypeDescription
"Road"Regular roads
"Ferry"Ferry routes
"Tollway"Toll roads
"All"All route types

RouteLabelType

LabelDescription
"Distance"Show distance labels
"Time"Show time labels
"Hide"Hide all labels

On this page