# JAWA MAPS LITE: API INTEGRATION GUIDE
Untuk Aplikasi Mobile (Flutter), Backend Web (Django / FastAPI), & Frontend (React / Vue)

Layanan **Jawa Maps Lite** menyediakan satu pintu masuk (Single Unified API Gateway) pada port **`8080`** (`http://<SERVER_IP>:8080`). Semua layanan internal (Routing Valhalla, Geocoding SQLite FTS5, Map Tiles Martin PMTiles) terisolasi di jaringan lokal container dan diakses secara terpadu melalui gateway ini.

---

## 1. Daftar Endpoint API

| Method | Endpoint | Deskripsi |
|---|---|---|
| `GET` | `/api/v1/version` | Informasi status layanan, versi, dan engine yang aktif |
| `GET` | `/api/v1/coverage` | Metadata cakupan wilayah (6 provinsi Pulau Jawa) & Bounding Box |
| `GET` | `/api/v1/search` | Geocoding pencarian alamat & POI |
| `GET` | `/api/v1/autocomplete` | Autocomplete / autosuggest berbasis prefix |
| `GET` | `/api/v1/reverse` | Reverse geocoding (koordinat `lat,lon` -> nama lokasi) |
| `GET` | `/api/v1/route` | Routing sederhana via URL query parameter |
| `POST`| `/api/v1/route` | Routing lanjutan (multi-waypoints, preferensi rute via JSON) |
| `GET` | `/api/v1/pois` | Pencarian fasilitas umum / tempat menarik terdekat |
| `GET` | `/tiles/{source}/{z}/{x}/{y}` | Vector map tiles (OpenMapTiles MVT / PMTiles) |
| `GET` | `/` | Web Map Dashboard & Interactive Testing UI |

---

## 2. Spesifikasi Request & Response

### A. Geocoding Search (`/api/v1/search`)

Mencari lokasi berdasarkan nama gedung, jalan, tempat wisata, atau kota di 6 provinsi Pulau Jawa.

**Request:**
```http
GET /api/v1/search?q=Monumen+Nasional&limit=5
```

**Parameters:**
- `q` (string, wajib): Kata kunci pencarian.
- `limit` (int, opsional, default: 10, max: 50): Jumlah hasil maksimal.

**Response (JSON GeoJSON FeatureCollection):**
```json
{
  "type": "FeatureCollection",
  "query": "Monumen Nasional",
  "count": 1,
  "features": [
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [106.827153, -6.175392]
      },
      "properties": {
        "id": 18274,
        "osm_id": 26861214,
        "name": "Monumen Nasional",
        "category": "tourism",
        "type": "monument",
        "city": "Kota Jakarta Pusat",
        "province": "DKI Jakarta",
        "country": "Indonesia",
        "label": "Monumen Nasional, Kota Jakarta Pusat, DKI Jakarta",
        "lat": -6.175392,
        "lon": 106.827153
      }
    }
  ]
}
```

---

### B. Autocomplete / Suggest (`/api/v1/autocomplete`)

Menghasilkan saran pencarian instan saat pengguna mengetik (debounce disarankan 200–300 ms).

**Request:**
```http
GET /api/v1/autocomplete?q=Sudirm&limit=5
```

**Response:**
```json
{
  "type": "FeatureCollection",
  "query": "Sudirm",
  "count": 3,
  "features": [
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [106.821431, -6.215284]
      },
      "properties": {
        "name": "Jalan Jenderal Sudirman",
        "city": "Kota Jakarta Selatan",
        "province": "DKI Jakarta",
        "label": "Jalan Jenderal Sudirman, Kota Jakarta Selatan, DKI Jakarta"
      }
    }
  ]
}
```

---

### C. Reverse Geocoding (`/api/v1/reverse`)

Menemukan alamat/lokasi terdekat berdasarkan koordinat GPS `lat` dan `lon`. Hanya menerima koordinat dalam cakupan Pulau Jawa. Jika berada di luar cakupan Jawa, API mengembalikan HTTP 404.

**Request:**
```http
GET /api/v1/reverse?lat=-6.1754&lon=106.8271
```

**Response (HTTP 200):**
```json
{
  "type": "FeatureCollection",
  "point": {"lat": -6.1754, "lon": 106.8271},
  "features": [
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [106.827153, -6.175392]
      },
      "properties": {
        "name": "Monumen Nasional",
        "category": "tourism",
        "type": "monument",
        "city": "Kota Jakarta Pusat",
        "province": "DKI Jakarta",
        "label": "Monumen Nasional, Kota Jakarta Pusat, DKI Jakarta"
      }
    }
  ]
}
```

---

### D. Routing (`/api/v1/route`)

Menghitung rute navigasi untuk 3 profil utama:
1. `motorcycle` (Sepeda Motor): Secara default menghindari jalan tol (`use_tolls: 0.0`), mengoptimalkan jalan arteri dan jalur motor.
2. `auto` (Mobil): Mendukung jalan tol dan jalan nasional berkecepatan tinggi (`use_tolls: 0.8`).
3. `pedestrian` (Jalan Kaki): Mengutamakan trotoar, jalur pejalan kaki, zebra cross, dan taman.

