Gọi API ma trận
sources là các kho, targets là điểm giao; costing chọn loại phương tiện (auto là ô tô).
curl 'https://cloud.gmap.vn/api/tsp/route/sources_to_targets' \
--header 'x-api-key: public-gmap-cloud-x-api-key-demo' \
--header 'content-type: application/json' \
--data '{
"sources": [{ "lat": 21.0285, "lon": 105.8542 }, { "lat": 21.0367, "lon": 105.8352 }],
"targets": [{ "lat": 21.015, "lon": 105.847 }],
"costing": "auto"
}'| Kho | Thời gian | Quãng đường |
|---|---|---|
| Hoàn Kiếm (21.0285, 105.8542) | 302 giây (~5 phút) | 2,733 km |
| Ba Đình (21.0367, 105.8352) | 319 giây (~5,3 phút) | 3,428 km |
sources_to_targets[i][j] là kết quả từ kho thứ i tới điểm giao thứ j; time tính bằng giây, distance theo units (kilometers).
Chọn kho trong JavaScript
const warehouses = [
{ name: 'Hoàn Kiếm', lat: 21.0285, lon: 105.8542 },
{ name: 'Ba Đình', lat: 21.0367, lon: 105.8352 },
];
const order = { lat: 21.015, lon: 105.847 };
const response = await fetch(
'https://cloud.gmap.vn/api/tsp/route/sources_to_targets?x-api-key=public-gmap-cloud-x-api-key-demo',
{
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
sources: warehouses.map(({ lat, lon }) => ({ lat, lon })),
targets: [order],
costing: 'auto',
}),
},
);
const { sources_to_targets: rows } = await response.json();
const nearest = rows
.map(([cell], index) => ({ ...warehouses[index], minutes: cell.time / 60, km: cell.distance }))
.sort((a, b) => a.minutes - b.minutes)[0];
// → Hoàn Kiếm, ~5 minutes, 2.733 kmLưu ý
- Thời gian là ước tính theo mô hình định tuyến, chưa gồm giao thông thời gian thực.
- Gom nhiều đơn vào một yêu cầu (nhiều targets) để giảm số lần gọi.
- Với chuyến giao nhiều điểm, dùng API tối ưu thứ tự điểm sau khi đã chọn kho.


