npm package: @route-optimization/converter
Description: Convert routes between different formats for cross-platform compatibility
Author: ks-arm
Latest version: 1.0.4

# @route-optimization/converter

Convert routes between different formats for cross-platform compatibility.

## Installation

```bash
npm install @route-optimization/converter @route-optimization/core
# or
pnpm add @route-optimization/converter @route-optimization/core
# or
yarn add @route-optimization/converter @route-optimization/core
```

## Features

- ✅ Convert `Route` objects to Google Maps `DirectionsResult` format
- ✅ Parse Google Maps `DirectionsResult` back to `Route` objects
- ✅ Encode/decode polylines using Google's Encoded Polyline Algorithm
- ✅ Format distances and durations for human-readable display
- ✅ Full TypeScript support with type definitions
- ✅ Zero runtime dependencies (except `@route-optimization/core`)

## Usage

### Convert Route to DirectionsResult

Convert your optimized routes to Google Maps DirectionsResult format for use with DirectionsRenderer:

```typescript
import { toDirectionsResult } from '@route-optimization/converter';
import type { Route } from '@route-optimization/core';

const route: Route = {
  id: 'route-1',
  vehicleId: 'vehicle-1',
  stops: [
    {
      id: 'stop-1',
      location: { lat: 13.7563, lng: 100.5018 },
      address: 'Bangkok, Thailand',
      type: 'START',
      sequence: 0,
    },
    {
      id: 'stop-2',
      location: { lat: 13.7467, lng: 100.5342 },
      address: 'Sukhumvit, Bangkok',
      type: 'DELIVERY',
      sequence: 1,
      serviceDuration: 5, // minutes
    },
  ],
  totalDistance: 5200,
  totalDuration: 15,
  status: 'pending',
};

// Convert to DirectionsResult
const directionsResult = toDirectionsResult(route);

// Use with Google Maps DirectionsRenderer
const directionsRenderer = new google.maps.DirectionsRenderer();
directionsRenderer.setDirections(directionsResult);
directionsRenderer.setMap(map);
```

### Parse DirectionsResult to Route

Parse Google Maps DirectionsResult into Route objects:

```typescript
import { fromDirectionsResult } from '@route-optimization/converter';

// Get DirectionsResult from Google Maps Directions API
const directionsService = new google.maps.DirectionsService();
const result = await directionsService.route({
  origin: 'Bangkok, Thailand',
  destination: 'Sukhumvit, Bangkok',
  travelMode: google.maps.TravelMode.DRIVING,
});

// Parse to Route object
const route = fromDirectionsResult(result.routes[0], {
  id: 'vehicle-1',
  name: 'Delivery Van #1',
  capacity: 1000,
});

console.log(route.stops);
console.log(route.totalDistance); // meters
console.log(route.totalDuration); // minutes
```

### Polyline Encoding/Decoding

Encode and decode polylines for efficient data transfer:

```typescript
import { encodePolyline, decodePolyline } from '@route-optimization/converter';

const points = [
  { lat: 13.7563, lng: 100.5018 },
  { lat: 13.7467, lng: 100.5342 },
  { lat: 13.7365, lng: 100.5601 },
];

// Encode to polyline string
const encoded = encodePolyline(points);
console.log(encoded); // "encodedPolylineString"

// Decode back to points
const decoded = decodePolyline(encoded);
console.log(decoded); // [{ lat: 13.7563, lng: 100.5018 }, ...]
```

### Format Utilities

Format distances and durations for display:

```typescript
import { formatDistance, formatDuration } from '@route-optimization/converter';

// Format distance (meters to readable string)
console.log(formatDistance(1234)); // "1.2 km"
console.log(formatDistance(567)); // "567 m"

// Format duration (seconds to readable string)
console.log(formatDuration(3661)); // "1 hour 1 min"
console.log(formatDuration(125)); // "2 mins"
console.log(formatDuration(45)); // "45 secs"
```

## API Reference

### toDirectionsResult(route: Route): DirectionsResult

Converts a Route object to Google Maps DirectionsResult format.

**Parameters:**

- `route` - Route object from @route-optimization/core

**Returns:**

- DirectionsResult with legs, steps, bounds, and overview polyline

**Features:**

- Automatically sorts stops by sequence
- Creates legs between consecutive stops
- Calculates distance using Haversine formula
- Includes service duration in total duration
- Generates overview polyline for the entire route
- Calculates bounds for map viewport

### fromDirectionsResult(directionsResult: DirectionsResult, vehicleInfo?: Partial<Vehicle>): Route

Parses Google Maps DirectionsResult into a Route object.

**Parameters:**

- `directionsResult` - DirectionsRoute from Google Maps API
- `vehicleInfo` - Optional vehicle information to include in the route

**Returns:**

- Route object compatible with @route-optimization/core

**Features:**

- Extracts stops from legs
- Calculates total distance and duration
- Assigns sequential stop numbers
- Supports custom vehicle information

### encodePolyline(points: LatLng[]): string

Encodes an array of coordinates to a polyline string using Google's Encoded Polyline Algorithm.

**Parameters:**

- `points` - Array of {lat, lng} coordinates

**Returns:**

- Encoded polyline string

### decodePolyline(encoded: string): LatLng[]

Decodes a polyline string to an array of coordinates.

**Parameters:**

- `encoded` - Encoded polyline string

**Returns:**

- Array of {lat, lng} coordinates

### formatDistance(meters: number): string

Formats distance in meters to human-readable string.

**Parameters:**

- `meters` - Distance in meters

**Returns:**

- Formatted string (e.g., "1.2 km", "567 m")

### formatDuration(seconds: number): string

Formats duration in seconds to human-readable string.

**Parameters:**

- `seconds` - Duration in seconds

**Returns:**

- Formatted string (e.g., "1 hour 5 mins", "45 secs")

## Use Cases

### 1. Render Optimized Routes on Google Maps

```typescript
const route = optimizeRoute(stops);
const directionsResult = toDirectionsResult(route);
directionsRenderer.setDirections(directionsResult);
```

### 2. Export Routes to External Systems

```typescript
const route = getCurrentRoute();
const directionsResult = toDirectionsResult(route);
const exportData = JSON.stringify(directionsResult);
```

### 3. Import Routes from Google Maps

```typescript
const result = await getDirectionsFromGoogle();
const route = fromDirectionsResult(result.routes[0]);
saveRoute(route);
```

### 4. Cross-Platform Route Sharing

```typescript
// Platform A (using custom Route format)
const route = getRouteFromPlatformA();
const directionsResult = toDirectionsResult(route);

// Platform B (using Google Maps format)
const routeForPlatformB = directionsResult;
```

## Type Definitions

This package includes full TypeScript definitions for:

- `DirectionsResult`
- `DirectionsRoute`
- `DirectionsLeg`
- `DirectionsStep`
- `LatLng`
- `LatLngBounds`
- `Distance`
- `Duration`
- `TravelMode`

## Bundle Size

- ESM: ~8.3 KB
- CJS: ~9.6 KB
- Types: ~4.2 KB

## License

MIT

## Related Packages

- [@route-optimization/core](../core) - Core types and utilities
- [@route-optimization/react](../react) - React hooks and components