#### 1. Via HTTP GET (Sederhana)
```http
GET /api/v1/route?start=-6.2088,106.8456&end=-6.9175,107.6191&profile=motorcycle
```

#### 2. Via HTTP POST (Lengkap / Rekomendasi)
```http
POST /api/v1/route
Content-Type: application/json

{
  "profile": "motorcycle",
  "locations": [
    {"lat": -6.2088, "lon": 106.8456},
    {"lat": -6.9175, "lon": 107.6191}
  ]
}
```

**Response (HTTP 200 GeoJSON):**
```json
{
  "status": "success",
  "profile": "motorcycle",
  "costing": "motorcycle",
  "summary": {
    "distance_km": 146.85,
    "duration_seconds": 12840,
    "duration_formatted": "3j 34m"
  },
  "geometry": {
    "type": "LineString",
    "coordinates": [
      [106.845601, -6.208812],
      [106.845920, -6.209140],
      [107.619080, -6.917490]
    ]
  },
  "steps": [
    {
      "instruction": "Lanjutkan ke Jalan Tebet Barat Dalam.",
      "distance_km": 0.45,
      "duration_sec": 42,
      "street_names": ["Jalan Tebet Barat Dalam"]
    },
    {
      "instruction": "Belok kanan ke Jalan Raya Pasar Minggu.",
      "distance_km": 1.2,
      "duration_sec": 110,
      "street_names": ["Jalan Raya Pasar Minggu"]
    }
  ]
}
```

---

## 3. Contoh Integrasi Client

### A. Integrasi Flutter (Dart)

```dart
import 'dart:convert';
import 'package:http/http.dart' as http;

class MapsService {
  static const String baseUrl = 'http://192.168.1.100:8080/api/v1';

  // 1. Pencarian Alamat / POI
  static Future<List<Map<String, dynamic>>> searchPlaces(String query) async {
    final uri = Uri.parse('$baseUrl/search?q=${Uri.encodeComponent(query)}&limit=5');
    final response = await http.get(uri);
    if (response.statusCode == 200) {
      final data = jsonDecode(response.body);
      return List<Map<String, dynamic>>.from(data['features']);
    }
    throw Exception('Gagal mencari alamat: ${response.statusCode}');
  }

  // 2. Navigasi Rute (Motor / Mobil / Pejalan Kaki)
  static Future<Map<String, dynamic>> calculateRoute({
    required double startLat,
    required double startLon,
    required double endLat,
    required double endLon,
    String profile = 'motorcycle', // 'motorcycle', 'auto', 'pedestrian'
  }) async {
    final uri = Uri.parse('$baseUrl/route');
    final response = await http.post(
      uri,
      headers: {'Content-Type': 'application/json'},
      body: jsonEncode({
        'profile': profile,
        'locations': [
          {'lat': startLat, 'lon': startLon},
          {'lat': endLat, 'lon': endLon},
        ],
      }),
    );

    if (response.statusCode == 200) {
      return jsonDecode(response.body);
    }
    throw Exception('Gagal menghitung rute');
  }
}
```

---

### B. Integrasi Python / Django

```python
import requests

MAPS_GATEWAY_URL = "http://localhost:8080/api/v1"

def get_driving_distance(origin_coords, dest_coords, vehicle="motorcycle"):
    """
    origin_coords: (lat, lon)
    dest_coords: (lat, lon)
    vehicle: 'motorcycle' | 'auto' | 'pedestrian'
    """
    payload = {
        "profile": vehicle,
        "locations": [
            {"lat": origin_coords[0], "lon": origin_coords[1]},
            {"lat": dest_coords[0], "lon": dest_coords[1]}
        ]
    }
    resp = requests.post(f"{MAPS_GATEWAY_URL}/route", json=payload, timeout=5)
    resp.raise_for_status()
    data = resp.json()
    return {
        "distance_km": data["summary"]["distance_km"],
        "duration_min": round(data["summary"]["duration_seconds"] / 60, 1),
        "polyline": data["geometry"]["coordinates"]
    }
```

---

### C. Menampilkan MapLibre GL di Web / Frontend

```javascript
const map = new maplibregl.Map({
    container: 'map',
    style: {
        version: 8,
        sources: {
            'java-tiles': {
                type: 'vector',
                url: 'http://localhost:8080/tiles/java' // Martin PMTiles source
            }
        },
        layers: [
            {
                id: 'background',
                type: 'background',
                paint: { 'background-color': '#0f172a' }
            },
            {
                id: 'roads',
                type: 'line',
                source: 'java-tiles',
                'source-layer': 'transportation',
                paint: { 'line-color': '#475569', 'line-width': 1.5 }
            }
        ]
    },
    center: [110.36, -7.30],
    zoom: 7
});
```
