Search Along Route
This example demonstrates how to calculate a route, simulate navigation, and search for landmarks along the route path.
Live Demo
Overview
This example shows how to:
- Calculate a route between two landmarks and display it on the map
- Start and stop simulated navigation along the route
- Search for landmarks located along the route path
- Manage route visualization and alternative routes
Code Implementation
Imports
First, import the required modules from the SDK:
import {
GemKit,
GemMap,
Coordinates,
PositionService,
Landmark,
RoutePreferences,
RoutingService,
GemError,
Route,
NavigationService,
SearchService,
HighlightRenderSettings,
HighlightOptions,
TaskHandler,
GemIcon,
AddressField
} from '@magiclane/maps-sdk';
Setup State Variables
Initialize global variables for route and navigation management:
let map: GemMap | null = null;
let routingHandler: TaskHandler | null = null;
let navigationHandler: TaskHandler | null = null;
let routes: Route[] | null = null;
let isSimulationActive = false;
let areRoutesBuilt = false;
// UI Elements
let controlsDiv: HTMLDivElement;
let buildRouteBtn: HTMLButtonElement;
let cancelRouteBtn: HTMLButtonElement;
let clearRoutesBtn: HTMLButtonElement;
let searchBtn: HTMLButtonElement;
let startSimBtn: HTMLButtonElement;
let stopSimBtn: HTMLButtonElement;
let searchResultsPanel: HTMLDivElement;
Initialize Map and UI Buttons
Setup the map and create control buttons:
Calculate Route
Build a route between San Francisco and San Jose:
Manage Routes
Cancel or clear routes from the map:
Start Navigation Simulation
Simulate navigation along the calculated route:
Stop Navigation Simulation
Cancel the navigation and clear routes:
Search Along Route
Search for landmarks located along the route path:
Update UI State
Manage button visibility based on application state:
Utility Functions
Format route labels and display messages:
Key Features
Route Calculation
Calculate routes using RoutingService:
Parameters:
waypoints: Array ofLandmarkobjects (departure and destination)preferences:RoutePreferencesobject for route customizationcallback: Receives error code and calculated routes
Route Display:
calculatedRoutes.forEach((route, index) => {
routesMap?.add(route, index === 0, { label: getRouteLabel(route) });
});
The first route is set as the main route (index === 0).
Navigation Simulation
Start simulated navigation using NavigationService:
Parameters:
route: The main route to navigateundefined: Optional start position (uses route start if undefined)callbacks: Object withonNavigationInstructionandonErrorhandlers
Following Position:
map.startFollowingPosition?.();
The map camera follows the simulated position along the route.
Search Along Route
Find landmarks along the route path:
Method:
SearchService.searchAlongRoute({
route: routesMap.mainRoute,
onCompleteCallback: (err, results) => { /* ... */ }
});
Results:
- Returns all landmarks located along the route
- Results are logged to console for inspection
- Useful for finding POIs, rest stops, gas stations, etc.
Route Management
Clear All Routes:
map?.preferences.routes.clear();
Keep Only Main Route:
map?.preferences.routes.clearAllButMainRoute?.();
Cancel Calculation:
RoutingService.cancelRoute(routingHandler);
Route Labels
Display distance and duration on route:
const timeDistance = route.getTimeDistance();
const totalDistance = timeDistance.unrestrictedDistanceM
+ timeDistance.restrictedDistanceM;
const totalDuration = timeDistance.unrestrictedTimeS
+ timeDistance.restrictedTimeS;
Labels show formatted distance (km) and duration (hours/minutes).
State Management
The UI updates based on application state:
States:
- Idle: Show "Build Route" button
- Calculating: Show "Cancel Route" button
- Route Built: Show "Clear Routes", "Search", and "Start Simulation"
- Simulating: Show "Stop Simulation" button only
Implementation Details
- Handler Management: Store routing and navigation handlers for cancellation
- Route Storage: Keep calculated routes in state for later use
- Dynamic UI: Buttons appear/disappear based on current state
- Error Handling: Handle route calculation and navigation errors gracefully
- Console Logging: Search results are logged to browser console
- Route Centering: Automatically center map on calculated routes
Use Cases
- Trip Planning: Calculate routes and find nearby POIs
- Gas Station Search: Find fuel stops along long routes
- Rest Area Discovery: Locate rest stops during navigation
- Restaurant Finder: Search for dining options along the way
- Testing Navigation: Simulate navigation without GPS movement
- Route Comparison: View alternative routes with different landmarks
Next Steps
- Text Search - Free-text search for landmarks
- Search Category - Filter search by categories
- What is Nearby - Find all POIs around current location