@route-optimization/react
v1.0.4
Published
React components and hooks for route optimization map visualization
Maintainers
Readme
@route-optimization/react
React hooks and components for building route optimization and map visualization interfaces.
Features
- 🎣 React Hooks -
useRouteMapanduseMapControlsfor map interactions - 🗺️ Ready Components -
RouteMapView,MapProvider, andMapControls - 🚀 Auto-fit Bounds - Automatically adjust map view to show all routes
- 🎨 Customizable - Support custom loading and error components
- 📦 TypeScript - Full TypeScript support with type definitions
- ⚡ Lightweight - ~11KB (CJS) / ~9KB (ESM)
Installation
# Using pnpm
pnpm add @route-optimization/react @route-optimization/core
# Using npm
npm install @route-optimization/react @route-optimization/core
# Using yarn
yarn add @route-optimization/react @route-optimization/coreQuick Start
Basic Usage
import { RouteMapView } from '@route-optimization/react';
import type { Route } from '@route-optimization/core';
const route: Route = {
id: 'route-1',
vehicle: {
id: 'truck-1',
type: 'LIGHT_TRUCK',
startLocation: { lat: 13.7563, lng: 100.5018 },
},
stops: [
{
id: 'stop-1',
location: { lat: 13.7563, lng: 100.5018 },
type: 'START',
sequence: 0,
},
{
id: 'stop-2',
location: { lat: 13.7467, lng: 100.5342 },
type: 'DELIVERY',
sequence: 1,
},
],
totalDistance: 5000,
totalDuration: 900,
};
function App() {
return <RouteMapView apiKey="YOUR_GOOGLE_MAPS_API_KEY" route={route} autoFitBounds />;
}Multiple Routes
<RouteMapView apiKey="YOUR_GOOGLE_MAPS_API_KEY" routes={[route1, route2, route3]} autoFitBounds />With Custom Components
<RouteMapView
apiKey="YOUR_GOOGLE_MAPS_API_KEY"
route={route}
center={{ lat: 13.7563, lng: 100.5018 }}
zoom={12}
loadingComponent={
<div style={{ padding: '2rem', textAlign: 'center' }}>
<Spinner />
<p>Loading map...</p>
</div>
}
errorComponent={(error) => (
<div style={{ padding: '2rem', color: 'red' }}>
<h3>Map Error</h3>
<p>{error.message}</p>
</div>
)}
/>API Reference
Components
RouteMapView
Main component for displaying routes on a map.
Props:
interface RouteMapViewProps {
// Required
apiKey: string;
// Route data (provide either route or routes)
route?: Route;
routes?: Route[];
// Map configuration
center?: LatLng;
zoom?: number;
mapOptions?: google.maps.MapOptions;
// Features
autoFitBounds?: boolean;
// Customization
containerStyle?: React.CSSProperties;
loadingComponent?: React.ReactNode;
errorComponent?: (error: Error) => React.ReactNode;
// Events
onMapReady?: (map: google.maps.Map) => void;
onRouteClick?: (route: Route) => void;
}MapProvider
Context provider for sharing map instance across components.
import { MapProvider } from '@route-optimization/react';
<MapProvider apiKey="YOUR_API_KEY">
<YourMapComponents />
</MapProvider>;MapControls
Pre-built UI controls for zoom and clear operations.
import { MapControls } from '@route-optimization/react';
<MapControls
position="top-right"
showZoomControls={true}
showClearButton={true}
onClear={() => console.log('Map cleared')}
/>;Hooks
useRouteMap
Hook for initializing and controlling the map.
import { useRouteMap } from '@route-optimization/react';
const { mapRef, isLoading, error, renderRoute, renderRoutes, fitBounds, clearMap } = useRouteMap({
apiKey: 'YOUR_API_KEY',
center: { lat: 13.7563, lng: 100.5018 },
zoom: 12,
});Return values:
mapRef- Ref to attach to map container divisLoading- Loading state booleanerror- Error object if initialization failedrenderRoute(route)- Function to render a single routerenderRoutes(routes)- Function to render multiple routesfitBounds(bounds)- Function to fit map to boundsclearMap()- Function to clear all overlays
useMapControls
Hook for map control operations (requires MapProvider).
import { useMapControls } from '@route-optimization/react';
const { zoomIn, zoomOut, panTo, fitBounds, clearMap, getCurrentZoom, getCurrentCenter } =
useMapControls();Functions:
zoomIn()- Increase zoom level by 1zoomOut()- Decrease zoom level by 1panTo(location)- Pan to specific locationfitBounds(bounds)- Fit map to boundsclearMap()- Clear all markers and polylinesgetCurrentZoom()- Get current zoom levelgetCurrentCenter()- Get current map center
Utility Functions
import { formatDistance, formatDuration } from '@route-optimization/react';
// Format distance in meters to readable string
formatDistance(15420); // "15.42 km"
formatDistance(850); // "850 m"
// Format duration in seconds to readable string
formatDuration(3600); // "1h 0m"
formatDuration(2580); // "43m"
formatDuration(90); // "1m 30s"Advanced Usage
Custom Map Adapter
import { MapProvider } from '@route-optimization/react';
import { GoogleMapsAdapter } from '@route-optimization/core';
const customAdapter = new GoogleMapsAdapter({
styles: [
{
featureType: 'poi',
elementType: 'labels',
stylers: [{ visibility: 'off' }],
},
],
});
<MapProvider adapter={customAdapter}>
<YourComponents />
</MapProvider>;Manual Control
import { useRouteMap } from '@route-optimization/react';
function CustomMapComponent() {
const { mapRef, renderRoute, clearMap } = useRouteMap({
apiKey: 'YOUR_API_KEY',
});
const handleShowRoute = () => {
renderRoute(myRoute);
};
return (
<div>
<button onClick={handleShowRoute}>Show Route</button>
<button onClick={clearMap}>Clear</button>
<div ref={mapRef} style={{ width: '100%', height: '500px' }} />
</div>
);
}Examples
Check out the example app for a complete working example with:
- Single and multiple route visualization
- Route metrics display
- Interactive controls
- Responsive UI
TypeScript Support
This package includes full TypeScript definitions. Import types from @route-optimization/core:
import type { Route, Stop, Vehicle, LatLng } from '@route-optimization/core';Requirements
- React 18.0.0 or higher
- Google Maps JavaScript API key
License
MIT
Related Packages
- @route-optimization/core - Core types and adapters
- @route-optimization/vue - Vue 3 composables (coming soon)
- @route-optimization/vanilla - Vanilla JavaScript API (coming soon)
