npm package: @route-optimization/react
Description: React components and hooks for route optimization map visualization
Latest version: 1.0.4

# @route-optimization/react

React hooks and components for building route optimization and map visualization interfaces.

## Features

- 🎣 **React Hooks** - `useRouteMap` and `useMapControls` for map interactions
- 🗺️ **Ready Components** - `RouteMapView`, `MapProvider`, and `MapControls`
- 🚀 **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

```bash
# 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/core
```

## Quick Start

### Basic Usage

```tsx
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

```tsx
<RouteMapView apiKey="YOUR_GOOGLE_MAPS_API_KEY" routes={[route1, route2, route3]} autoFitBounds />
```

### With Custom Components

```tsx
<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:**

```tsx
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.

```tsx
import { MapProvider } from '@route-optimization/react';

<MapProvider apiKey="YOUR_API_KEY">
  <YourMapComponents />
</MapProvider>;
```

#### `MapControls`

Pre-built UI controls for zoom and clear operations.

```tsx
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.

```tsx
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 div
- `isLoading` - Loading state boolean
- `error` - Error object if initialization failed
- `renderRoute(route)` - Function to render a single route
- `renderRoutes(routes)` - Function to render multiple routes
- `fitBounds(bounds)` - Function to fit map to bounds
- `clearMap()` - Function to clear all overlays

#### `useMapControls`

Hook for map control operations (requires MapProvider).

```tsx
import { useMapControls } from '@route-optimization/react';

const { zoomIn, zoomOut, panTo, fitBounds, clearMap, getCurrentZoom, getCurrentCenter } =
  useMapControls();
```

**Functions:**

- `zoomIn()` - Increase zoom level by 1
- `zoomOut()` - Decrease zoom level by 1
- `panTo(location)` - Pan to specific location
- `fitBounds(bounds)` - Fit map to bounds
- `clearMap()` - Clear all markers and polylines
- `getCurrentZoom()` - Get current zoom level
- `getCurrentCenter()` - Get current map center

### Utility Functions

```tsx
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

```tsx
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

```tsx
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](../../examples/react-example) 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`:

```tsx
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) - Core types and adapters
- [@route-optimization/vue](../vue) - Vue 3 composables (coming soon)
- [@route-optimization/vanilla](../vanilla) - Vanilla JavaScript API (coming soon)