# PANDUAN INTEGRASI API: PLATFORM LOGISTIK & E-COMMERCE
**Jawa Maps Lite — Central Maps Services untuk Aplikasi Belanja, Ekspedisi, & Kurir**

Dokumen ini adalah panduan teknis bagi tim pengembang (**Backend Developer, Mobile Developer Flutter/React Native, & Web Developer**) untuk mengintegrasikan layanan **Jawa Maps Lite** ke dalam sistem e-commerce, kurir instan, ekspedisi kargo, atau manajemen gudang.

---

## 1. Arsitektur Alur E-Commerce & Logistik

```
1. Pembeli Mengetik Alamat               2. Pembeli Geser Pin Peta
   GET /api/v1/autocomplete?q=...           GET /api/v1/reverse?lat=...&lon=...
              │                                        │
              ▼                                        ▼
┌───────────────────────────┐            ┌───────────────────────────┐
│ Form Checkout E-Commerce  │            │ Titik Jemput / Titik Kirim│
│ (Nama Jalan, Kota, Lat/Lon│            │ Presisi di Peta           │
└─────────────┬─────────────┘            └─────────────┬─────────────┘
              │                                        │
              └───────────────────┬────────────────────┘
                                  ▼
3. Hitung Jarak & Ongkir Pengiriman (Checkout / Keranjang)
   POST /api/v1/route
   - Motor (Instan / Sameday): avoids tolls
   - Mobil / Kargo (Ekspedisi): uses tolls
                                  │
                                  ▼
4. Kurir Mengantar & Live Tracking Pembeli
   - Render rute GeoJSON LineString di peta aplikasi mobile
   - Panduan belokan jalan (turn-by-turn steps)
```

---

## 2. Kasus Penggunaan 1: Pencarian Alamat & Autocomplete Checkout

Saat pembeli mengetik alamat di formulir checkout aplikasi mobile atau web, gunakan endpoint ini dengan jeda (*debounce*) 200–300 ms.

### Endpoint:
```http
GET /api/v1/autocomplete?q={kata_kunci}&limit={jumlah_hasil}
```

### Contoh Request:
```http
GET /api/v1/autocomplete?q=Gedung+Sate&limit=3 HTTP/1.1
Host: localhost:8080
```

### Contoh Response (GeoJSON):
```json
{
  "type": "FeatureCollection",
  "query": "Gedung Sate",
  "count": 1,
  "features": [
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [107.6188, -6.9015]
      },
      "properties": {
        "name": "Gedung Sate",
        "label": "Gedung Sate, Kota Bandung, Jawa Barat, Indonesia",
        "category": "tourism",
        "city": "Kota Bandung",
        "province": "Jawa Barat",
        "country": "Indonesia",
        "lat": -6.9015,
        "lon": 107.6188
      }
    }
  ]
}
```

> **Tips Implementasi Frontend**: Simpan nilai `lat` dan `lon` ke dalam database pesanan (*orders table*) untuk digunakan pada perhitungan jarak & ongkir di backend.

---

## 3. Kasus Penggunaan 2: Pinpoint Lokasi Peta (Reverse Geocoding)

Saat pengguna menggeser pin di peta untuk menandai rumah atau gerbang masuk secara presisi.

### Endpoint:
```http
GET /api/v1/reverse?lat={latitude}&lon={longitude}
```

### Contoh Request:
```http
GET /api/v1/reverse?lat=-6.1754&lon=106.8271 HTTP/1.1
Host: localhost:8080
```

### Contoh 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",
        "label": "Monumen Nasional, Kota Jakarta Pusat, DKI Jakarta",
        "city": "Kota Jakarta Pusat",
        "province": "DKI Jakarta"
      }
    }
  ]
}
```

---

## 4. Kasus Penggunaan 3: Hitung Jarak & Ongkir (Delivery Fee Calculation)

Backend e-commerce memanggil endpoint ini untuk menghitung jarak nyata jaringan jalan (*driving road distance*), bukan jarak garis lurus (*as-the-crow-flies*).

### Endpoint:
```http
POST /api/v1/route
Content-Type: application/json
```

### Pilihan Profil Kendaraan Logistik:
| Profile | Jenis Armada | Karakteristik Tol di Indonesia |
|---|---|---|
| `"motorcycle"` / `"motor"` | Kurir Motor, Instan, Sameday | **Menghindari Jalan Tol** (`use_tolls: 0.0`) sesuai regulasi jalan tol Indonesia. |
| `"auto"` / `"mobil"` | Mobil Box, Van, Truk Kargo | **Memanfaatkan Jalan Tol** (`use_tolls: 0.8`) seperti Tol Trans-Jawa, Tol Cipularang, Tol Dalam Kota. |
| `"pedestrian"` | Pengantaran Dekat / Cluster | Jalur setapak dan trotoar. |

### Contoh Request Payload:
```json
{
  "profile": "motorcycle",
  "locations": [
    {
      "lat": -6.2088,
      "lon": 106.8456
    },
    {
      "lat": -6.9175,
      "lon": 107.6191
    }
  ]
}
```

### Contoh Response Payload:
```json
{
  "status": "success",
  "profile": "motorcycle",
  "costing": "motorcycle",
  "summary": {
    "distance_km": 163.65,
    "duration_seconds": 7977,
    "duration_formatted": "2j 12m"
  },
  "geometry": {
    "type": "LineString",
    "coordinates": [
      [106.845653, -6.208629],
      [106.845699, -6.208643],
      [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"]
    }
  ]
}
```

---

## 5. Contoh Kode Implementasi Nyata

### A. Backend PHP / Laravel (Service Ongkos Kirim)

```php
<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Exception;

class CentralMapsService
{
    protected string $baseUrl;

    public function __construct()
    {
        // Sesuaikan IP server Jawa Maps Lite Anda
        $this->baseUrl = config('services.maps.url', 'http://127.0.0.1:8080/api/v1');
    }

    /**
     * Hitung ongkos kirim berdasarkan jarak nyata jalan
     *
     * @param float $originLat Latitude Toko/Gudang
     * @param float $originLon Longitude Toko/Gudang
     * @param float $destLat   Latitude Pembeli
     * @param float $destLon   Longitude Pembeli
     * @param string $fleet    'motorcycle' atau 'auto'
     * @return array
     */
    public function calculateShippingCost(float $originLat, float $originLon, float $destLat, float $destLon, string $fleet = 'motorcycle'): array
    {
        $response = Http::timeout(5)->post("{$this->baseUrl}/route", [
            'profile' => $fleet,
            'locations' => [
                ['lat' => $originLat, 'lon' => $originLon],
                ['lat' => $destLat, 'lon' => $destLon],
            ]
        ]);

        if ($response->failed()) {
            throw new Exception("Gagal menghitung rute: " . $response->body());
        }

        $data = $response->json();
        $distanceKm = $data['summary']['distance_km'];
        $durationFormatted = $data['summary']['duration_formatted'];

        // Formula Tarif Pengiriman (Contoh: Kurir Instan Motor)
        // Tarif dasar 4 km pertama = Rp 10.000, selanjutnya Rp 2.500 per km
        $baseFare = 10000;
        $perKmRate = ($fleet === 'motorcycle') ? 2500 : 5000;
        
        $shippingCost = $baseFare;
        if ($distanceKm > 4) {
            $shippingCost += ceil($distanceKm - 4) * $perKmRate;
        }

        return [
            'distance_km' => $distanceKm,
            'duration' => $durationFormatted,
            'shipping_cost' => $shippingCost,
            'route_polyline' => $data['geometry']['coordinates']
        ];
    }
}
```

---

### B. Backend Python (Django / FastAPI / Celery)

```python
import requests

MAPS_API_URL = "http://127.0.0.1:8080/api/v1"

def get_delivery_quote(warehouse_lat: float, warehouse_lon: float, 
                       customer_lat: float, customer_lon: float, 
                       is_cargo: bool = False) -> dict:
    """
    Menghitung estimasi ongkir dan waktu pengiriman e-commerce.
    """
    profile = "auto" if is_cargo else "motorcycle"
    
    payload = {
        "profile": profile,
        "locations": [
            {"lat": warehouse_lat, "lon": warehouse_lon},
            {"lat": customer_lat, "lon": customer_lon}
        ]
    }
    
    resp = requests.post(f"{MAPS_API_URL}/route", json=payload, timeout=5)
    resp.raise_for_status()
    data = resp.json()
    
    distance = data["summary"]["distance_km"]
    duration = data["summary"]["duration_formatted"]
    
    # Skema tarif ekspedisi
    if is_cargo:
        # Kargo Mobil/Box: Tarif dasar Rp 35.000 + Rp 4.000/km
        ongkir = 35000 + int(distance * 4000)
    else:
        # Kurir Motor: Tarif dasar Rp 8.000 + Rp 2.200/km
        ongkir = 8000 + int(distance * 2200)
        
    return {
        "status": "success",
        "fleet": profile,
        "distance_km": distance,
        "estimated_arrival": duration,
        "shipping_fee_idr": ongkir,
        "polyline": data["geometry"]["coordinates"]
    }
```

---

### C. Mobile App Flutter (Dart) — Address Picker & Kurir Tracking

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

class LogisticsMapsService {
  static const String apiBase = 'http://192.168.1.100:8080/api/v1';

  // 1. Autocomplete Alamat saat input form checkout
  static Future<List<Map<String, dynamic>>> searchAddress(String query) async {
    final res = await http.get(Uri.parse('$apiBase/autocomplete?q=${Uri.encodeComponent(query)}&limit=5'));
    if (res.statusCode == 200) {
      final json = jsonDecode(res.body);
      return List<Map<String, dynamic>>.from(json['features']);
    }
    return [];
  }

  // 2. Reverse Geocoding saat geser pin peta
  static Future<String> getAddressFromPin(double lat, double lon) async {
    final res = await http.get(Uri.parse('$apiBase/reverse?lat=$lat&lon=$lon'));
    if (res.statusCode == 200) {
      final json = jsonDecode(res.body);
      final features = json['features'] as List;
      if (features.isNotEmpty) {
        return features[0]['properties']['label'] ?? 'Alamat ditemukan';
      }
    }
    return 'Alamat tidak diketahui';
  }

  // 3. Ambil rute jalan untuk navigasi kurir dan live tracking
  static Future<Map<String, dynamic>> getDriverRoute({
    required double originLat,
    required double originLon,
    required double destLat,
    required double destLon,
    bool isMotorcycle = true,
  }) async {
    final res = await http.post(
      Uri.parse('$apiBase/route'),
      headers: {'Content-Type': 'application/json'},
      body: jsonEncode({
        'profile': isMotorcycle ? 'motorcycle' : 'auto',
        'locations': [
          {'lat': originLat, 'lon': originLon},
          {'lat': destLat, 'lon': destLon},
        ]
      }),
    );

    if (res.statusCode == 200) {
      return jsonDecode(res.body);
    }
    throw Exception('Gagal memuat rute pengiriman');
  }
}
```

---

## 6. Menampilkan Peta Vector Offline di Aplikasi

Untuk menampilkan peta dasar (*basemap*) Pulau Jawa tanpa bayar biaya Mapbox/Google Maps:

### Format URL Martin Vector Tiles:
```
http://<SERVER_IP>:8080/tiles/java/{z}/{x}/{y}
```

### Contoh Konfigurasi MapLibre GL JS / Web:
```javascript
const map = new maplibregl.Map({
    container: 'map',
    style: {
        version: 8,
        sources: {
            'java-tiles': {
                type: 'vector',
                tiles: ['http://localhost:8080/tiles/java/{z}/{x}/{y}']
            }
        },
        layers: [
            {
                id: 'background',
                type: 'background',
                paint: { 'background-color': '#0f172a' }
            },
            {
                id: 'roads',
                type: 'line',
                source: 'java-tiles',
                'source-layer': 'transportation',
                paint: { 'line-color': '#38bdf8', 'line-width': 2 }
            }
        ]
    },
    center: [106.8456, -6.2088], // Jakarta
    zoom: 12
});
```

---

## 7. Keunggulan untuk Bisnis Logistik & E-Commerce

1. **Hemat Biaya 100%**: Tidak ada tagihan bulanan Google Maps API (Google Distance Matrix API seharga \$5 per 1.000 call, Geocoding seharga \$5 per 1.000 call). Dengan Jawa Maps Lite, **jutaan hit API gratis seumur hidup**.
2. **Kecepatan Latensi Lokal**: Response routing dan pencarian alamat selesai dalam **5–20 milidetik** karena server berjalan di jaringan lokal / cloud VPS mandiri.
3. **Privasi & Keamanan Data Pelanggan**: Alamat rumah pelanggan dan riwayat pengiriman barang tidak pernah dikirim ke pihak ketiga atau server asing.
4. **Kesesuaian Regulasi Lokal**: Rute motor otomatis tidak akan mengarahkan kurir masuk jalan tol (mengeliminasi komplain kurir kesasar di pintu tol).
