# VIETMAP Maps API - full reference for LLMs > Generated at build time from the agent integration guides in docs/assets/agents/. Index: https://maps.vietmap.vn/docs/llms.txt Every request needs an `apikey`: the services key for the Map APIs (call them from your backend), the tilemap key to render the base map. Register at https://maps.vietmap.vn/console-v2/register Contents: 1. VIETMAP Search & Geocoding APIs — Agent Integration Guide (also at https://maps.vietmap.vn/docs/assets/agents/search-geocoding.txt) 2. VIETMAP Routing APIs — Agent Integration Guide (also at https://maps.vietmap.vn/docs/assets/agents/routing.txt) 3. VIETMAP Logistics APIs — Agent Integration Guide (also at https://maps.vietmap.vn/docs/assets/agents/logistics.txt) 4. VIETMAP Address Migration API (Data Tools) — Agent Integration Guide (also at https://maps.vietmap.vn/docs/assets/agents/data-tools.txt) 5. VietMap Map Display — Agent Integration Guide (also at https://maps.vietmap.vn/docs/assets/agents/map-display.txt) 6. VIETMAP Console, API Keys & Pricing — Agent Integration Guide (also at https://maps.vietmap.vn/docs/assets/agents/console.txt) --- # VIETMAP Search & Geocoding APIs — Agent Integration Guide > **APIs covered:** Autocomplete v4 · Geocode v4 (`/api/search/v4`, also called Search v4) · Place v4 · Reverse v4 > **Auth:** API key required, sent as the `apikey` query parameter — use your **services key** (the tilemap key is for map rendering only). Register at https://maps.vietmap.vn/console-v2/register (60,000 free transactions, about 3,000,000 VND). > **⚠️ Security:** All API calls MUST be made from your **backend server**. NEVER expose your API key in frontend/client-side code. > **💬 Need help?** Contact VietMap via Zalo OA: https://zalo.me/3189066936017422854 ## Quick Summary Everything about **"find this address / POI"** and **"what's at these coordinates"** in Vietnam. All four endpoints are `GET` and return JSON. Autocomplete and Geocode match addresses written in both the old 3-level (ward, district, province) and the new 2-level (ward, province) administrative format, and every API can answer in either format. | API | Input | Output | Use when | |---------------------|-------------------------------|------------------------------------------|----------| | **Autocomplete v4** | Partial text + `focus` | Up to 10 suggestions, each with `ref_id` | Type-ahead (user still typing) | | **Geocode v4** | Complete address string | Up to 10 candidates, each with `ref_id` | One-call lookup of a whole address, e.g. an address pasted from elsewhere | | **Place v4** | `refid` (a `ref_id` from the two APIs above) | `lat`/`lng` + address parts (house number, street, ward, province) | User picked a result → coordinates for map, routing, order | | **Reverse v4** | `lat` + `lng` | Nearest address(es), each with `lat`/`lng` | Map pin, GPS point → address | Each request to any of these four APIs counts as **1 transaction**. ### Recommended interactive flow ``` Type-ahead: Autocomplete v4 (debounced, as user types) → user picks → Place v4 (refid) → lat/lng + address parts Full string: Geocode v4 (complete address) → Place v4 with the chosen ref_id → lat/lng Coord→Addr: Reverse v4 → nearest address; each result already carries lat/lng ``` ### Autocomplete best practices **Always pass `focus` = user's current coordinates (`lat,lng`, latitude first).** This is the single most impactful parameter for result quality: it ranks places near the user first, so a search for "Cà phê" in Ho Chi Minh City returns Ho Chi Minh City places. Without `focus`, ranking uses text relevance only. - Mobile: pass the device's latest GPS `lat,lng`. - Web: pass the map's current center or the browser Geolocation result. - Fallback: if device location is unavailable, use IP-based coordinates from your infrastructure's GeoIP service, formatted as `lat,lng` (latitude first). IP coordinates are approximate and less accurate than device location: - Cloudflare: enable the "Add visitor location headers" Managed Transform to receive `cf-iplatitude` and `cf-iplongitude` on requests to your server. - AWS CloudFront: configure CloudFront to include `CloudFront-Viewer-Latitude` and `CloudFront-Viewer-Longitude` in requests sent to your origin. - Vercel: read `X-Vercel-IP-Latitude` and `X-Vercel-IP-Longitude` (available in Vercel Functions). **Debounce `text` at 200–300 ms.** Call on each input change, debounced — this saves transactions and keeps the UI responsive. Send at least **2 characters**. Cancel the previous in-flight request before sending a new one (`AbortController` on web, cancel tokens on mobile). **Use `display_type=5` (recommended default).** New 2-level format as the main result, old 3-level format in `data_old` — both formats in one response. `6` is the mirror image: old format as the main result, new format in `data_new`. **Call Place v4 once, on selection only.** Each Place v4 call is 1 transaction; resolve only the row the user taps, not every suggestion in the list. **Show `display` to the user; pass `ref_id` verbatim to Place v4.** `ref_id` is an opaque token with a prefix — pass it verbatim, prefix included. **Optional hardening:** encode `ref_id` on your server before sending suggestions to the client; when the user selects one, the client sends the encoded value back, your server decodes it and calls Place v4. This keeps your Place endpoint protected from abuse. --- ## 1. Autocomplete v4 (type-ahead) ### Endpoint ``` GET https://maps.vietmap.vn/api/autocomplete/v4?apikey={apikey}&text={text}&focus={lat,lng}&display_type=5 ``` ### Core Parameters | Parameter | Type | Required | Description | |---------------|---------|-----------------|-------------| | apikey | string | yes | Your VietMap services key | | text | string | yes | Text the user has typed so far. Send at least 2 characters. | | focus | string | no (recommended)| User's location as `lat,lng` (latitude first). Ranks nearby results first; omitted = ranking by text match only. | | display_type | number | no (recommended)| Address format of the response: `1`, `2`, `3`, `5`, `6`. **Use `5`.** See §5. | ### Filter parameters (optional) | Parameter | Type | Description | |---------------|---------|-------------| | layers | string | Restrict result types. Allowed: `POI`, `ADDRESS`, `VILLAGE`, `WARD`, `DIST`, `CITY`, `STREET`. Omit to search all types. | | cityId | number | Only results inside this province/city, e.g. `12` | | distId | number | Only results inside this district, e.g. `1292` | | wardId | number | Only results inside this ward, e.g. `984332` | | admin_new | boolean | `true` = new administrative boundaries, `false` = old. Applies only together with `cityId` / `distId` / `wardId`. Example: `cityId=12&admin_new=false` returns only results inside the old Ho Chi Minh City boundary (no Binh Duong, no Vung Tau). | | circle_center | string | Center of a circular search area, `lat,lng`. Use with `circle_radius`. | | circle_radius | number | Radius of that circle in **meters**, e.g. `200` | | cats | string | POI category code(s) to filter by, e.g. `1002-1` | Administrative IDs for `cityId` / `distId` / `wardId`: https://github.com/vietmap-company/vietnam_administrative_address ### Request ``` GET https://maps.vietmap.vn/api/autocomplete/v4?apikey={apikey}&text=197 tran phu&focus=10.75887508,106.67538868&display_type=5 ``` URL-encode every query value (spaces, commas, Vietnamese diacritics), e.g. with `URLSearchParams`, Python `requests` `params=`, or `curl -G --data-urlencode`. ### Response — `Array` (up to 10, `display_type=5`) ```json [ { "ref_id": "auto:RAkPcicmZ3d-NQhac2kADHYlbFAkBiEeAQAkCVcMURChqPDS09-oXQRCYUDM3JU...", "distance": 0.06911172534949989, "address": "Phường Chợ Quán,Thành Phố Hồ Chí Minh", "name": "197 Trần Phú", "display": "197 Trần Phú Phường Chợ Quán,Thành Phố Hồ Chí Minh", "boundaries": [ { "type": 2, "id": 18700, "name": "Chợ Quán", "prefix": "Phường", "full_name": "Phường Chợ Quán" }, { "type": 0, "id": 12, "name": "Hồ Chí Minh", "prefix": "Thành Phố", "full_name": "Thành Phố Hồ Chí Minh" } ], "categories": [], "entry_points": [], "data_new": null, "data_old": { "ref_id": "auto:RAkPcicmZ3d-NQhac2kADHYlbFAkBiEeAQAkCV0EXwdF_KakgoWOrg0FFWZfh4j...", "distance": 0.06911172534949989, "address": "Phường 4,Quận 5,Thành Phố Hồ Chí Minh", "name": "197 Trần Phú", "display": "197 Trần Phú Phường 4,Quận 5,Thành Phố Hồ Chí Minh", "boundaries": [ { "type": 2, "id": 656652, "name": "4", "prefix": "Phường", "full_name": "Phường 4" }, { "type": 1, "id": 1292, "name": "5", "prefix": "Quận", "full_name": "Quận 5" }, { "type": 0, "id": 12, "name": "Hồ Chí Minh", "prefix": "Thành Phố", "full_name": "Thành Phố Hồ Chí Minh" } ], "categories": [], "entry_points": [], "data_new": null, "data_old": null } } ] ``` (`ref_id` values shortened here; real values are longer. With `display_type=6` the main object is the old format and the new format sits in `data_new`.) ### Response Fields | Field | Type | Description | |--------------|--------------|-------------| | ref_id | string | Opaque place ID with a prefix. Pass verbatim, prefix included, as `refid` to Place v4 for coordinates and address details. | | distance | number | Distance from `focus`, in **kilometers** | | address | string | Administrative part only: ward, district (old format only), province. House number and street are in `name`; full address is in `display`. | | name | string | POI name, or house number + street for an address result (e.g. `197 Trần Phú`) | | display | string | `name` + `address` in one string — use as the user-facing label | | boundaries | Boundary[] | Administrative units, smallest first (ward → district → province) | | categories | string[] | POI category codes | | entry_points | EntryPoint[] | Entrances of the POI; empty array if none. Present mainly for airports, hotels and malls. | | data_old | object\|null | Same result in the old 3-level format. Populated for `display_type=5`; otherwise `null`. | | data_new | object\|null | Same result in the new 2-level format. Populated for `display_type=6`; otherwise `null`. | **Boundary**: `type` (`0` = province/city, `1` = district, `2` = ward), `id`, `name` (without prefix, e.g. `4`), `prefix` (e.g. `Phường`, `Quận`, `Thành Phố`), `full_name` (e.g. `Phường 4`). The new 2-level format has no `type=1` entry. **EntryPoint**: `ref_id`, `name`. Pass an entry point's `ref_id` to Place v4 to get its coordinates. **data_old / data_new** objects carry the same fields: `ref_id`, `distance`, `address`, `name`, `display`, `boundaries`, `categories`, `entry_points`. Each has its own `ref_id`; Place v4 answers in the format of the object the `ref_id` came from. Autocomplete v4 returns a `ref_id` per result; call Place v4 with it to get `lat`/`lng` and address components. --- ## 2. Geocode v4 (forward geocode, complete address string) Geocode v4 takes a complete address string (house number, street, ward, province — e.g. `197 Trần Phú, phường 4, quận 5, TP.HCM`) and returns up to 10 matching places, each with a `ref_id`, a normalized address and its administrative units. Call Place v4 with the chosen `ref_id` to get `lat`/`lng`. For text the user is still typing, use Autocomplete v4. ### Endpoint ``` GET https://maps.vietmap.vn/api/search/v4?apikey={apikey}&text={text}&focus={lat,lng}&display_type=5 ``` ### Parameters | Parameter | Type | Required | Description | |---------------|---------|-----------------|-------------| | apikey | string | yes | Your VietMap services key | | text | string | yes | Complete address string to geocode | | focus | string | no (recommended)| `lat,lng` (latitude first). Ranks nearby results first; omitted = ranking by text match only. | | display_type | number | no (recommended)| `1`, `2`, `3`, `5`, `6`. **Use `5`.** See §5. | Same optional filters as Autocomplete v4: `layers`, `cityId`, `distId`, `wardId`, `admin_new`, `circle_center`, `circle_radius`, `cats` (identical meaning and values). ### Request ``` GET https://maps.vietmap.vn/api/search/v4?apikey={apikey}&text=197 Trần Phú, phường 4, quận 5, thành phố Hồ Chí Minh&focus=10.75887508,106.67538868&display_type=5 ``` ### Response `Array`, up to 10 items, best match first. Same fields and shape as Autocomplete v4 (`ref_id`, `distance`, `address`, `name`, `display`, `boundaries`, `categories`, `entry_points`, `data_old`, `data_new`). An empty array means no match. --- ## 3. Reverse v4 (coordinates → address) ### Endpoint ``` GET https://maps.vietmap.vn/api/reverse/v4?apikey={apikey}&lat={lat}&lng={lng}&display_type=1 ``` ### Parameters | Parameter | Type | Required | Description | |--------------|--------|----------|-------------| | apikey | string | yes | Your VietMap services key | | lat | number | yes | Latitude of the point, e.g. `10.759221` | | lng | number | yes | Longitude of the point, e.g. `106.675901` | | display_type | number | no | `1`, `2`, `4`, `5`, `6`. Omitted or `1` = new 2-level format. `5` adds the old format in `data_old`. See §5. | ### Request ``` GET https://maps.vietmap.vn/api/reverse/v4?apikey={apikey}&lat=10.759221&lng=106.675901&display_type=5 ``` ### Response — `Array` (`display_type=5`) ```json [ { "lat": 10.759221, "lng": 106.675901, "ref_id": "vm:ADDRESS:MM03541B04565B07001C5D035204030202005A1D535A01321F...", "distance": 0, "address": "Phường Chợ Quán,Thành Phố Hồ Chí Minh", "name": "197 Trần Phú", "display": "197 Trần Phú Phường Chợ Quán,Thành Phố Hồ Chí Minh", "boundaries": [ { "type": 2, "id": 18700, "name": "Chợ Quán", "prefix": "Phường", "full_name": "Phường Chợ Quán" }, { "type": 0, "id": 12, "name": "Hồ Chí Minh", "prefix": "Thành Phố", "full_name": "Thành Phố Hồ Chí Minh" } ], "categories": [], "entry_points": [], "data_old": { "lat": 10.759221, "lng": 106.675901, "ref_id": "vm:ADDRESS:MM03541B04565B07001C5D035204030202005A1D535A01321F...", "distance": 0, "address": "Phường 4,Quận 5,Thành Phố Hồ Chí Minh", "name": "197 Trần Phú", "display": "197 Trần Phú Phường 4,Quận 5,Thành Phố Hồ Chí Minh", "boundaries": [ ... 3 entries: ward (type 2), district (type 1), province (type 0) ... ], "categories": [], "entry_points": [], "data_old": null, "data_new": null }, "data_new": null } ] ``` ### Response Fields | Field | Type | Description | |--------------|--------------|-------------| | lat, lng | number | Coordinates of the result — use them directly | | ref_id | string | Reference ID of the location | | distance | number | Distance from the query point, in **kilometers** | | address | string | Administrative part: ward + province (new format); ward + district + province (old format). House number and street are in `name`; full address is in `display`. | | name | string | Name of the location or street address | | display | string | `name` + `address` in one string | | boundaries | Boundary[] | Same schema as Autocomplete v4 | | categories | array | Categories of the location | | entry_points | EntryPoint[] | `ref_id`, `name`; pass an entry point's `ref_id` to Place v4 for its details | | data_old | object\|null | Old 3-level variant (same fields incl. `lat`/`lng`). Populated only when `display_type=5`. | | data_new | object\|null | New 2-level variant (same fields incl. `lat`/`lng`). Populated only when `display_type=6`. | With `display_type=4` the array holds two items for the same location: the new-format item first, then the old-format item. --- ## 4. Place v4 (ref_id → lat/lng + details) ### Endpoint ``` GET https://maps.vietmap.vn/api/place/v4?apikey={apikey}&refid={ref_id} ``` ### Parameters | Parameter | Type | Required | Description | |-----------|--------|----------|-------------| | apikey | string | yes | Your VietMap services key | | refid | string | yes | The `ref_id` from an Autocomplete v4 or Geocode v4 result (or one of its `entry_points`), **verbatim including its `auto:` / `geocode:` prefix**. | ### Request ``` GET https://maps.vietmap.vn/api/place/v4?apikey={apikey}&refid=auto:RAkPcicmZ3d-NQhac2kADHYlbFAkBiEeAQAkCV0EXwdF_KakgoWOrg0FFWZfh4jFXA1kXfbZFlNRGFUYCAJXAF8BUQBVCAZUC18EA1VMAwUYXwJQBBQFBQVTHVFacANBQlU ``` ### Response — single JSON object ```json { "display": "197 Đường Trần Phú,Phường Chợ Quán,Thành Phố Hồ Chí Minh", "name": "", "hs_num": "197", "street": "Đường Trần Phú", "address": "197 Đường Trần Phú", "city_id": 12, "city": "Thành Phố Hồ Chí Minh", "district_id": 0, "district": "", "ward_id": 18700, "ward": "Phường Chợ Quán", "lat": 10.759222947000069, "lng": 106.67590269100003 } ``` | Field | Type | Description | |-------------|--------|-------------| | display | string | Full formatted address — use as user-facing label | | name | string | POI name. Empty string for a plain street address. | | hs_num | string | House / building number | | street | string | Street name with its prefix (e.g. `Đường Trần Phú`) | | address | string | House number + street (`hs_num` + `street`) | | city_id | int | Province/city ID | | city | string | Province/city name | | district_id | int | District ID for an old-format `ref_id`; `0` for a new-format `ref_id` | | district | string | District name for an old-format `ref_id`; `""` for a new-format `ref_id` | | ward_id | int | Ward ID | | ward | string | Ward name | | lat, lng | number | Coordinates of the place | The response uses the same administrative format as the result the `refid` came from: a `ref_id` from a new-format (2-level) result returns `district_id: 0` and `district: ""`; a `ref_id` from an old-format (3-level) result (e.g. `data_old.ref_id`) returns all three levels. --- ## 5. `display_type` cheat-sheet | Value | Label | Description | Autocomplete / Geocode | Reverse | |------:|-----------------------|-------------|:---:|:---:| | 1 | New format | New merged 2-level format (ward, province) | ✓ | ✓ (default) | | 2 | Old format | Old 3-level format (ward, district, province) | ✓ | ✓ | | 3 | As input format | Detects whether `text` is old or new format and answers in that same format | ✓ | — | | 4 | Both, as two items | One new-format item and one old-format item in the list | — | ✓ | | **5** | **Both, new primary** | **New format as main object, old format in `data_old` (recommended)** | ✓ | ✓ | | 6 | Both, old primary | Old format as main object, new format in `data_new` | ✓ | ✓ | `data_old` / `data_new` are populated only for `5` / `6`; for every other value they are `null` (treat a missing field as `null`). The new 2-level format has no district (`boundaries` has no `type=1` entry). --- ## 6. Errors & status codes Autocomplete, Geocode, Place and Reverse v4 report errors through the HTTP status. | HTTP | Meaning | Body | What to do | |-------|---------|------|------------| | `200` | Success | JSON (array; Place v4: object). An empty array = no match. | — | | `400` | A parameter is missing or malformed | — | Fix the request; compare with the examples above | | `401` | API key missing, wrong or unknown | **Empty** | Check the `apikey` value and that the whole services key was copied | | `423` | Quota used up, the API is not enabled for this key, or a tilemap key was used | **Plain text**, e.g. `Your request is limited` | Check usage in the Console (Monitor API key usage), enable the API for the key (Manage API key), and call with the services key | | `429` | Too many requests in a short time | — | Wait and retry, lengthening the wait each time (1 s, 2 s, 4 s) | | `500` | Server error | — | Retry later; contact support if it persists | Read the status **before** parsing JSON — `401` and `423` bodies are not JSON. Quota behaviour behind `423`: on a Trial account each API serves 500 requests a day and resumes the next day (Autocomplete has no daily cap); a Standard account runs until its total quota is used; an Enterprise account pauses for the rest of the day when the daily quota reaches 100%. --- ## 7. Transactions (billing) | API | Requests | Transactions | |-----------------|---------:|-------------:| | Autocomplete v4 | 1 | 1 | | Geocode v4 | 1 | 1 | | Place v4 | 1 | 1 | | Reverse v4 | 1 | 1 | Keep usage efficient: debounce Autocomplete (≥ 2 characters, 200–300 ms), call Place v4 once per selection, and use the `lat`/`lng` already present in Reverse v4 results. --- ## Integration Flow ### Address field with suggestions (checkout, delivery address) ``` 1. User types → frontend sends text to YOUR backend (≥ 2 chars, after 300 ms idle) 2. Backend calls Autocomplete v4 with text + focus + display_type=5 3. Backend returns [{ref_id, display}] → frontend renders the list (show `display`) 4. User selects a row → frontend sends its ref_id to YOUR backend 5. Backend calls Place v4 with refid → display, lat, lng, hs_num, street, ward_id, ward, city_id, city 6. Frontend uses lat/lng for the map marker / routing; user may drag the pin 7. Pin dropped → backend calls Reverse v4 with lat, lng, display_type=1 → nearest address ``` For new orders, store the address in the new format together with `ward_id`, `city_id` and the coordinates. Stored old-format addresses can be converted with the Migrate-Address API (see `data-tools.txt`). ### Complete address string (pasted or imported address) ``` 1. Backend calls Geocode v4 with the full address + focus (if known) + display_type=5 2. Pick the best result (first item) or let the user confirm among candidates 3. Backend calls Place v4 with its ref_id → lat/lng + address parts ``` ### Coordinates → address on a map click ``` 1. User clicks on the map → frontend sends lat/lng to YOUR backend 2. Backend calls Reverse v4 with lat, lng (+ display_type) 3. Return the first result's `display` (and its lat/lng) to the frontend ``` ### Server code (Node.js 18+) ```js // Runs on the server; the services key never reaches the browser. const KEY = process.env.VIETMAP_API_KEY; const API = "https://maps.vietmap.vn/api"; async function getJson(path, params, retries = 3) { const url = `${API}/${path}?${new URLSearchParams({ apikey: KEY, ...params })}`; for (let attempt = 0; ; attempt++) { const res = await fetch(url); if (res.status === 429 && attempt < retries) { await new Promise((r) => setTimeout(r, 1000 * 2 ** attempt)); // 1 s, 2 s, 4 s continue; } if (res.status === 401) throw new Error("VIETMAP 401: wrong or missing API key"); if (res.status === 423) throw new Error(`VIETMAP 423: ${await res.text()}`); // plain text if (!res.ok) throw new Error(`VIETMAP ${path}: HTTP ${res.status}`); return res.json(); } } // Suggestions while typing. focus: the user's "lat,lng", if known export async function suggest(text, focus) { const params = { text, display_type: "5" }; // new format, old one in data_old if (focus) params.focus = focus; const results = await getJson("autocomplete/v4", params); return results.map((r) => ({ refId: r.ref_id, display: r.display })); } // The user picked a suggestion: coordinates and address parts export async function resolve(refId) { const p = await getJson("place/v4", { refid: refId }); return { display: p.display, lat: p.lat, lng: p.lng, houseNumber: p.hs_num, street: p.street, wardId: p.ward_id, ward: p.ward, cityId: p.city_id, city: p.city, }; } // Full address string -> candidates (resolve the chosen one with resolve()) export async function geocode(text, focus) { const params = { text, display_type: "5" }; if (focus) params.focus = focus; return getJson("search/v4", params); } // The user dragged the pin: coordinates -> nearest address export async function pinToAddress(lat, lng) { const [nearest] = await getJson("reverse/v4", { lat, lng, display_type: "1" }); return nearest ? { display: nearest.display, lat: nearest.lat, lng: nearest.lng } : null; } ``` ### Server code (Python) ```python import os import requests KEY = os.environ["VIETMAP_API_KEY"] API = "https://maps.vietmap.vn/api" def get_json(path, params): resp = requests.get(f"{API}/{path}", params={"apikey": KEY, **params}, timeout=10) if resp.status_code == 423: raise RuntimeError(f"VIETMAP 423: {resp.text}") # plain-text body resp.raise_for_status() # 401 has an empty body return resp.json() def suggest(text, focus=None): # display_type=5: new format, old one in data_old results = get_json("autocomplete/v4", {"text": text, "focus": focus, "display_type": 5}) return [{"ref_id": r["ref_id"], "display": r["display"]} for r in results] def resolve(ref_id): p = get_json("place/v4", {"refid": ref_id}) keys = ("display", "lat", "lng", "hs_num", "street", "ward_id", "ward", "city_id", "city") return {k: p[k] for k in keys} def pin_to_address(lat, lng): results = get_json("reverse/v4", {"lat": lat, "lng": lng, "display_type": 1}) return results[0] if results else None ``` ### Browser (debounced input, calls YOUR backend) ```js const input = document.querySelector("#address"); let timer, controller; input.addEventListener("input", () => { clearTimeout(timer); const text = input.value.trim(); if (text.length < 2) return; // at least 2 characters timer = setTimeout(async () => { controller?.abort(); // cancel the previous request controller = new AbortController(); const res = await fetch(`/address/suggest?text=${encodeURIComponent(text)}`, { signal: controller.signal }); showSuggestions(await res.json()); // your render function }, 300); // after 300 ms without typing }); ``` --- ## cURL ```bash # Autocomplete v4 curl -G 'https://maps.vietmap.vn/api/autocomplete/v4' \ --data-urlencode 'apikey=YOUR_API_KEY' \ --data-urlencode 'text=197 tran phu' \ --data-urlencode 'focus=10.75887508,106.67538868' \ --data-urlencode 'display_type=5' # Geocode v4 (complete address string) curl -G 'https://maps.vietmap.vn/api/search/v4' \ --data-urlencode 'apikey=YOUR_API_KEY' \ --data-urlencode 'text=197 Trần Phú, phường 4, quận 5, thành phố Hồ Chí Minh' \ --data-urlencode 'focus=10.75887508,106.67538868' \ --data-urlencode 'display_type=5' # Place v4 (ref_id from Autocomplete/Geocode, prefix included) curl -G 'https://maps.vietmap.vn/api/place/v4' \ --data-urlencode 'apikey=YOUR_API_KEY' \ --data-urlencode 'refid=PASTE_REF_ID_VERBATIM' # Reverse v4 curl -G 'https://maps.vietmap.vn/api/reverse/v4' \ --data-urlencode 'apikey=YOUR_API_KEY' \ --data-urlencode 'lat=10.759221' \ --data-urlencode 'lng=106.675901' \ --data-urlencode 'display_type=5' ``` --- ## Common Pitfalls - **Pass `ref_id` verbatim, prefix included.** Send it as the `refid` query value unchanged; standard query encoding (`URLSearchParams`, `requests` `params=`, `--data-urlencode`) is fine. - **Request parameter is `refid`; the response field is `ref_id`.** - **`lat,lng` order — latitude first** for `focus` and `circle_center`. Reverse v4 takes separate `lat` and `lng` parameters. - **One Place v4 call per selection — not per suggestion.** - **Reverse v4 results carry `lat`/`lng`** — use them directly. - **`district_id: 0` / `district: ""` in Place v4** is the expected new-format answer (the `ref_id` came from a new 2-level result, e.g. the main object with `display_type=5`). Show `ward` + `city`. For all three levels, resolve the old-format `ref_id` (`data_old.ref_id`). - **Find boundaries by `type`, not by array position** — the new format has 2 entries (ward, province), the old format 3. - **Geocode v4 is for complete address strings**; route partial, as-you-type input to Autocomplete v4. - **Use the services key.** A tilemap key on these APIs returns `423`. - **Check the HTTP status before parsing** — `401` is empty, `423` is plain text. - **`display_type=5` is the recommended default** — new 2-level format plus the old 3-level format in `data_old`, so you can render either without a second call. `3` is for Autocomplete/Geocode only; `4` is for Reverse only. --- # VIETMAP Routing APIs — Agent Integration Guide > **APIs covered:** Route v4 (turn-by-turn for car, motorcycle, truck and container + toll cost per station & congestion) · Map Matching (`match-tolls`: snap a GPS trace already driven to the road network) > **Auth:** API key required, sent as the `apikey` query parameter. Use your **services key**; the tilemap key only renders the map. Register at https://maps.vietmap.vn/console-v2/register to get a key and 60,000 free transactions (about 3,000,000 VND). > **⚠️ Security:** All API calls MUST be made from your **backend server** so the API key stays private. NEVER expose your API key in frontend/client-side code. > **💬 Need help?** Contact VietMap via Zalo OA: https://zalo.me/3189066936017422854 ## Quick Summary Two related APIs for **driving in Vietnam**, before and after the trip: | API | Returns | Use when | |------------------|----------------------------------------------------|----------| | **Route v4** | Distance, duration, geometry, turn-by-turn instructions — plus optional toll cost per station (`annotations=toll`) and congestion | Navigation, trip planning, ETA, truck and container routing, freight toll quotes | | **Map Matching** | Snapped path, matched distance (km), toll stations along the matched path | A trip **already driven**: rebuild the route from a GPS trace, mileage, reconciliation | **Route v4 is the default.** It routes `car`, `motorcycle`, `truck` and `container` profiles; the profile determines speed and which roads are allowed. For the toll cost of a trip, call Route v4 with the vehicle and `annotations=toll`: the response carries the route total `toll_cost` (VND) and every station in `tolls[]`, priced for that vehicle. --- ## 1. Route v4 — Turn-by-turn (+ toll & congestion) ### Endpoint ``` GET https://maps.vietmap.vn/api/route/v4?apikey={apikey}&point={lat,lng}&point={lat,lng}&vehicle={vehicle} ``` ### Parameters | Parameter | Type | Required | Default | Description | |----------------|---------|-------------|--------------|-------------| | apikey | string | yes | | Your VietMap services API key | | point | string | yes (2+) | | Waypoint as `lat,lng` — **latitude first**. Repeat once per point, in order: origin, via points, destination. The maximum number of points depends on your plan. | | heading | number | no | `null` | Current heading of the vehicle in **degrees**, `0`–`360`, `0` = north. Used to pick the correct departure direction. E.g. `heading=45` | | vehicle | string | yes | | Enum: `car`, `motorcycle`, `truck`, `container`. Routing profile — determines speed and which roads are allowed. Send `vehicle` in every request. | | capacity | integer | conditional | `null` | **Required when `vehicle=truck`.** Gross vehicle weight in **kilograms**, e.g. `capacity=15000` for a 15-ton truck. | | container_feet | integer | no | `null` | Container length in **feet**, used with `vehicle=container`. E.g. `container_feet=40` | | time | string | no | none | Departure time, ISO-8601 in **UTC**, e.g. `time=2025-08-01T12:01:00Z`. Used to **avoid zones restricted** for your vehicle. For a vehicle leaving now, send the current time. | | avoid | string | no | `null` | Road types to avoid. Allowed values: `ferry`. E.g. `avoid=ferry` | | alternative | boolean | no | `false` | `true` also returns alternative routes in `paths` | | annotations | string | no | `null` | Comma-separated extra metadata. Allowed values: `congestion`, `congestion_distance`, `toll`. `toll` populates `toll_cost` + `tolls` on each path. E.g. `annotations=congestion,toll`. Annotations increase compute time and payload size. | | points_encoded | boolean | no | `true` | `true`: `points` and `snapped_waypoints` are Google Polyline (precision 5) strings — compact, recommended. `false`: GeoJSON `LineString` objects with `[longitude, latitude]` coordinates. | ### Truck and container routing | Profile | Send | What it does | |-------------|------|--------------| | `truck` | `vehicle=truck&capacity={kg}` | Route calculated from the gross vehicle weight (kg), respecting the weight limit on each road. `capacity` is required for trucks. | | `container` | `vehicle=container&container_feet={ft}` | Container routing by length (feet). `container_feet` is optional, e.g. `40`. | | both | `time={ISO-8601 UTC}` | Departure time, so Route v4 checks zone restrictions for your vehicle and avoids zones restricted for it. Send the current time for a vehicle leaving now. | | both | `annotations=toll` | Route total `toll_cost` (VND) and per-station `tolls[]`, priced for this vehicle | | both | `alternative=true` | Alternative routes, to compare distance, time and tolls before dispatch | `capacity` and `container_feet` are plain integers; `capacity` is kilograms (15 tons → `15000`). ### Request Examples ```bash # Basic car route curl "https://maps.vietmap.vn/api/route/v4?apikey=YOUR_API_KEY&point=10.755222,106.662633&point=10.755991,106.663323&vehicle=car" # Truck, 2,000 kg gross, toll + congestion (example from the Route v4 docs) curl "https://maps.vietmap.vn/api/route/v4?apikey=YOUR_API_KEY&point=18.7338,105.6209&point=17.75697,106.12351&vehicle=truck&capacity=2000&annotations=congestion,toll" # Truck, 15 tons gross, departure time set, toll cost curl "https://maps.vietmap.vn/api/route/v4?apikey=YOUR_API_KEY&point=18.7338,105.6209&point=17.75697,106.12351&vehicle=truck&capacity=15000&time=2025-08-01T12:01:00Z&annotations=toll" # Container, 40 ft, departure time set, toll cost + alternative routes curl "https://maps.vietmap.vn/api/route/v4?apikey=YOUR_API_KEY&point=18.7338,105.6209&point=17.75697,106.12351&vehicle=container&container_feet=40&time=2025-08-01T12:01:00Z&annotations=toll&alternative=true" # Avoid ferries curl "https://maps.vietmap.vn/api/route/v4?apikey=YOUR_API_KEY&point=10.755,106.662&point=10.770,106.670&vehicle=car&avoid=ferry" # Multi-point A → B → C (via point B) curl "https://maps.vietmap.vn/api/route/v4?apikey=YOUR_API_KEY&point=10.755,106.662&point=10.760,106.665&point=10.770,106.670&vehicle=car" ``` Repeated `point` parameters are sent as separate query parameters (`URLSearchParams` array of pairs in JS, list of tuples in Python `requests`). ### Response Truck, `capacity=2000`, `annotations=congestion,toll` (instructions shortened): ```json { "license": "vietmap", "code": "OK", "paths": [ { "distance": 194465.7, "weight": 10854.3, "time": 10854078, "transfers": 0, "points_encoded": true, "bbox": [105.6139, 17.75471, 106.37462, 18.73474], "points": "ccjqBkhtcS`E{DhFyDzDeBjHkC`Bg@xEkAnEaA|LwCxH{A~Ag@rDs@hA]bAg@...", "instructions": [ { "distance": 1191, "heading": 0, "sign": 2, "interval": [49, 67], "text": "Quốc Lộ 46", "time": 95123, "street_name": "Quốc Lộ 46" }, { "distance": 0, "heading": 0, "sign": 4, "interval": [1555, 1555], "text": "", "time": 0, "street_name": "" } ], "snapped_waypoints": "ccjqBkhtcSdl~DydaB", "toll_cost": 166000, "tolls": [ { "id": 544, "name": "Trạm Thu Phí Km 479+200", "address": "Cao Tốc Diễn Châu Bãi Vọt", "type": "exit", "price": 45000, "lat": 18.536289, "lng": 105.654187 }, { "id": 777, "name": "Trạm Thu Phí Tuyến Cao Tốc Hàm Nghi Vũng Áng", "address": "Cao Tốc Bãi Vọt Hàm Nghi", "type": "exit", "price": 42000, "lat": 18.330725, "lng": 105.830093 }, { "id": 779, "name": "Trạm Thu Phí Tuyến Cao Tốc Vũng Áng Bùng", "address": "Cao Tốc Vũng Áng Bùng", "type": "exit", "price": 79000, "lat": 18.044709, "lng": 106.257408 }, { "id": 670, "name": "Trạm Thu Phí Nút Giao Tiến Châu Văn Hóa", "address": "Cao Tốc Vũng Áng Bùng", "type": "exit", "price": 0, "lat": 17.828866, "lng": 106.359899 } ] } ] } ``` ### Top-level Fields | Field | Type | Description | |----------|--------|-------------| | license | string | License type of the routing data | | code | string | Status: `OK` on success. See section 3 (Errors & status) | | messages | string | Additional messages (if any); validation details when `code` is `INVALID_REQUEST` or `ERROR_UNKNOWN` | | paths | Path[] | Routes; also holds the alternative routes when `alternative=true` | ### Path Fields | Field | Type | Description | |-------------------|---------------|-------------| | distance | number | Total distance in **meters** | | weight | number | Internal routing cost used to rank candidate paths. Unitless; only for comparing routes in the same response. | | time | int | Total travel time in **milliseconds** | | transfers | int | Number of transfers | | points_encoded | boolean | Whether `points` and `snapped_waypoints` are polyline strings (`true`) or GeoJSON `LineString` objects (`false`) | | bbox | number[] | `[minLon, minLat, maxLon, maxLat]` | | points | string/object | Geometry as **Google Polyline 5** when `points_encoded=true`, or GeoJSON `LineString` with `[longitude, latitude]` coordinates when `points_encoded=false` | | instructions | Instruction[] | Turn-by-turn steps | | snapped_waypoints | string/object | Waypoints snapped to the road network, same format as `points` (Google Polyline 5 or GeoJSON `LineString` with `[longitude, latitude]` coordinates, if available) | | annotations | object | Per-segment `congestion` / `congestion_distance`. Only when requested via `annotations` | | toll_cost | number | Total toll for the route in **VND**, for the requested `vehicle`. Only with `annotations=toll` | | tolls | Toll[] | Toll stations along the route. Only with `annotations=toll` | ### Instruction Fields | Field | Type | Description | |--------------|--------|-------------| | distance | number | Distance until the next instruction (meters) | | heading | int | Heading of the instruction (if available) | | sign | int | Direction sign of the step. Table: https://www.figma.com/design/rWyQ5TNtt6E5l8tPEE9Tkl/VietMap-navigation-symbol?node-id=354-4 | | interval | int[] | `[startIdx, endIdx]` into the decoded `points`: the segment this instruction covers | | text | string | What the driver has to do to follow the route | | time | int | Duration of this step (ms) | | street_name | string | Street to turn onto to follow the route | | last_heading | null | Last heading of the instruction (if available) | ### Polyline Decoding With `points_encoded=true` (default), `points` and `snapped_waypoints` are **Google Polyline precision-5** strings. Decode with any standard polyline library: - JavaScript: `@mapbox/polyline` → `polyline.decode(encoded)` returns `[[lat, lng], ...]` - Dart: `google_polyline_algorithm` → `decodePolyline(encoded)` - Python: `polyline` package → `polyline.decode(encoded)` Keep `points_encoded=true` for the smallest response. `points_encoded=false` returns GeoJSON `LineString` objects with `[longitude, latitude]` coordinates (larger payload, no decoding). ### Toll cost (`annotations=toll`) Add `annotations=toll` with the right `vehicle` (+ `capacity` for trucks, `container_feet` for containers). Tolls depend on the vehicle profile and load: on the route above, the Km 479+200 station charges 35,000 VND (`car`), 45,000 VND (`truck`, `capacity=2000`), 93,000 VND (`truck`, `capacity=15000`), and 131,000 VND (`container`, `container_feet=40`), with route totals of 116,000, 166,000, 294,000, and 451,000 VND respectively. Each path gains: | Field | Type | Description | |-----------------|--------|-------------| | toll_cost | number | Total toll for the route, for the requested `vehicle`, in **VND** | | tolls[].id | int | Unique identifier of the toll station | | tolls[].name | string | Station name | | tolls[].address | string | Address or road of the station | | tolls[].type | string | `entry` (station where the vehicle enters) or `exit` (station where the vehicle exits and where the price is charged) | | tolls[].price | number | Toll fee charged at this station for the requested `vehicle` (VND) | | tolls[].lat | number | Latitude of the toll station | | tolls[].lng | number | Longitude of the toll station | **Calculate tolls leg by leg.** Annotations are calculated per leg: send 2 `point` values per call. For a multi-stop trip, call each leg and add up `toll_cost`. A 2-point request costs 1 transaction. ### Congestion (`annotations=congestion,congestion_distance`) Returned in `paths[].annotations`: | Key | Description | |---------------------|-------------| | congestion | Congestion level per segment (if available): `low` (avg ≥ 40 km/h), `moderate` (20–<40), `heavy` (10–<20), `severe` (>0–≤10), `unknown` | | congestion_distance | Distances in **meters**, only for segments with level ≥ `heavy` (if available) | Like tolls, congestion annotations are calculated leg by leg — 2 `point` values per call. ### Code: toll cost of a truck or container trip ```js // Node.js 18+. Call from your server so the API key stays private. const KEY = process.env.VIETMAP_API_KEY; async function routeV4(params, retries = 3) { const url = `https://maps.vietmap.vn/api/route/v4?${new URLSearchParams([["apikey", KEY], ...params])}`; for (let attempt = 0; ; attempt++) { const res = await fetch(url); if (res.status === 429 && attempt < retries) { await new Promise((r) => setTimeout(r, 1000 * 2 ** attempt)); // 1 s, 2 s, 4 s continue; } if (res.status === 401) throw new Error("VIETMAP 401: wrong or missing API key"); if (res.status === 423) throw new Error(`VIETMAP 423: ${await res.text()}`); if (!res.ok) throw new Error(`VIETMAP HTTP ${res.status}`); const data = await res.json(); if (data.code !== "OK") throw new Error(`VIETMAP ${data.code}: ${data.messages ?? ""}`); return data; } } // points: ["lat,lng", ...]; vehicle: query pairs for the profile; time: ISO-8601 UTC async function tripTolls(points, vehicle, time) { let total = 0; const stations = []; for (let i = 0; i + 1 < points.length; i++) { // one call per leg const data = await routeV4([ ["point", points[i]], ["point", points[i + 1]], ...vehicle, ["time", time], ["annotations", "toll"], ]); const path = data.paths[0]; total += path.toll_cost ?? 0; stations.push(...(path.tolls ?? [])); } return { total, stations }; } const truck = [["vehicle", "truck"], ["capacity", "15000"]]; // 15 t gross const container = [["vehicle", "container"], ["container_feet", "40"]]; // 40 ft const now = new Date().toISOString().slice(0, 19) + "Z"; // leaving now const trip = await tripTolls(["18.7338,105.6209", "17.75697,106.12351"], truck, now); console.log("Total toll:", trip.total, "VND"); ``` ```python import os from datetime import datetime, timezone import requests KEY = os.environ["VIETMAP_API_KEY"] def leg_tolls(origin, destination, vehicle, time): """Toll cost of one leg. origin, destination: "lat,lng"; vehicle: list of query pairs.""" params = [("apikey", KEY), ("point", origin), ("point", destination), *vehicle, ("time", time), ("annotations", "toll")] resp = requests.get("https://maps.vietmap.vn/api/route/v4", params=params, timeout=30) resp.raise_for_status() # 401 has an empty body, 423 a plain-text body data = resp.json() if data["code"] != "OK": raise RuntimeError(f"Route v4: {data['code']} {data.get('messages') or ''}") path = data["paths"][0] return path.get("toll_cost", 0), path.get("tolls", []) def trip_tolls(points, vehicle, time): """Toll cost of a trip: the sum of its legs. points: ["lat,lng", ...].""" legs = [leg_tolls(a, b, vehicle, time) for a, b in zip(points, points[1:])] return sum(t for t, _ in legs), [s for _, stations in legs for s in stations] container = [("vehicle", "container"), ("container_feet", "40")] now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") total, stations = trip_tolls(["18.7338,105.6209", "17.75697,106.12351"], container, now) print("Total toll:", total, "VND") ``` --- ## 2. Map Matching — Snap a GPS trace already driven POST the `[longitude, latitude]` points recorded by a phone or vehicle tracker. The API snaps them to the road network and returns the matched route, its length, and the toll stations along it priced for the given `vehicle` class. Use it for trip reconstruction, mileage and reconciliation after the trip. For a route **to be driven** — including truck and container, with `toll_cost` — use Route v4. ### Endpoint ``` POST https://maps.vietmap.vn/api/match-tolls?api-version=1.1&apikey={apikey}&vehicle={vehicle} Content-Type: application/json ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|--------|----------|---------|-------------| | apikey | string | yes | | Your VietMap services API key | | vehicle | number | no | `1` | Toll vehicle class `1`–`5` (table below) | ### Vehicle Class (Map Matching `vehicle`) | `vehicle` | Applies to | |-----------|------------| | `1` | Passenger cars `< 12` seats; trucks `< 2 tons` gross | | `2` | Passenger cars `<= 30` seats; trucks `< 4 tons` gross | | `3` | Passenger cars `> 31` seats; trucks `< 10 tons`; tractors not towing containers | | `4` | Trucks `< 18 tons` gross; tractor trucks with containers `<= 20 ft` | | `5` | Trucks `>= 18 tons` gross; tractors with containers `> 20 ft` | This numeric class is the Map Matching `vehicle`. Route v4 `vehicle` is a profile string (`truck` + `capacity`, `container` + `container_feet`). ### Body ```json [ [105.621984, 18.734739], [105.632625, 18.710847], [105.624089, 18.703015], [105.616424, 18.709974], [105.618558, 18.659362], [105.63865, 18.615698], [105.657487, 18.56891], [105.66063, 18.519051] ] ``` Array of `[longitude, latitude]` pairs in **time order** — **longitude first**, the opposite of Route v4 `point`. ### Response ```json { "distance": 29.302754191055257, "tolls": [ { "id": 528, "name": "Trạm Thu Phí Nút Giao Quốc Lộ 46B", "address": "Cao Tốc Diễn Châu Bãi Vọt", "type": "entry", "price": 0, "prices": null }, { "id": 544, "name": "Trạm Thu Phí Km 479+200", "address": "Cao Tốc Diễn Châu Bãi Vọt", "type": "exit", "price": 93000, "prices": { "523": 223000, "524": 152000, "528": 93000 } } ], "path": [ [105.62198442156398, 18.73473936521019], [105.6229179, 18.733773], [105.623846, 18.7326009], [105.6604439, 18.519257], [105.66057966475628, 18.51902456500069] ] } ``` The `path` array is shortened for brevity. | Field | Type | Description | |-----------------|---------------|-------------| | distance | float | Total distance of the matched route in **kilometers** | | path | `[lng,lat][]` | Coordinate pairs of the matched route, **longitude first** | | tolls | array | Toll stations along the matched route | | tolls[].id | integer | Unique identifier of the toll station | | tolls[].name | string | Station name | | tolls[].address | string | Station address or road | | tolls[].type | string | Station type: `entry` (where the vehicle enters) or `exit` (where the vehicle exits and the toll is charged) | | tolls[].price | integer | Toll fee at this station in **VND** for the requested `vehicle` class (`0` for `entry` stations) | | tolls[].prices | object / null | Present only on `exit` stations (`null` on `entry` stations). Keys are `entry` station `id` values; values are the toll fee (VND) from that entry station to this exit station for the requested `vehicle` class | ### cURL ```bash curl 'https://maps.vietmap.vn/api/match-tolls?api-version=1.1&apikey=YOUR_API_KEY&vehicle=4' \ -H 'Content-Type: application/json' \ -d '[[105.621984,18.734739],[105.632625,18.710847],[105.624089,18.703015],[105.616424,18.709974],[105.618558,18.659362],[105.63865,18.615698],[105.657487,18.56891],[105.66063,18.519051]]' ``` --- ## 3. Errors & status Check the **HTTP status first**, then (Route v4) the `code` field: a routing request can return HTTP `200` with `code: "ZERO_RESULTS"`. ### HTTP status | Status | Meaning | What to do | |--------|---------|------------| | `200` | Success, JSON body | For Route v4, also check `code` | | `400` | A parameter is missing or malformed | Fix the request; compare it with the examples above | | `401` | API key missing, wrong or unknown. **Empty body** | Check `apikey` and that you copied the whole services key | | `423` | Quota used up, the API is not enabled for this key, or a tilemap key was used. **Plain-text body**, e.g. `Your request is limited` | Trial accounts get 500 requests per API per day, renewed the next day. Check the API is enabled for the key in the Console; call Map APIs with the services key | | `429` | Too many requests in a short time | Wait and retry, lengthening the wait on each retry | | `500` | Server error | Retry later; contact support if it persists | `401` (empty) and `423` (plain text) are not JSON — read the status before parsing. ### Route v4 `code` | `code` | Meaning | What to do | |---------------------|---------|------------| | `OK` | Success | — | | `INVALID_REQUEST` | Parameters failed validation; details in `messages` | Fix the parameters named in `messages` | | `OVER_DAILY_LIMIT` | The key went over its daily limit | Wait for the next day, or raise the limit | | `MAX_POINTS_EXCEED` | More points than your plan allows | Send fewer points, or split the request | | `ZERO_RESULTS` | No road connects the points for the chosen vehicle | Check coordinate order (latitude first). With `truck` or `container`, retry with `car` to find a point on a road closed to trucks | | `ERROR_UNKNOWN` | Unexpected error; details in `messages` | Retry; contact support if it keeps happening | --- ## 4. Transaction cost | API | Transactions per request | Examples | |----------|--------------------------|----------| | Route v4 | `⌊points / 5⌋ + 1` (`points` = number of `point` values) | 2 points → 1 · 5 points → 2 · 8 points → 2 · 10 points → 3 · 12 points → 3 | Leg-by-leg toll calculation sends 2 points per call, so each leg costs 1 transaction. --- ## Integration Flow ### Navigation app ``` 1. User picks origin + destination 2. Backend calls Route v4 with `vehicle` (default points_encoded=true); add heading for a moving vehicle 3. Decode `paths[0].points`, render on map, show distance (m) and time (ms) 4. Iterate `instructions[]` for turn-by-turn UI (`interval` indexes into the decoded points) ``` ### Truck / container trip with toll cost ``` 1. User picks stops + vehicle: truck (gross weight, kg) or container (length, ft) + departure time 2. For each leg (2 points), backend calls Route v4 with vehicle=truck&capacity={kg} or vehicle=container&container_feet={ft} + time={ISO-8601 UTC} + annotations=toll 3. Add up `paths[0].toll_cost` (VND) across legs; list `paths[0].tolls[]` per station 4. Read distance/time from the SAME responses; add alternative=true to compare options ``` ### After the trip: reconciliation ``` 1. Tracker uploads the GPS trail ([lng, lat], time order) 2. Backend calls Map Matching with the vehicle class (1..5) 3. Compare matched `distance` (km) and `path` with the planned Route v4 route 4. `tolls[]` lists the stations along the matched route, priced for that class ``` --- ## Common Pitfalls - **Coordinate order flips between APIs.** Route v4 query: `point=lat,lng`. Map Matching body: `[lng, lat]`. Double-check when moving between them. - **`vehicle` differs per API.** Route v4 requires a profile string (`car` / `motorcycle` / `truck` / `container`) in every request. Map Matching takes a numeric class `1`–`5`. - **Route v4 `truck` needs `capacity`**, the gross vehicle weight in **kg** (15 tons → `15000`). For `container`, add `container_feet` (e.g. `40`). - **Send `time` for trucks and containers** (ISO-8601 UTC; the current time if leaving now) so Route v4 avoids zones restricted for the vehicle. - **Toll cost is opt-in.** `toll_cost`/`tolls` appear when you pass `annotations=toll`. Use the right `vehicle` — tolls depend on the vehicle class. - **Annotations work leg by leg.** Send 2 `point` values per call; for a multi-stop trip, call each leg and add up `toll_cost`. - **The toll is charged at the `exit` station.** Keep `entry` rows for display; `toll_cost` already holds the route total. - **Check HTTP status, then `code`.** `401` has an empty body, `423` a plain-text body; HTTP `200` can carry `ZERO_RESULTS`. - **Use the services key** for Route v4 and Map Matching; the tilemap key returns `423` on Map APIs. - **Units:** Route v4 `distance` is meters and `time` milliseconds; Map Matching `distance` is kilometers; tolls are VND. --- # VIETMAP Logistics APIs — Agent Integration Guide > **APIs covered:** Matrix v4 (N×M travel time/distance) · TSP v4 (1 vehicle, optimal order) · VRP (fleet planning) · Isochrone (reachable area) · Geofencing (is a position inside a zone?) > **Auth:** API key required, sent as the `apikey` query parameter. Use the **services key**, not the tilemap key. Register at https://maps.vietmap.vn/console-v2/register — new accounts get 60,000 free transactions (about 3,000,000 VND). > **⚠️ Security:** All API calls MUST be made from your **backend server**. NEVER expose your API key in frontend/client-side code. Read it from an environment variable (e.g. `VIETMAP_API_KEY`). > **💬 Need help?** Contact VIETMAP via Zalo OA: https://zalo.me/3189066936017422854 · Email: maps.info@vietmap.vn ## Quick Summary Five APIs for **dispatch, route optimization and coverage** in Vietnam. Matrix, TSP, VRP and Isochrone are computed on the real VIETMAP road network (one-way streets and restricted roads included). | API | Problem | Use when | |---|---|---| | **Matrix v4** | Travel time (s) or distance (m) for every origin → destination pair in one call | Pick the nearest driver/store (1×N), or build the N×N cost matrix for your own solver | | **TSP v4** | Lowest-driving-time visiting order for **one vehicle**, with geometry + turn-by-turn | One driver, many stops — "just tell me the order" | | **VRP** | Which of **several vehicles** takes which stops, and in what order | Fleet planning with capacity, delivery slots, shift hours, skills, priority | | **Isochrone** | Area reachable from a point within a travel time or distance — polygon or line contours | Delivery zones, store site selection, "which branch serves me?", EV range | | **Geofencing** | Is a position within `radius` meters of each zone center? — `inside` per center | Proof of delivery, depot departure/return, site attendance | Matrix v4 and TSP v4 accept the `truck` and `container` vehicle profiles. For toll cost by vehicle type on the final route, use Route v4 (see `routing.txt`). Try without code: https://tools.vietmap.vn/playground/matrix · https://tools.vietmap.vn/playground/tsp · https://tools.vietmap.vn/playground/vrp ### Transaction cost | API | Transactions per request | Example | |---|---|---| | Matrix v4 | `n × m` (origins × destinations) | 4 origins × 10 destinations = 40 | | TSP v4 | `m` (one per stop) | 20-stop tour = 20 | | VRP | `n × m` (vehicles × stops) | 3 vehicles × 20 stops = 60 | | Isochrone | 1 | — | | Route v4 (chain step) | `⌊points / 5⌋ + 1` | 8 points = 2 | | Geocode v4, Place v4 (chain step) | 1 each | 20 addresses × 2 = 40 | Matrix with the default `sources=all&destinations=all` uses every point on both sides. Size a daily VRP plan from the formula before sending it. Convert transactions to VND with the Pricing Converter: https://maps.vietmap.vn/docs/map-api/console/pricing-converter/ --- ## 1. Matrix v4 Travel time or distance for every origin → destination pair in one call, instead of N×M Route calls. The response is numbers only — no geometry. Runs on the same v4 routing engine as Route v4. ### Endpoint ``` GET https://maps.vietmap.vn/api/matrix/v4?apikey={apikey}&point={lat,lng}&point={lat,lng}&...&vehicle={vehicle}&sources={idx}&destinations={idx}&annotation={duration|distance} ``` ### Parameters | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | apikey | string | yes | — | Your VIETMAP services key | | point | string (repeatable) | yes | — | `lat,lng` — latitude first. Repeat once per point, in order. At least an origin and a destination; the maximum depends on your plan | | vehicle | string | yes | — | `car`, `motorcycle`, `truck`, `container`. Send `vehicle` in every request | | sources | int or string | no | `all` | Zero-based indices of origin points in `point` order, separated by `;` (e.g. `0;1`). `all` = every point | | destinations | int or string | no | `all` | Zero-based indices of destination points, separated by `;` (e.g. `2;3;4;5`). `all` = every point | | annotation | string | no | `duration` | `duration` (seconds) or `distance` (meters) | **Indexing:** points are 0-indexed in URL order. With 6 points and `sources=0;1&destinations=2;3;4;5`, rows are points 0–1 and columns are points 2–5. ### Request Example ``` GET https://maps.vietmap.vn/api/matrix/v4?apikey={apikey} &point=10.768897,106.678505 &point=10.765496,106.67626 &point=10.7627936,106.6750729 &point=10.7616745,106.6792425 &point=10.765605,106.685383 &point=10.766843,106.674029 &vehicle=car &sources=0;1 &destinations=2;3;4;5 ``` ### Response ```json { "code": "OK", "messages": null, "durations": [ [230, 201, 386, 193], [126, 188, 435, 108] ], "distances": [ [1766.3, 1374.3, 1952.2, 1113.5], [507.5, 1152.4, 2101.8, 399.4] ] } ``` | Field | Type | Description | |---|---|---| | code | string | `OK` on success; see [Errors](#6-errors-and-status-codes) | | messages | string \| null | Messages associated with the response, if any (validation details on `INVALID_REQUEST`) | | durations | number[][] | Travel time in **seconds**. `durations[i][j]` = `sources[i]` → `destinations[j]`; one row per origin, one column per destination | | distances | number[][] | Same layout as `durations`, in **meters** | Read `durations` for `annotation=duration` and `distances` for `annotation=distance`. **Status codes (`code`):** `OK`, `INVALID_REQUEST`, `OVER_DAILY_LIMIT`, `MAX_POINTS_EXCEED`, `ERROR_UNKNOWN`. --- ## 2. TSP v4 (single vehicle, optimal order) Returns the route for **one** vehicle through all points with the lowest total driving time, with geometry and turn-by-turn instructions. Times come from the VIETMAP road network for the given `vehicle`. By default the route returns to the first point. Runs on the same v4 routing engine as Route v4. For several vehicles use VRP. ### Endpoint ``` GET https://maps.vietmap.vn/api/tsp/v4?apikey={apikey}&point={lat,lng}&point={lat,lng}&...&vehicle={vehicle}&roundtrip={true|false}&sources={any|first}&destinations={any|last}&points_encoded={true|false} ``` ### Parameters | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | apikey | string | yes | — | Your VIETMAP services key | | point | string (repeatable) | yes | — | `lat,lng` — latitude first. Repeat once per point. The maximum depends on your plan | | vehicle | string | yes | — | `car`, `motorcycle`, `truck`, `container`. Send `vehicle` in every request | | roundtrip | boolean | no | `true` | `true` = route returns to the start point. `false` = open route; start/end set by `sources`/`destinations` | | sources | string | no | `any` | `any` = solver picks the start point; `first` = start at the first `point` sent | | destinations | string | no | `any` | `any` = solver picks the end point; `last` = end at the last `point` sent (use with `roundtrip=false`) | | points_encoded | boolean | no | `true` | `true` = `points` and `snapped_waypoints` as Google polyline-5 strings; `false` = plain `[lon,lat]` coordinate pairs | ### Common setups | Situation | Parameters | |---|---| | Start and end at the depot | `roundtrip=true` (default) — send the depot as the first `point` | | Start at the depot, end anywhere | `roundtrip=false&sources=first` | | End at the last `point` you sent | `roundtrip=false&destinations=last` | | Opening hours or load limits | Use VRP (`time_windows`, `capacity`) | ### Response ```json { "license": "vietmap", "code": "OK", "messages": null, "paths": [{ "distance": 7720.5, "weight": 1022.8, "time": 1022800, "transfers": 0, "points_encoded": true, "bbox": [106.68973, 10.79352, 106.71098, 10.80307], "points": "", "instructions": [ { "distance": 192, "heading": 0, "sign": 0, "interval": [0, 6], "text": "Tiếp tục theo Đường Nguyễn Cửu Vân", "time": 25900, "street_name": "Đường Nguyễn Cửu Vân", "last_heading": null }, { "distance": 0, "heading": 0, "sign": 4, "interval": [201, 201], "text": "Đích đến", "time": 0, "street_name": "Đường Nguyễn Cửu Vân", "last_heading": null } ], "snapped_waypoints": "" }] } ``` Response truncated; middle instructions omitted. | Field | Type | Description | |---|---|---| | license | string | License type of the map data | | code | string | `OK` on success; see [Errors](#6-errors-and-status-codes) | | messages | null \| string | Messages associated with the response, if any | | paths | array | A single path — the optimized tour | | paths[].distance | number | Total distance, **meters** | | paths[].weight | number | Internal routing cost; use `time` and `distance` for display | | paths[].time | integer | Total travel time, **milliseconds** | | paths[].transfers | integer | Number of transfers | | paths[].points_encoded | boolean | Whether `points` / `snapped_waypoints` are polyline strings | | paths[].bbox | number[4] | `[minLon, minLat, maxLon, maxLat]` | | paths[].points | string | Route geometry (Google polyline precision 5 when `points_encoded=true`) | | paths[].instructions | array | Turn-by-turn steps (below) | | paths[].snapped_waypoints | string | Input points snapped to the road network, in visiting order, same encoding as `points` | | Instruction field | Type | Description | |---|---|---| | distance | number | Length of this step, meters | | heading | integer | Heading direction of the step | | sign | integer | Turn code for the step (e.g. turn left) | | interval | int[2] | First and last index into the decoded `points` covered by this step | | text | string | Instruction text | | time | integer | Duration of this step, milliseconds | | street_name | string | Street name | | last_heading | null \| number | Last heading direction, or `null` | **Status codes (`code`):** `OK`, `INVALID_REQUEST`, `OVER_DAILY_LIMIT`, `MAX_POINTS_EXCEED`, `ERROR_UNKNOWN`, `ZERO_RESULTS` — see section 6. --- ## 3. VRP (fleet planning) You send `vehicles` and `jobs`. The response has one route per vehicle used, listing its stops in visiting order with the arrival time at each stop and cumulative distance and duration, plus `unassigned` for jobs no vehicle could take. ### Endpoint ``` POST https://maps.vietmap.vn/api/vrp?api-version=1.1&apikey={apikey} Content-Type: application/json ``` | Query param | Required | Value | |---|---|---| | apikey | yes | Your VIETMAP services key | | api-version | — | `1.1` (keep it in the URL as shown) | | Body key | Type | Required | Description | |---|---|---|---| | vehicles | array | yes | [Vehicle objects](#vehicle-object); at least one | | jobs | array | conditional | [Job objects](#job-object); each job is one place to visit. At least one of `jobs` or `shipments` is required | | shipments | array | conditional | [Shipment objects](#shipment-object); pickup-to-delivery pairs on the same vehicle. At least one of `jobs` or `shipments` is required | > ⚠️ **VRP coordinates are `[longitude, latitude]`** (longitude first) in `location`, `start`, `end` and the response — the opposite of the `point=lat,lng` used by Matrix/TSP. ### Request Body (Unix timestamps, skills, breaks) ```json { "vehicles": [ { "id": 1, "start": [106.5983012, 10.8879148], "end": [106.5983012, 10.8879148], "profile": "bike", "time_window": [1685953800, 1686418200], "skills": [1, 1000], "breaks": [ { "id": 1000, "time_windows": [[1685966400, 1685970000]], "service": 3600 } ] } ], "jobs": [ { "id": 1001, "description": "HOME", "location": [106.5983012, 10.8879148], "service": 0, "priority": 3, "time_windows": [[1685986200, 1685988000]], "skills": [1000] }, { "id": 304, "description": "CO.OP FOOD NGUYỄN VĂN QUÁ", "location": [106.6287481, 10.8362058], "service": 1800, "time_windows": [[1685948400, 1685980800], [1686034800, 1686067200]], "skills": [1] } ] } ``` A relative-time example with `capacity` / `delivery` is in [cURL](#curl). ### Vehicle Object | Key | Type | Required | Default | Description | |---|---|---|---|---| | id | integer | yes | — | Unique across all vehicles | | start | `[lng,lat]` | conditional | — | Where the route begins. At least one of `start`/`end` is required. Without `start`, the route begins at its first job (the solver picks which) | | end | `[lng,lat]` | conditional | — | Where the route ends. Without `end`, the route finishes at its last job. Same as `start` = round trip from a depot | | profile | string | no | — | Routing profile that determines speed and allowed roads, e.g. `bike`, `car`, `truck` | | capacity | int[] | no | — | Maximum load per dimension, e.g. `[items, weight, volume]`. Dimension order must match jobs' `delivery`/`pickup` | | skills | int[] | no | — | Skills this vehicle **has** | | time_window | `[start,end]` | no | — | Working hours as **one** pair, in seconds. Singular key (jobs use `time_windows`). Omitted = no time constraint | | breaks | object[] | no | — | Mandatory breaks: `{ "id": int, "time_windows": [[start,end], ...], "service": seconds }` | ### Job Object | Key | Type | Required | Default | Description | |---|---|---|---|---| | id | integer | yes | — | Unique across all jobs | | location | `[lng,lat]` | yes | — | Job coordinates | | description | string | no | — | Free-text label, returned as-is to help identify the stop | | service | integer | no | `0` | Time spent at the job, **seconds** | | delivery | int[] | no | — | Goods loaded at the vehicle's `start` and dropped here. Same dimensions as `capacity` | | pickup | int[] | no | — | Goods collected here and carried to the vehicle's `end`. Same dimensions as `capacity` | | skills | int[] | no | — | Skills this job **requires**; only a vehicle with all of them can serve it | | priority | integer `0`–`10` | no | `0` | Higher values are kept first when not every job fits | | time_windows | `[[start,end], ...]` | no | — | Windows in which service may **start**, seconds. Several disjoint windows allowed. Omitted = any time | ### Shipment Object Both stops of a shipment are served by the same vehicle, `pickup` before `delivery`. Load increases at `pickup` and decreases at `delivery`. | Key | Type | Required | Default | Description | |---|---|---|---|---| | pickup | object | yes | — | Pickup stop (goods or passenger) | | delivery | object | yes | — | Delivery stop (goods or passenger) | | amount | int[] | no | — | Quantities per dimension; same length and order as vehicle `capacity` | Each `pickup` / `delivery` object: | Key | Type | Required | Default | Description | |---|---|---|---|---| | id | integer | yes | — | Stop identifier, echoed as `id` on the corresponding `pickup`/`delivery` step | | location | `[lng,lat]` | yes | — | Stop coordinates | | service | integer | no | `0` | Stop duration, **seconds** | | time_windows | `[[start,end], ...]` | no | — | Windows in which service may start, seconds (same convention as job `time_windows`; supported on both `pickup` and `delivery`) | | description | string | no | — | Optional text echoed on the corresponding step | ### Constraints Load limits (items, weight, volume) → vehicle `capacity` + job `delivery`/`pickup` · customer delivery slots → job `time_windows` · driver shift hours → vehicle `time_window` · only some vehicles can do some jobs (cold chain, licence, equipment) → `skills` on both · jobs to keep when the fleet is short → job `priority` · round trip from a depot → vehicle `start` = `end`. - **Capacity:** `capacity`, `delivery`, `pickup` are integer arrays of the same length, one entry per dimension. The load at every step must stay within `capacity` on every dimension. Put the most limiting dimension first. - **Skills:** a job with `skills` goes only to a vehicle whose `skills` contain all of them. No `skills` on either side = no restriction. - **Priority:** when not every job fits, higher-priority jobs are kept; dropped jobs appear in `unassigned`. - **Time:** seconds, in one convention used consistently across the request — relative to the planning horizon (`[0, 14400]` = first 4 hours) or absolute Unix timestamps. `arrival` in the response uses the same convention. ### Response ```json { "code": 0, "summary": { "cost": 12400, "unassigned": 0, "service": 196200, "duration": 12400, "waiting_time": 237145, "priority": 3, "distance": 109272, "computing_times": { "loading": 37, "solving": 61, "routing": 11 } }, "unassigned": [], "routes": [ { "vehicle": 1, "cost": 12400, "service": 196200, "duration": 12400, "waiting_time": 237145, "priority": 3, "distance": 109272, "steps": [ { "type": "start", "location": [106.5983012, 10.8879148], "arrival": 1685956255, "duration": 0, "distance": 0 }, { "type": "break", "id": 6000, "service": 3600, "waiting_time": 177741, "arrival": 1686220659, "duration": 12400, "distance": 109272 }, { "type": "end", "location": [106.5983012, 10.8879148], "arrival": 1686402000, "duration": 12400, "distance": 109272 } ], "geometry": "" } ] } ``` Response truncated; middle steps omitted. A `job` step carries `type`, `id` (the job `id`), `location`, `service`, `waiting_time`, `arrival`, `duration`, `distance`. | Field | Type | Description | |---|---|---| | code | int | `0` = problem solved | | summary | object | Totals across **all** routes | | summary.cost | number | Objective value the solver minimizes, derived mainly from travel time | | summary.unassigned | int | Number of jobs not assigned to any vehicle | | summary.service | int | Total service time at visited jobs, seconds | | summary.duration | int | Total travel (driving) time, seconds | | summary.waiting_time | int | Total time waiting for time windows to open, seconds | | summary.priority | int | Sum of `priority` of assigned jobs | | summary.distance | number | Total distance, meters | | summary.computing_times | object | Solver time per phase (`loading`, `solving`, `routing`), milliseconds | | unassigned | array | Jobs or shipment stops no vehicle could take: `{ "id", "location" }`. An unassigned shipment lists both its `pickup` and `delivery` stops with their `id` and `location`. Empty when all are assigned | | routes | array | One entry per vehicle used | | routes[].vehicle | int | Vehicle `id` | | routes[].cost / service / duration / waiting_time / priority / distance | number | Same metrics as `summary`, for this route | | routes[].steps | array | Ordered stops | | routes[].steps[].type | string | `start`, `job`, `pickup`, `delivery`, `break`, `end` | | routes[].steps[].id | int | Job or break `id` (on `job`, `pickup`, `delivery`, `break` steps) | | routes[].steps[].location | `[lng,lat]` | On `start`, `end` and job steps | | routes[].steps[].service | int | Service or break duration, seconds | | routes[].steps[].waiting_time | int | Wait before service can start, seconds | | routes[].steps[].arrival | int | Arrival time, seconds, same convention as input (relative or Unix) | | routes[].steps[].duration | int | Cumulative travel time from route start, seconds | | routes[].steps[].distance | number | Cumulative distance from route start, meters | | routes[].geometry | string | Full route geometry, Google polyline 5 | Read the stop order per vehicle: ```js for (const route of plan.routes) { const stops = route.steps.filter((s) => s.type === "job").map((s) => s.id); console.log(`Vehicle ${route.vehicle}: ${stops.join(" → ")}, ${route.distance} m`); } console.log("Unassigned:", plan.unassigned.map((j) => j.id)); ``` --- ## 4. Isochrone (reachable area) Returns the area reachable from a point within a given travel time or distance, as polygon or line contours. Computed on the VIETMAP road network behind Routing, so it follows one-way streets, respects road classes and vehicle profiles, and takes rivers, canals and dead ends into account — unlike a straight-line radius circle. **Getting started:** Isochrone is enabled per API key. Contact VIETMAP to enable it for your key and receive the endpoint, parameters and integration details: - Zalo OA (Vietmap Solutions): https://zalo.me/3189066936017422854 - Email: maps.info@vietmap.vn Build the integration on the endpoint and parameters VIETMAP sends with the activation. Cost: 1 transaction per request. Pairs with Geofencing: compute an isochrone to decide a serving area, then use that area's center and an approximate radius as the geofence. Use Matrix v4 when you need exact times between specific pairs rather than an area. --- ## 5. Geofencing (position vs. zone centers) Takes one position (vehicle, device) plus a list of zone centers sharing one radius in meters, and returns `inside: true/false` per center. Each request is an independent check: the API stores no fences and emits no events. To detect enter/exit, call it on every position update and compare with the previous result. ### Endpoint ``` POST https://maps.vietmap.vn/api/geofencing?apikey={apikey} Content-Type: application/json ``` ### Request Body ```json { "geometryCenters": [ { "id": "1", "long": 105.7487405, "lat": 9.8644254 }, { "id": "2", "long": 105.7491342, "lat": 9.8642686 }, { "id": "3", "long": 105.7489267, "lat": 9.8645398 } ], "radius": 15, "long": 105.7488398, "lat": 9.8643837 } ``` | Field | Type | Required | Description | |---|---|---|---| | geometryCenters | array of `{id, long, lat}` | yes | Zone centers to check against, one object per zone | | geometryCenters[].id | string | yes | Your zone identifier, echoed in the response | | geometryCenters[].long | number | yes | Zone center **longitude** | | geometryCenters[].lat | number | yes | Zone center **latitude** | | radius | number | yes | Radius in **meters**, applied to every center | | long | number | yes | Longitude of the position to check (vehicle, device) | | lat | number | yes | Latitude of the position to check | ### Response ```json { "code": null, "message": null, "data": [ { "id": "1", "inside": true }, { "id": "2", "inside": false }, { "id": "3", "inside": false } ] } ``` | Field | Type | Description | |---|---|---| | code | null \| string | Error code; `null` on success | | message | null \| string | Error message; `null` on success | | data | array | One entry per center in `geometryCenters` | | data[].id | string | The zone `id` you sent — match results by `id` | | data[].inside | boolean | `true` if the position is within `radius` of this center | --- ## 6. Errors and status codes Check the HTTP status first, then the body: Matrix v4 and TSP v4 can return HTTP `200` with a non-`OK` `code`. | HTTP | Meaning | Action | |---|---|---| | `200` | Success (JSON) | Matrix/TSP: also check `code`. VRP: `code: 0` = solved. Geofencing: `code: null` = success | | `400` | A parameter is missing or malformed | Fix the request; compare with the examples above | | `401` | API key missing, wrong or unknown. **Empty body** | Check the `apikey` value (the whole services key) | | `423` | Quota used up, API not enabled for the key, or a tilemap key used. **Plain-text body**, e.g. `Your request is limited` | Check usage and top up in the Console; enable the API for the key in Manage API key (or contact VIETMAP); call with the services key | | `429` | Too many requests in a short time | Wait and retry with a growing delay (1 s, 2 s, 4 s) | | `500` | Server error | Retry later; send the request to support if it persists | Read the status before parsing JSON (`401` and `423` are not JSON). | `code` (Matrix v4, TSP v4) | Meaning | Action | |---|---|---| | `OK` | Success | — | | `INVALID_REQUEST` | Parameters failed validation; details in `messages` | Fix the parameters named in `messages` | | `OVER_DAILY_LIMIT` | Key went over its daily limit | Wait for the next day, or raise the limit | | `MAX_POINTS_EXCEED` | More points than your plan allows | Send fewer points, or split the request | | `ZERO_RESULTS` (TSP) | No road connects the points for the chosen vehicle | Check `lat,lng` order; with `truck`/`container`, retry with `car` | | `ERROR_UNKNOWN` | Unexpected error; details in `messages` | Retry; contact support if it persists | One wrapper for every call (Node.js 18+, server-side): ```js async function callVietmap(url, init, retries = 3) { for (let attempt = 0; ; attempt++) { const res = await fetch(url, init); if (res.status === 429 && attempt < retries) { await new Promise((r) => setTimeout(r, 1000 * 2 ** attempt)); // 1 s, 2 s, 4 s continue; } if (res.status === 401) throw new Error("VIETMAP 401: wrong or missing API key"); if (res.status === 423) throw new Error(`VIETMAP 423: ${await res.text()}`); if (!res.ok) throw new Error(`VIETMAP HTTP ${res.status}`); const data = await res.json(); // Matrix/TSP return "OK" on success; VRP returns 0 and Geofencing null if (typeof data.code === "string" && data.code !== "OK") { throw new Error(`VIETMAP ${data.code}: ${data.messages ?? ""}`); } return data; } } // VRP: additionally check data.code === 0 ``` --- ## Integration Flow ### Delivery planning — chaining the APIs | Step | Job | API | |---|---|---| | 1 | Address → coordinates | `GET https://maps.vietmap.vn/api/search/v4?apikey=&text={address}` → `[0].ref_id`, then `GET https://maps.vietmap.vn/api/place/v4?apikey=&refid={ref_id}` → `lat`, `lng`. Store coordinates for reuse | | 2 | Split stops between vehicles and order them | VRP; for a single vehicle, TSP v4 | | 3 | Turn-by-turn directions and tolls by vehicle type | Route v4 with the points in the order VRP chose; tolls are calculated leg by leg (see `routing.txt`) | | 4 | Confirm the vehicle reached the stop | Geofencing | | 5 | Reconcile the distance driven | Map Matching (see `routing.txt`) | ### Matrix — choose nearest driver ``` 1. Collect driver locations + the customer pickup point 2. Call Matrix v4: vehicle=car|motorcycle|truck|container, sources = driver indices, destinations = customer index, annotation=duration 3. Pick the row i with the smallest durations[i][0] ``` ### TSP — order one driver's stops ``` 1. Collect stops; send the depot first 2. Call TSP v4 with roundtrip=true (or roundtrip=false&sources=first), vehicle=motorcycle|car|truck|container 3. Decode paths[0].points → draw on the map; paths[0].snapped_waypoints gives the stops in visiting order 4. Iterate paths[0].instructions → turn-by-turn UI ``` ### VRP — plan tomorrow's routes for a fleet ``` 1. Assemble vehicles[] (depot start/end + time_window + capacity + skills) 2. Assemble jobs[] (location [lng,lat] + delivery/pickup + service + time_windows + priority) 3. POST /api/vrp?api-version=1.1 from your backend 4. Check code === 0, then iterate routes[] → assign to drivers in the dispatch app 5. Surface unassigned[] (id, location) to the dispatcher 6. Optional: Route v4 per route for turn-by-turn and toll cost ``` ### Isochrone — delivery zone per branch ``` 1. Enable Isochrone for your key (section 4) and use the endpoint and parameters VIETMAP provides 2. Call it from YOUR backend; draw the returned polygon or line contours on the map ``` ### Geofencing — "has the driver reached the customer?" ``` 1. Driver app reports GPS to YOUR backend on each position update 2. Backend: long/lat = driver position, geometryCenters = [{ id: stopId, long, lat }, ...] (the stops), radius = arrival radius in meters 3. POST /api/geofencing → data[].inside per stop (match by id) 4. Compare with the previous result per stop: false → true = arrived, true → false = left ``` Same pattern for depot departure/return and site attendance (center = depot or site). --- ## cURL ```bash # Matrix v4 (2 origins × 4 destinations = 8 transactions) curl 'https://maps.vietmap.vn/api/matrix/v4?apikey=YOUR_API_KEY&point=10.768897,106.678505&point=10.765496,106.67626&point=10.7627936,106.6750729&point=10.7616745,106.6792425&point=10.765605,106.685383&point=10.766843,106.674029&vehicle=car&sources=0;1&destinations=2;3;4;5' # TSP v4 (3 stops, round trip, motorcycle) curl 'https://maps.vietmap.vn/api/tsp/v4?apikey=YOUR_API_KEY&point=10.79628438955497,106.70592293472612&point=10.801891047584164,106.70660958023404&point=10.801595962927763,106.6898296806408&points_encoded=true&vehicle=motorcycle&roundtrip=true' # VRP (relative time: seconds from planning start; capacity + delivery) curl -X POST 'https://maps.vietmap.vn/api/vrp?api-version=1.1&apikey=YOUR_API_KEY' \ -H 'Content-Type: application/json' \ -d '{ "vehicles": [{"id":1,"start":[106.5983012,10.8879148],"end":[106.5983012,10.8879148], "capacity":[10],"time_window":[0,14400]}], "jobs": [ {"id":1,"location":[106.6519,10.8231],"service":300,"delivery":[2]}, {"id":2,"location":[106.6297,10.8016],"service":300,"delivery":[3],"time_windows":[[3600,7200]]} ] }' # Geofencing (one position vs. 3 zone centers, radius 15 m) curl -X POST 'https://maps.vietmap.vn/api/geofencing?apikey=YOUR_API_KEY' \ -H 'Content-Type: application/json' \ -d '{"geometryCenters":[{"id":"1","long":105.7487405,"lat":9.8644254},{"id":"2","long":105.7491342,"lat":9.8642686},{"id":"3","long":105.7489267,"lat":9.8645398}],"radius":15,"long":105.7488398,"lat":9.8643837}' ``` --- ## Common Pitfalls - **Coordinate order differs per API.** Check before copying values between calls: | Where | Format | |---|---| | Matrix v4, TSP v4, Route v4 `point` | String `lat,lng`, latitude first | | Place v4 and Reverse v4 results | Two fields, `lat` and `lng` | | VRP `location`, `start`, `end`, response `location`; Map Matching body | Array `[lng, lat]`, longitude first | | Geofencing | Two fields, `lat` and `long` (named `long`, not `lng`) | | VietMap GL JS (`center`, `setLngLat`) | Array `[lng, lat]` | - **Units differ per API.** Matrix: `durations` seconds, `distances` meters. TSP/Route v4: `distance` meters, `time` **milliseconds**. VRP: `service`, `duration`, `waiting_time`, time windows in seconds; `distance` meters; `computing_times` milliseconds. - **VRP `time_window` (vehicle, one pair) vs `time_windows` (job, list of pairs).** Use one time convention — relative seconds or Unix timestamps — across the whole request; `arrival` comes back in that convention. - **VRP dimensions must line up.** `capacity`, `delivery` and `pickup` have the same length and the same dimension order. - **Always read `unassigned[]` in the VRP response.** Each entry carries the job `id` and `location`; `summary.unassigned` gives the count. - **`code` types differ.** Matrix/TSP: string `"OK"`. VRP: integer `0`. Geofencing: `null` on success. `401`/`423` bodies are not JSON — check the HTTP status first. --- # VIETMAP Address Migration API (Data Tools) — Agent Integration Guide > **APIs covered:** Migrate-Address v3 — convert one Vietnamese address between the **old** administrative format (ward / district / province) and the **new** post-merger format (ward / province), in either direction. > **Auth:** API key as the `apikey` query parameter. Use the **services key** (the `default` consumer key for Map APIs), not the tilemap key. Register at https://maps.vietmap.vn/console-v2/register (60,000 free transactions, about 3,000,000 VND). > **⚠️ Security:** All calls MUST be made from your **backend server**. NEVER expose your API key in frontend/client-side code. > **💬 Need help?** Contact VietMap via Zalo OA: https://zalo.me/3189066936017422854 · Email: maps.info@vietmap.vn ## Quick Summary Vietnam merged its provinces and wards in 2025, so the same place can be written as an **old** address (3 levels: ward, district, province/city) or a **new** address (2 levels: ward, province/city). Migrate-Address rewrites one free-text address into the target format and returns it **pre-split**: house number and street in `name`, each administrative unit with its numeric `id` in `boundaries`. Write the result straight into database columns, no string parsing. | Task | How | |---|---| | **Migrate a whole address database** (one-time or scheduled) | Loop over each record with `migrate_type=1` (old → new); store `display` plus the `boundaries` array | | **Reconcile with a partner still on old addresses** | Convert the other way with `migrate_type=2` (new → old), sending `focus` | | **Clean up hand-typed addresses** | Send the free text; the response is a normalised, split version | | **Sync administrative codes** | Use `boundaries[].id` as the key instead of matching ward/province names as text | > **Tip:** For **live address search** that accepts either format and shows both, use **Autocomplete v4 / Geocode v4** with `display_type=5` or `6` (see `search-geocoding.txt`). They return both formats in one response. Migrate-Address is the tool for converting **stored** addresses. ### Transaction cost | API | Transactions per call | |---|---| | Migrate-Address | 1 address per request. The pricing page has no dedicated formula for it; APIs outside the formula-based group (Tile, Routing, Matrix, TSP, VRP) are typically 1 request = 1 transaction. | Estimate a migration job as one request per address. Track actual usage on the Console Dashboard. --- ## 1. Migrate-Address v3 ### Endpoint ``` GET https://maps.vietmap.vn/api/migrate-address/v3?apikey={apikey}&text={text}&focus={lat,lng}&migrate_type={1|2} ``` - Method `GET`, query parameters only, no request body. - One address per request. Response: one JSON object. ### Parameters | Parameter | Type | Required | Default | Description | Example | |--------------|---------|-----------------------------------|---------|-------------|---------| | apikey | string | yes | | Your VietMap services API key | | | text | string | yes | | Free-text address to convert. Accepts both the old and the new format | `197 tran phu p4 q5` | | focus | string | no — **required when `migrate_type=2`** | | A coordinate near the address as `lat,lng` (latitude first). Disambiguates identical street names | `10.758867,106.675566` | | migrate_type | integer | no | `1` | Conversion direction. Allowed values: `1` = old → new (data migration), `2` = new → old (**requires `focus`**) | `1` | ### Old → New (`migrate_type=1`, default) The request below omits `migrate_type`, so the default `1` applies. ``` GET https://maps.vietmap.vn/api/migrate-address/v3?apikey={apikey}&text=197 tran phu p4 q5&focus=10.75887508,106.67538868 ``` ```json { "address": "Phường Chợ Quán,Thành Phố Hồ Chí Minh", "name": "197 tran phu ", "display": "197 tran phu Phường Chợ Quán,Thành Phố Hồ Chí Minh", "boundaries": [ { "type": 2, "id": 18700, "name": "Chợ Quán", "prefix": "Phường", "full_name": "Phường Chợ Quán" }, { "type": 0, "id": 12, "name": "Hồ Chí Minh", "prefix": "Thành Phố", "full_name": "Thành Phố Hồ Chí Minh" } ] } ``` New format: 2 boundary levels (ward + province/city), no `type=1` entry. ### New → Old (`migrate_type=2`, `focus` required) ``` GET https://maps.vietmap.vn/api/migrate-address/v3?apikey={apikey}&text=197 tran phu phuong cho quan tp ho chi minh&focus=10.75887508,106.67538868&migrate_type=2 ``` ```json { "address": "Phường 4,Quận 5,Thành Phố Hồ Chí Minh", "name": "197 Trần Phú", "display": "197 Trần Phú Phường 4,Quận 5,Thành Phố Hồ Chí Minh", "boundaries": [ { "type": 2, "id": 656652, "name": "4", "prefix": "Phường", "full_name": "Phường 4" }, { "type": 1, "id": 1292, "name": "5", "prefix": "Quận", "full_name": "Quận 5" }, { "type": 0, "id": 12, "name": "Hồ Chí Minh", "prefix": "Thành Phố", "full_name": "Thành Phố Hồ Chí Minh" } ] } ``` Old format: 3 boundary levels (ward + district + province/city). ### Response Fields | Field | Type | Description | |------------|--------|-------------| | address | string | Administrative part of the address only: ward and province/city in the new format; ward, district and province/city in the old format. The house number and street are in `name` | | name | string | House number and street, as parsed from `text` | | display | string | `name` and `address` joined into one string — store this as the full address | | boundaries | array | Administrative units of the address, from the smallest level up (ward → district → province/city) | All four fields are present in every success response. **boundaries[]** | Field | Type | Description | |-----------|--------|-------------| | type | int | Administrative level: `0` = province/city, `1` = district (old format only), `2` = ward | | id | int | Unique identifier of the administrative unit — use it as the key when syncing codes | | name | string | Name of the unit without its prefix, e.g. `Chợ Quán`, `4` | | prefix | string | Level prefix, e.g. `Phường`, `Quận`, `Thành Phố` | | full_name | string | Full name including the prefix, e.g. `Phường 9` | ### HTTP status and errors Success is HTTP `200` with the JSON object above. Check the HTTP status first: `401` has an empty body and `423` a plain-text body, so read the status before parsing JSON. | Status | Meaning | What to do | |--------|---------|------------| | `200` | Success, JSON body | Parse the result | | `400` | A parameter is missing or malformed | Fix the request; compare it with the examples above | | `401` | API key missing, wrong or unknown. Empty body | Check the `apikey` value and that the whole services key was copied | | `423` | Quota used up, the API is not enabled for this key, or a tilemap key was used for a Map API. Plain-text body, e.g. `Your request is limited` | Check usage on the Console and top up; enable the API for the key in Manage API key (or contact VietMap); call with the services key | | `429` | Too many requests in a short time | Slow down, wait and retry, lengthening the wait on each retry (e.g. 1 s, 2 s, 4 s) | | `500` | Server error | Retry later; contact support if it persists | For a batch job: on `429` back off and retry the same record; on `423` stop the job, keep the progress, and resume after the quota is topped up or resets. ### Code — Node.js 18+ (server-side) ```js // Reads the key from the VIETMAP_API_KEY environment variable. const MIGRATE_URL = "https://maps.vietmap.vn/api/migrate-address/v3"; async function migrateAddress({ text, focus, migrateType = 1 }, retries = 3) { const params = new URLSearchParams({ apikey: process.env.VIETMAP_API_KEY, text, // URLSearchParams encodes spaces and diacritics migrate_type: String(migrateType), // 1 = old → new, 2 = new → old }); if (focus) params.set("focus", focus); // "lat,lng"; required when migrateType === 2 for (let attempt = 0; ; attempt++) { const res = await fetch(`${MIGRATE_URL}?${params}`); if (res.status === 429 && attempt < retries) { await new Promise((r) => setTimeout(r, 1000 * 2 ** attempt)); // 1 s, 2 s, 4 s continue; } if (res.status === 401) throw new Error("VIETMAP 401: wrong or missing API key"); if (res.status === 423) throw new Error(`VIETMAP 423: ${await res.text()}`); if (!res.ok) throw new Error(`VIETMAP HTTP ${res.status}`); return res.json(); // { address, name, display, boundaries } } } // Map one result to database columns. Pick levels by `type`, not by array index. function toColumns(r) { const level = (t) => r.boundaries.find((b) => b.type === t); return { full_address: r.display, street: r.name.trim(), ward_id: level(2)?.id ?? null, ward_name: level(2)?.full_name ?? null, district_id: level(1)?.id ?? null, // old format only district_name: level(1)?.full_name ?? null, province_id: level(0)?.id ?? null, province_name: level(0)?.full_name ?? null, }; } // Batch: one request per record, sequential. Keep the old address column. // A thrown 423 stops the loop; resume from the last saved record. for (const row of rows) { const r = await migrateAddress({ text: row.old_address, focus: row.lat_lng }); await saveNewAddress(row.id, toColumns(r)); // your own DB write } ``` ### Code — Python ```python import os import time import requests MIGRATE_URL = "https://maps.vietmap.vn/api/migrate-address/v3" def migrate_address(text, focus=None, migrate_type=1, retries=3): """Convert one address. migrate_type 1 = old -> new, 2 = new -> old (needs focus).""" params = {"apikey": os.environ["VIETMAP_API_KEY"], "text": text, "migrate_type": migrate_type} if focus: params["focus"] = focus # "lat,lng", latitude first for attempt in range(retries + 1): resp = requests.get(MIGRATE_URL, params=params, timeout=30) if resp.status_code == 429 and attempt < retries: time.sleep(2 ** attempt) # 1 s, 2 s, 4 s continue if resp.status_code == 401: raise RuntimeError("VIETMAP 401: wrong or missing API key") if resp.status_code == 423: raise RuntimeError(f"VIETMAP 423: {resp.text}") resp.raise_for_status() return resp.json() # {"address", "name", "display", "boundaries"} def level(result, t): """Boundary of a given type: 0 province/city, 1 district (old format only), 2 ward.""" return next((b for b in result["boundaries"] if b["type"] == t), None) ``` ### cURL ```bash # Old → New (migrate_type=1) curl -G 'https://maps.vietmap.vn/api/migrate-address/v3' \ --data-urlencode 'apikey=YOUR_API_KEY' \ --data-urlencode 'text=197 tran phu p4 q5' \ --data-urlencode 'focus=10.75887508,106.67538868' \ --data-urlencode 'migrate_type=1' # New → Old (migrate_type=2, focus required) curl -G 'https://maps.vietmap.vn/api/migrate-address/v3' \ --data-urlencode 'apikey=YOUR_API_KEY' \ --data-urlencode 'text=197 tran phu phuong cho quan tp ho chi minh' \ --data-urlencode 'focus=10.75887508,106.67538868' \ --data-urlencode 'migrate_type=2' ``` --- ## Integration Flow ### Batch migration (old database → new format) ``` 1. Add columns for the new address (full address, street, ward id/name, province id/name); keep the old address column for legacy lookups 2. For each record, call Migrate-Address with migrate_type=1; send focus=lat,lng when the record has coordinates 3. Store `display` as the full address, the trimmed `name` as the street, and `boundaries[].id` per level (by `type`) as the administrative codes 4. Pace the loop to your plan's rate limit; on 429 back off and retry the record; on 423 stop, keep progress, resume later from the last saved record 5. Re-run the same job on a schedule for newly added records ``` ### Reconcile with a partner on old addresses (new → old) ``` 1. For each new-format address, take its coordinates as lat,lng 2. Call Migrate-Address with migrate_type=2 and focus=lat,lng 3. Exchange `display` / `boundaries` (3 levels: ward, district, province/city) with the partner ``` ### Address entry in your app (both formats, live) ``` 1. Frontend sends the typed text to YOUR backend 2. Backend calls Autocomplete v4 / Geocode v4 with display_type=5 or 6 3. Show both formats from one response (see search-geocoding.txt) ``` --- ## Common Pitfalls - **Send `focus` with `migrate_type=2`.** New → old requires a nearby `lat,lng`. Send `focus` on old → new as well whenever the record has coordinates; it disambiguates identical street names. - **`focus` is `lat,lng`, latitude first**, e.g. `10.75887508,106.67538868`. - **`migrate_type` takes `1` or `2` only.** `1` is the default and the direction for data migration. - **One address per request.** Bulk conversion is a loop of single calls, paced to the rate limit of your plan (see Usage Limits). - **Pick boundary levels by `type`, not by position.** The new format has 2 entries (ward, province/city); the old format has 3 and is the only one with `type=1` (district). - **Key on `boundaries[].id`**, not on ward/province name strings. - **Trim `name` before storing it as its own column.** The old → new example returns `"197 tran phu "` with a trailing space. Store `display` as the full address. - **URL-encode `text`.** Addresses contain spaces, commas and Vietnamese diacritics; use `URLSearchParams`, `requests` `params=` or `curl --data-urlencode`. - **Read the HTTP status before parsing JSON.** `401` returns an empty body and `423` plain text. - **Use the services key.** A tilemap key returns `423` on Map APIs. - **Live dual-format search** is served by Autocomplete v4 / Geocode v4 with `display_type=5` or `6`, which return both formats in one response (see `search-geocoding.txt`). --- ## References - Human docs: https://maps.vietmap.vn/docs/migrate-address/migrate-address-docs/ - Overview: https://maps.vietmap.vn/docs/migrate-address/migrate-address/ - Playground (deep links accept `text`, `focus`, `migrate_type`): https://tools.vietmap.vn/playground/migrate-address - Convert Address tool: https://tools.vietmap.vn/convert-address - OpenAPI 3.1 (operationId `migrateAddress`): https://maps.vietmap.vn/docs/openapi.json - Error codes: https://maps.vietmap.vn/docs/map-api/errors/ - Usage limits: https://maps.vietmap.vn/docs/map-api/console/usage-limitation/ - How pricing works: https://maps.vietmap.vn/docs/map-api/console/request-to-transaction/ --- # VietMap Map Display — Agent Integration Guide > **Covers:** Tile styles · Map Editor · VietMap GL JS · Leaflet · Flutter / React Native / Android / iOS · Traffic overlay · Static Map · Branch Locator & Management > **Auth:** API key required, sent as the `apikey` parameter. Every account gets two keys: the **tilemap key** renders styles and tiles in client SDKs; the **services key** calls the Map APIs (Static Map, search, routing). A Map API called with the tilemap key returns `423`. Register at https://maps.vietmap.vn/console-v2/register to get both keys and 60,000 free transactions (about 3,000,000 VND). > **⚠️ Security:** > - **Client SDKs:** the tilemap key sits in the style and tile URLs the client fetches. Protect it in the Console (https://maps.vietmap.vn/console-v2/) with a domain (HTTP referer) allowlist, IP restrictions and a per-IP rate limit. > - **Static Map:** call from your **backend** with the services key, sent in the form body. > **💬 Need help?** Contact VietMap via Zalo OA: https://zalo.me/3189066936017422854 ## Quick Summary | Surface | Package / Endpoint | Use when | |---|---|---| | Web (WebGL) | `@vietmap/vietmap-gl-js` v6 (§1) | Web apps, dashboards | | Leaflet | `@vietmap/vietmap-gl-leaflet` (§8) | Existing Leaflet apps | | Flutter | `vietmap_flutter_gl` (+ `vietmap_flutter_navigation`, `vietmap_flutter_plugin`) (§2) | Flutter apps | | React Native / Expo | `@vietmap/vietmap-gl-react-native` (+ navigation, `@vietmap/vietmap-api`) (§3) | RN apps; Expo apps via a development build | | Android (native) | `com.github.vietmap-company:maps-sdk-android` (JitPack) (§4) | Native Kotlin/Java apps | | iOS (native) | CocoaPod `VietMap` (§5) | Native Swift apps | | Custom style | Map Editor style link — https://tools.vietmap.vn/map-editor/ (§0) | Brand colors, dark maps, English labels, built-in traffic | | Traffic overlay | `GET /maps/styles/tf/style.json` (§6) | Real-time congestion merged into the running map | | Static Map (PNG) | `POST /api/maps/statics/tm` (§7) | Emails, PDFs, notifications, share previews | | Store map / own data | Branch Locator — https://local.map.zone (§9) | Store map iframe, own layers as MVT | All SDKs render the same **VietMap vector tiles** from a `style.json` URL and the tilemap key. --- ## 0. Tile Styles (shared by every SDK) ### Vector styles (recommended — pass the style.json URL to the SDK's `style` parameter) | Style | Code | URL | |---|---|---| | Default (Street) | `tm` | `https://maps.vietmap.vn/maps/styles/tm/style.json?apikey={apikey}` | | Light | `lm` | `https://maps.vietmap.vn/maps/styles/lm/style.json?apikey={apikey}` | | Dark | `dm` | `https://maps.vietmap.vn/maps/styles/dm/style.json?apikey={apikey}` | | Hybrid (satellite + labels) | `hm` | `https://maps.vietmap.vn/maps/styles/hm/style.json?apikey={apikey}` | - **Version requirement:** VietMap GL JS **v6.0.0 or later**; the mobile SDKs accept these styles on every version. Other GL libraries (MapLibre, Mapbox GL) accept them too. - The response is a MapLibre / Mapbox Style Spec v8 document; the tile URLs inside already carry your `apikey`. Restyle at runtime with `setPaintProperty` / `setLayoutProperty`. - Preview: https://tools.vietmap.vn/playground/tilemap?style=tm¢er=21.0285,105.8542&zoom=14 (swap `style=`) · Live Map https://tools.vietmap.vn/live ### Raster tiles | Style | URL | |---|---| | Satellite | `https://maps.vietmap.vn/maps/tiles/st/{z}/{x}/{y}.png?apikey={apikey}` | XYZ raster source (Leaflet `L.tileLayer`, OpenLayers, GL JS `raster` source): raw imagery without labels — `hm` adds road/POI labels. ### Custom styles (Map Editor) Map Editor (, VIETMAP account sign-in) builds a custom style in the browser. After **Save to cloud**, **Share & embed** gives the **style link** (`…/styles/{styleId}/style.json?…`), an iframe embed, and ready-made code for Web (HTML/npm), React Native, Flutter, Android (Kotlin), iOS (Swift) and cURL. - Pass the style link like a stock URL: `style` (GL JS, Leaflet), `styleString` (Flutter), `mapStyle` (React Native), `Style.Builder().fromUri()` (Android), `styleURL` (iOS). Use it as-is. It carries the map API key — restrict that key in the Console. - Apps receive edits when the owner presses **Update** (**Save as new style** keeps the old version). **New public link** retires the old link and its embeds; **Disable public link** pauses the map everywhere until re-enabled. - Editor features: 8 templates (incl. dark Night, Dark Matter, Navigation; Hybrid satellite), 9 palettes, per-part colors, 4 icon sets, per-category icon color and visibility, POI density, label font/size/color/outline, Vietnamese / English / Bilingual labels, a **Traffic** toggle saved with the style, data layers from Branch Locator (§9), and an **Advanced** per-layer mode. - Preview: `https://tools.vietmap.vn/playground/tilemap?custom={styleId}` · Docs: For a branded, dark or English-labelled base map, point the user to Map Editor rather than hand-writing a style.json. ### Transaction rule Tile map: **25 tile requests = 1 transaction** (100 tiles → 4 transactions). Each unique tile URL is counted once; the SDKs cache tiles and request only what the view needs. Traffic and satellite tiles are tile loads too. --- ## 1. VietMap GL JS (Web SDK) The API follows MapLibre GL JS (`new vietmapgl.Map(...)`, same methods, events and style spec). Use v6.0.0+ for the §0 styles. ### Install ```js // npm install @vietmap/vietmap-gl-js import vietmapgl from "@vietmap/vietmap-gl-js/dist/vietmap-gl"; import "@vietmap/vietmap-gl-js/dist/vietmap-gl.css"; ``` Import from `dist/vietmap-gl` exactly as above: 6.0.1 ships its entry under `dist/` and declares no package `main`, so a bare `"@vietmap/vietmap-gl-js"` import does not resolve. CDN (global `vietmapgl`): ```html ``` ### Minimal map ```html
``` GL JS coordinates are **`[lng, lat]`** (GeoJSON); VietMap REST query parameters use `lat,lng`. ### Constructor options (most useful) | Option | Default | Description | |---|---|---| | `container` / `style` | — | Element or id (no children) / style URL or object | | `center` | `[0,0]` | `[lng, lat]` | | `zoom` / `bearing` / `pitch` | `0` | Initial camera (bearing ccw from north, pitch 0–85) | | `minZoom` / `maxZoom` | `0` / `22` | Zoom clamp (0–24); `minPitch` / `maxPitch` `0` / `60` | | `bounds` / `maxBounds` | — | Initial bounds (overrides center/zoom) / restrict panning | | `hash` / `interactive` | `false` / `true` | Sync camera to URL hash / attach interaction listeners | | `dragPan`, `dragRotate`, `scrollZoom`, `boxZoom`, `keyboard`, `doubleClickZoom`, `touchZoomRotate`, `touchPitch` | `true` | Per-handler switch (runtime: `map.scrollZoom.disable()`) | | `preserveDrawingBuffer` | `false` | `true` enables `getCanvas().toDataURL()` | | `transformRequest` | — | Modify URL / headers / credentials per request | ### API surface - **Camera:** `flyTo`, `easeTo` (animated), `jumpTo` (instant), `fitBounds`, `panBy`, `zoomIn`/`zoomOut`, `setCenter`/`setZoom`/`setBearing`/`setPitch`, `getCenter`/`getZoom`/`getBounds`, `project`/`unproject`. - **Data & style:** `addSource`/`getSource`/`removeSource`, `addLayer`/`getLayer`/`removeLayer`/`moveLayer`, `setPaintProperty`, `setLayoutProperty`, `setFilter`, `loadImage`/`addImage`, `getSource(id).setData(geojson)`, `setStyle`, `queryRenderedFeatures(point, { layers })`. - **Controls:** `NavigationControl`, `ScaleControl`, `FullscreenControl`, `GeolocateControl` → `map.addControl(ctrl, 'top-right')` (or `top-left`, `bottom-*`). - **Markers / popups:** `new vietmapgl.Marker({ color, draggable, anchor, element, offset }).setLngLat([lng,lat]).addTo(map)`; `new vietmapgl.Popup({ offset, closeButton }).setLngLat(..).setText(..)`. `setHTML` does no sanitization — use `setText` for untrusted content. - **Cleanup:** `map.remove()` releases DOM, events, workers and WebGL resources. - **Events:** `load` (add sources/layers here) · `style.load` (every style load, also after `setStyle`) · `idle` · `click` / `mousemove` (`lngLat`, `point`, `features`) · layer-scoped `mouseenter` / `mouseleave` · `movestart|move|moveend` (also `drag*`, `zoom*`, `rotate*`, `pitch*`) · `resize` · `error`. ### Suggested flow — draw a Route v4 result 1. Backend calls `GET https://maps.vietmap.vn/api/route/v4?apikey={services key}&point={lat,lng}&point={lat,lng}&vehicle=car` (trucks: `vehicle=truck&capacity={kg}`; containers: `vehicle=container&container_feet={ft}`; toll cost: `annotations=toll`) and returns `paths[0]`. 2. Decode `paths[0].points` (Google Polyline precision 5, default `points_encoded=true`) with any Polyline-5 decoder (output `[lat, lng]` pairs) and flip each pair to `[lng, lat]`. 3. On `load`: `addSource('route', { type: 'geojson', data: { type: 'Feature', properties: {}, geometry: { type: 'LineString', coordinates } } })`, then a `line` layer on it. 4. `map.fitBounds(paths[0].bbox, { padding: 40 })` — `bbox` is `[minLng, minLat, maxLng, maxLat]`. 5. Markers at the first and last coordinate. Examples and reference: https://maps.vietmap.vn/docs/sdk-web-gl/overview/ --- ## 2. Flutter SDK ```bash flutter pub add vietmap_flutter_gl # map (4.1.1: Flutter 3.10+, Dart 3.0+) flutter pub add vietmap_flutter_navigation # turn-by-turn (optional) flutter pub add vietmap_flutter_plugin # REST API wrapper (optional) ``` Latest versions, platform setup and full API: `https://pub.dev/packages/`. ```dart import 'package:vietmap_flutter_gl/vietmap_flutter_gl.dart'; VietmapGL( styleString: 'https://maps.vietmap.vn/maps/styles/tm/style.json?apikey=YOUR_TILEMAP_KEY', initialCameraPosition: const CameraPosition(target: LatLng(14.5, 108), zoom: 5), ); ``` `styleString` takes any §0 style URL or a Map Editor style link. Coordinates: `LatLng(lat, lng)`. ### API wrapper (vietmap_flutter_plugin 0.5.2) Initialize once: `Vietmap.getInstance('YOUR_API_KEY')`. - `Vietmap.autocompleteV4(...)`, `geoCodeV4(...)`, `reverseV4(...)`, `placeV4(...)` — Autocomplete / Geocode / Reverse / Place v4, the post-merger address format (the unsuffixed `autocomplete`, `geoCode`, `reverse`, `place` call v3). - `Vietmap.routing(VietMapRoutingParams(points: [LatLng(..), LatLng(..)]))` — route between points; `Vietmap.getVietmapStyleUrl()` — style URL for `VietmapGL`. - For toll cost and truck/container routing, call Route v4 over HTTP (§1 flow). - Results are dartz `Either`: `.fold((failure) => ..., (data) => ...)`. Depends on `dio` and `dartz`. Demo: https://github.com/vietmap-company/flutter-navigation-example --- ## 3. React Native SDK ```bash npm i @vietmap/vietmap-gl-react-native npm i @vietmap/vietmap-react-native-navigation # turn-by-turn (optional) npm i @vietmap/vietmap-api # REST API wrapper (optional) ``` ```jsx import { MapView, Camera } from "@vietmap/vietmap-gl-react-native"; ``` - `Camera`: `zoomLevel`, `centerCoordinate` (`[lng, lat]`), `followUserLocation`, `animationMode` (`flyTo` / `moveTo` / `linearTo` / `easeTo`), `animationDuration`. Move the camera by updating `centerCoordinate` from state. - Overlays (children of `MapView`): `UserLocation`; `ShapeSource` (`id`, `shape` = GeoJSON) holding `SymbolLayer` (`style={{ iconImage, iconSize }}`), `LineLayer` (`lineColor`, `lineWidth`, `lineJoin`, `lineCap`) or `FillLayer`. - Events: `onPress`, `onLongPress`, `onDidFinishLoadingMap`, `onDidFinishRenderingMap`. ### API wrapper (`@vietmap/vietmap-api`) `import { VietmapApi } from '@vietmap/vietmap-api'; const vietmapApi = new VietmapApi({ apiKey: VIETMAP_API_KEY });` - `vietmapApi.autoCompleteSearch(new SearchRequest({ text }))` · `vietmapApi.search(new SearchRequest({ text }))` · `vietmapApi.reverse({ latitude, longitude })` - `vietmapApi.route([[lat,lng],[lat,lng]], new RouteRequest({ vehicle: 'car', apikey, points_encoded: true }))` - `new Polyline().decode(encoded, 5)` → `LatLng` list `@vietmap/vietmap-api` 1.1.2 wraps the v3 search APIs. For v4 search (post-merger address format) and Route v4 (truck/container profiles, toll cost), call the REST endpoints directly. ### Expo - Runs in a **development build**: add the package, then `npx expo prebuild` + a local run, or EAS Build (which regenerates `/android/` and `/ios/`). Expo Go ships only Expo's own native modules; no eject needed. - Native settings (Info.plist keys, Android permissions) go in `app.json`. - The map uses the **tilemap key** shipped in the app; Search, Routing and other Map APIs take the **services key**, kept on your backend. Demos: https://github.com/vietmap-company/vietmap-react-native-demo · https://github.com/vietmap-company/react-native-expo-demo --- ## 4. Android SDK (Kotlin) ### Map SDK ```gradle // app/build.gradle — compileSdk 34, targetSdk 34 implementation 'com.github.vietmap-company:maps-sdk-android:2.0.4' implementation 'com.github.vietmap-company:maps-sdk-plugin-localization-android:2.0.0' implementation 'com.github.vietmap-company:vietmap-services-geojson-android:1.0.0' implementation 'com.github.vietmap-company:vietmap-services-turf-android:1.0.2' implementation 'com.squareup.okhttp3:okhttp:4.9.3' implementation 'com.google.code.gson:gson:2.10.1' // settings.gradle → dependencyResolutionManagement.repositories (older projects: allprojects.repositories) maven { url 'https://plugins.gradle.org/m2' } maven { url 'https://jitpack.io' } ``` Manifest permissions: `FOREGROUND_SERVICE`, `ACCESS_COARSE_LOCATION`, `ACCESS_FINE_LOCATION`. Layout: `` ```kotlin override fun onCreate(savedInstanceState: Bundle?) { Vietmap.getInstance(this) // before super.onCreate super.onCreate(savedInstanceState) setContentView(R.layout.activity_map) mapView = findViewById(R.id.vmMapView) mapView.onCreate(savedInstanceState) mapView.getMapAsync { vietMapGL: VietMapGL -> this.vietMapGL = vietMapGL vietMapGL.setStyle( Style.Builder().fromUri("https://maps.vietmap.vn/maps/styles/tm/style.json?apikey=YOUR_TILEMAP_KEY") ) { style -> /* location, overlays */ } } } ``` Forward `onStart/onResume/onPause/onStop/onLowMemory/onDestroy/onSaveInstanceState` to `mapView`. **Feature API** (on `vietMapGL`): - `addMarker(MarkerOptions().position(LatLng(lat, lng)).title(..).snippet(..))`; `addPolylines(listOf(PolylineOptions().add(a).add(b).color(..)))`; `addPolygon(PolygonOptions().addAll(points).fillColor(..))`. - `setOnPolylineClickListener { }`, `setOnPolygonClickListener { }`, `addOnMapClickListener(this)` (`VietMapGL.OnMapClickListener.onMapClick(latLng): Boolean`). - User location (in the `setStyle` callback, after the permission check): `locationComponent.activateLocationComponent(LocationComponentActivationOptions.builder(this, style).build())`, `isLocationComponentEnabled = true`, `setCameraMode(CameraMode.TRACKING_GPS_NORTH, …)`, `locationEngine = LocationEngineDefault.getDefaultLocationEngine(this)`. ### Navigation SDK ```gradle implementation 'com.github.vietmap-company:maps-sdk-android:2.6.0' implementation 'com.github.vietmap-company:maps-sdk-navigation-ui-android:2.3.2' implementation 'com.github.vietmap-company:maps-sdk-navigation-android:2.3.3' implementation 'com.github.vietmap-company:vietmap-services-core:1.0.0' implementation 'com.github.vietmap-company:vietmap-services-directions-models:1.0.1' implementation 'com.github.vietmap-company:vietmap-services-turf-android:1.0.2' implementation 'com.github.vietmap-company:vietmap-services-android:1.1.2' implementation 'com.github.vietmap-company:vietmap-services-geojson-android:1.0.0' // plus: androidx.recyclerview:recyclerview:1.2.1, androidx.cardview:cardview:1.0.0, // androidx.lifecycle:lifecycle-extensions:2.2.0, androidx.core:core-ktx:1.7.0, // com.google.android.gms:play-services-location:21.0.1, com.jakewharton:butterknife:10.2.3, // com.squareup.picasso:picasso:2.8, com.squareup.okhttp3:okhttp:3.2.0, // com.squareup.retrofit2:retrofit:2.9.0, com.squareup.retrofit2:converter-gson:2.0.0-beta4, // com.google.code.gson:gson:2.10.1 ``` **minSdk** 24, **compileSdk / targetSdk** 34, same JitPack repositories. Add the `FOREGROUND_SERVICE_LOCATION` permission; on Android 14+ also declare inside ``: ```xml ``` Flow: 1. `navigation = VietmapNavigation(this, VietmapNavigationOptions.builder().build(), locationEngine)`. 2. `NavigationRoute.builder(this).apikey("YOUR_API_KEY").origin(origin, bearing, bearing).destination(destination, bearing, bearing).build().getRoute(object : Callback { … })` — points are `Point.fromLngLat(lng, lat)`, `bearing` may be `null`. 3. Draw: `NavigationMapRoute(mapView, vietmapGL, "boundary_province").addRoutes(routes)`. 4. `navigation.addProgressChangeListener(this)` (+ `addOffRouteListener`, `addMilestoneEventListener`, `addFasterRouteListener`, `addNavigationEventListener`), then `navigation.startNavigation(route)`; finish with `stopNavigation()` and remove the listeners. 5. `onProgressChange(location, routeProgress)` carries progress; `userOffRoute(location)` triggers a reroute. 6. Voice: `NavigationSpeechPlayer(SpeechPlayerProvider(this, "vi", true))` plays `SpeechAnnouncement`s from `onMilestoneEvent`, through the system TTS engine (Google, `Locale("vi", "VN")`). 7. Simulation: `ReplayRouteLocationEngine().assign(route)` as `navigation.locationEngine`. Demo: https://github.com/vietmap-company/vietmap-android-navigation-example --- ## 5. iOS SDK (Swift) ### Map SDK ```ruby pod 'VietMap', '~> 1.2.2' ``` `pod install --repo-update`, then open the `.xcworkspace`. `Info.plist`: `NSLocationWhenInUseUsageDescription`, `NSLocationAlwaysAndWhenInUseUsageDescription`, `NSLocationAlwaysUsageDescription`, and `UIBackgroundModes` = `audio`, `location`. ```swift import VietMap mapView = MGLMapView(frame: view.bounds, styleURL: URL(string: "https://maps.vietmap.vn/maps/styles/tm/style.json?apikey=YOUR_TILEMAP_KEY")) mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight] mapView.delegate = self // MGLMapViewDelegate mapView.userTrackingMode = .follow view.addSubview(mapView) ``` - Shapes: `MGLPointAnnotation` (`coordinate`, `title`), `MGLPolyline(coordinates:count:)`, `MGLPolygon(coordinates:count:)` → `mapView.addAnnotation(_:)`. Screen point → coordinate: `mapView.convert(point, toCoordinateFrom: mapView)`. - Delegate (most used): `mapViewDidFinishLoadingMap`, `regionDidChangeAnimated`, `didSelect` / `didDeselect`, `didUpdate` (user location), `imageFor` → `MGLAnnotationImage`, `viewFor` → `MGLAnnotationView`, `annotationCanShowCallout`, `strokeColorForShapeAnnotation`, `fillColorForPolygonAnnotation`, `lineWidthForPolylineAnnotation`. ### Navigation SDK ```ruby pod 'VietMap', '~> 1.2.2' pod 'VietMapNavigation', '~> 2.1.8' pod 'VietMapCoreNavigation', '~> 2.1.6' ``` `Info.plist` (plus the location keys above): ```xml VietMapURL https://maps.vietmap.vn/maps/styles/tm/style.json?apikey=YOUR_TILEMAP_KEY VietMapAPIBaseURL https://maps.vietmap.vn/api/navigations/route/ VietMapAccessToken YOUR_API_KEY ``` ```swift import VietMapCoreNavigation import VietMapNavigation import VietMapDirections let styleURL = Bundle.main.object(forInfoDictionaryKey: "VietMapURL") as! String let mapView = NavigationMapView(frame: view.bounds, styleURL: URL(string: styleURL)) Locale.localeVoice = "vi" let options = NavigationRouteOptions(waypoints: [ Waypoint(location: userLocation, heading: heading, name: "User location"), Waypoint(coordinate: destination, name: "Destination")]) Directions.shared.calculate(options) { waypoints, routes, error in guard let routes = routes else { return } mapView.showRoutes(routes) } let nav = NavigationViewController(for: route, styles: [NightStyle()], locationManager: NavigationLocationManager()) nav.delegate = self present(nav, animated: true) ``` - `NotificationCenter`: `.routeControllerProgressDidChange` (userInfo `RouteControllerNotificationUserInfoKey.routeProgressKey` / `.locationKey`), `.routeControllerDidReroute`. - `NavigationMapViewDelegate`: `didSelect waypoint`, `didSelect route`. `NavigationViewControllerDelegate`: `didArriveAt` (return `true` to start the next leg), `navigationViewControllerDidDismiss(_:byCanceling:)`. Demo (TestFlight): https://testflight.apple.com/join/72lT6D0w --- ## 6. Traffic Overlay (real-time congestion) A **vector style** coloring real-time congestion per direction of travel. Merge its `sources` and `layers` into the running map (as the map's `style` it would replace the base map). ``` GET https://maps.vietmap.vn/maps/styles/tf/style.json?apikey={apikey} ``` ### Merge (VietMap GL JS) ```js const APIKEY = 'YOUR_TILEMAP_KEY'; async function addTraffic(map) { const tf = await fetch(`https://maps.vietmap.vn/maps/styles/tf/style.json?apikey=${APIKEY}`) .then((r) => r.json()); for (const [id, source] of Object.entries(tf.sources)) { if (!map.getSource(id)) map.addSource(id, source); } for (const layer of tf.layers) { if (!map.getLayer(layer.id)) map.addLayer(layer); } } map.on('style.load', () => addTraffic(map)); // setStyle wipes custom layers; this re-adds them ``` ### Contents - Source `traffic`: vector tiles `https://maps.vietmap.vn/maps/tiles/tf/{z}/{x}/{y}.pbf?apikey={apikey}`, `maxzoom` 15 (overzoomed beyond), source layer `jam`. - Layers `traffic-left` (`lcolor`, `oneway <= 0`), `traffic-right` (`rcolor`, `oneway >= 0`), `traffic-border-left` / `traffic-border-right` (white casing, `oneway == 0`). Two-way roads draw two offset lines with casing; one-way roads one line. - All layers have `minzoom` 10. Color lives in the data (`["get", "lcolor"]`); for your own palette override `line-color` on `traffic-left` / `traffic-right`. - Remove: `removeLayer` for the four ids, then `removeSource('traffic')`. - **Map Editor style:** turn on **Traffic** in the editor — saved with the style, so every app using the link shows traffic with no code. **Leaflet:** merge into `gl.getVietmapMap()` (§8). **Congestion as data:** Route v4 `annotations=congestion`. Preview: https://tools.vietmap.vn/playground/tilemap?style=tm¢er=21.0285,105.8542&zoom=14&traffic=true · Billing: vector tiles, tile-map rule (§0). --- ## 7. Static Map (server-side PNG) Returns a **PNG** centered on a coordinate with a marker and address label, for emails, notifications and share previews. ``` POST https://maps.vietmap.vn/api/maps/statics/tm Content-Type: multipart/form-data ``` | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | lat | number | yes | — | Center latitude | | lng | number | yes | — | Center longitude | | apikey | string | yes | — | Services key, in the form body | | zoom | number | no | `15` | 0 (world) – 20 (building) | | size | string | no | `"600x400"` | `"WIDTHxHEIGHT"` in pixels | | address | string | no | Auto | Label under the marker; omitted → reverse-geocoded from `lat`/`lng` | | markerUrl | string | no | Default pin | URL of a custom marker icon | | markerFile | file | no | — | Uploaded marker icon (max 10 MB); takes precedence over `markerUrl` | Response: **200** `image/png` bytes · **400** missing/invalid parameter (e.g. `size` format) · **401** missing or wrong key · **413** `markerFile` over 10 MB · **423** key out of quota or API not enabled for it · **429** rate limit · **500** render error. ```bash curl -L 'https://maps.vietmap.vn/api/maps/statics/tm' \ --form 'lat="10.759157"' \ --form 'lng="106.675859"' \ --form 'apikey="YOUR_SERVICES_KEY"' \ --form 'zoom="17"' \ --form 'size="800x400"' \ --form 'address="197 Trần Phú, phường Chợ Quán, thành phố Hồ Chí Minh"' \ --output map.png ``` Node 18+: `FormData` with the same fields → `fetch(url, { method: "POST", body: form })` → `Buffer.from(await res.arrayBuffer())`. For HTML email, serve the PNG from a backend route (e.g. `/map.png?lat=…&lng=…`) used as the ``. --- ## 8. Leaflet Integration `@vietmap/vietmap-gl-leaflet` adds VietMap GL JS to a Leaflet map as a layer: the Leaflet API and plugins stay, WebGL renders the vector base map. Include order is mandatory: **Leaflet → VietMap GL JS → plugin**. ```html
``` npm: `npm install leaflet @vietmap/vietmap-gl-js @vietmap/vietmap-gl-leaflet` Layer options: `style` (style.json URL incl. `apikey`, or a Map Editor style link) · `pane` (default `tilePane`, below markers and popups) · `padding` (`0.1` = 10% beyond the viewport per side) · `interactive` (`false`) · `updateInterval` (`32` ms between syncs while panning). - `gl.getVietmapMap()` returns the GL JS `Map` (add traffic, §6, on its `load`). Keep Leaflet's attribution control on — the plugin moves the style's attribution into it. - The binding renders a north-up 2D map; for bearing/pitch, or without Leaflet plugins, VietMap GL JS directly is faster and fuller. - Satellite only: `L.tileLayer('https://maps.vietmap.vn/maps/tiles/st/{z}/{x}/{y}.png?apikey=YOUR_TILEMAP_KEY').addTo(map)` — no plugin needed. --- ## 9. Branch Locator & Management (Local Store) No-code platform at **https://local.map.zone** for stores and branches (address, contact, opening hours, category icon, auto-geocoded or pinned coordinates), grouped into data layers that viewers toggle and filter. **Iframe embed** (`{your-map-id}` from the dashboard; `embed=true` hides navigation chrome, `sidebar=true` shows the location list): ```html ``` **MVT layer in VietMap GL JS** — each data layer is served as vector tiles: only viewport tiles load, the raw dataset stays off the client, 10k+ points stay smooth. `{layer-id}` is in the layer's **Share / Embed** settings. ```js map.on('load', () => { map.addSource('store-layer', { type: 'vector', tiles: ['https://local.map.zone/api/layers/{layer-id}/mvt/{z}/{x}/{y}'], minzoom: 0, maxzoom: 22 }); map.addLayer({ id: 'store-points', type: 'circle', source: 'store-layer', 'source-layer': 'default', paint: { 'circle-radius': 8, 'circle-color': '#E53935' } }); }); ``` Map Editor's **Add data layer** draws these layers into a custom style (§0); Excel imports run in MapZone. --- ## Coordinate Order Cheat-sheet | Layer | Order | |---|---| | VietMap GL JS, GeoJSON, React Native | `[lng, lat]` | | Leaflet (`setView`, `L.marker`) | `[lat, lng]` | | Flutter / Android `LatLng` | `LatLng(lat, lng)` | | iOS | `CLLocationCoordinate2D(latitude:longitude:)` | | Android navigation `Point` | `Point.fromLngLat(lng, lat)` | | Google Polyline decoder output | `[lat, lng]` — flip before feeding GL JS | | Route v4 / Matrix v4 / TSP v4 query | `point=lat,lng` | | VRP / Map Matching (`match-tolls`) bodies | `[lng, lat]` | | Static Map | separate `lat`, `lng` fields | --- ## Common Pitfalls - **`[lng, lat]` in GL JS and React Native**; `lat,lng` in REST query parameters. - **GL JS:** import from `@vietmap/vietmap-gl-js/dist/vietmap-gl` (+ `.css`), v6.0.0+ for the §0 styles; add sources/layers in `load` / `style.load`; update GeoJSON with `setData`; guard ids with `getSource` / `getLayer` in HMR; `map.remove()` on unmount. - **Right key, right place:** tilemap key in style/tile URLs (domain/IP-restricted); services key for Static Map and other Map APIs. - **One map instance per page** keeps tile transactions lean (base, traffic and raster tiles all count). - **Traffic is an overlay** on a base style, rendered from zoom 10. **Map Editor links are live:** **Update** changes every app using them. - **Static Map:** `size` is a `"WxH"` string; `apikey` goes in the form body, from your backend. - **Android:** `Vietmap.getInstance(this)` before `super.onCreate`; forward lifecycle calls to `mapView`. **Expo:** development build or EAS Build. --- ## Contact & Support - **Email:** maps.info@vietmap.vn · **Zalo OA:** https://zalo.me/3189066936017422854 - **API docs:** https://maps.vietmap.vn/docs/map-api/overview/ · **SDK Web docs:** https://maps.vietmap.vn/docs/sdk-web-gl/overview/ - **GitHub:** https://github.com/vietmap-company · **Support site:** https://maps.vietmap.vn/web#contact-section --- # VIETMAP Console, API Keys & Pricing — Agent Integration Guide > **Audience:** This file is context for an AI agent helping a customer **get, secure and manage** VIETMAP API keys and estimate cost — not an API reference. Use it when the customer asks "how do I get a key", "which key goes where", "how do I restrict it", "why do I get 423", "why is my usage so high", "how much will this cost" or "how do I pay". > **Support:** Zalo OA https://zalo.me/3189066936017422854 · Email maps.info@vietmap.vn · Website https://maps.vietmap.vn ## Quick Summary - **Register:** https://maps.vietmap.vn/console-v2/register - **Console:** https://maps.vietmap.vn/console-v2/ - **Payments (plans, top-up):** https://maps.vietmap.vn/console-v2/payments - **Playground:** https://tools.vietmap.vn/playground - **Live Map:** https://tools.vietmap.vn/live - **New accounts:** 60,000 free transactions (about 3,000,000 VND). No credit card required. - **Auth:** every Map API request sends the key in the `apikey` query parameter. Every account comes with **two consumers (projects), each with its own API key**. Each key has its own usage limits and permissions, and the two are not interchangeable: | Key | Console consumer | Use it for | Where it lives | |-----|------------------|------------|----------------| | **Services key** | `default` | Map APIs: address search (Autocomplete, Geocode, Place), Reverse, routing, matrix, route optimization (TSP, VRP), … | Backend only. Read it from an environment variable (e.g. `VIETMAP_API_KEY`); never put it in browser or app code. | | **Tilemap key** | `public tile` | Rendering the base map in the SDKs, e.g. style URL `https://maps.vietmap.vn/maps/styles/tm/style.json?apikey=YOUR_TILEMAP_KEY` | Client code (web/mobile), restricted to your referring domains (and IPs) in the Console. | A Map API called with the tilemap key returns `423`. Map APIs always take the services key. --- ## 1. Register an Account 1. Open **https://maps.vietmap.vn/console-v2/register**. 2. Fill in all required fields. - **Student:** school name as Company Name, education email as Company Email. - **Individual:** `Individual` as Company Name, personal email as Company Email. 3. Read the [Terms and Conditions](https://maps.vietmap.vn/console/privacy-policy) and check **"I accept the terms and conditions"**. 4. Submit the form. A verification email is sent to the address entered. 5. Open the verification link (check the inbox and the spam folder). The link is valid for **24 hours**. 6. Right after verification, a **second email** titled **"Account Registration Information"** delivers both API keys (services key + tilemap key). The keys work immediately; there is no approval step. ### First request (services key) ```bash export VIETMAP_API_KEY="your services key" curl -G 'https://maps.vietmap.vn/api/autocomplete/v4' \ --data-urlencode "apikey=$VIETMAP_API_KEY" \ --data-urlencode 'text=197 tran phu' \ --data-urlencode 'focus=10.7588,106.6753' ``` Response (trimmed): ```json [ { "ref_id": "auto:RAkPcicmZ3d-NQ...", "address": "Phường 4,Quận 5,Thành Phố Hồ Chí Minh", "name": "197 Trần Phú", "display": "197 Trần Phú Phường 4,Quận 5,Thành Phố Hồ Chí Minh" } ] ``` | Code | Meaning | |-------|---------| | `200` | Success | | `401` | Wrong API key | | `423` | Out of quota, or this API is not enabled for the key — details are in the response body | Without a command line, type the same address into the Autocomplete Playground (https://tools.vietmap.vn/playground/autocomplete) to see the result on a map. To try several APIs at once, use the Postman collection: https://app.getpostman.com/run-collection/10912981-433d17b2-76d7-416e-beb2-468b9682b7a7?action=collection%2Ffork --- ## 2. Manage Keys in the Console Log in at **https://maps.vietmap.vn/console-v2/** with the registered email and password. Keys are organized by **Consumer (project)**: left menu → **Consumers** → **Detail** on a project lists and manages its API keys. Available actions: - **Add / delete API keys** - **Whitelist IPs** (servers allowed to use the key) - **Restrict by referring domain** (websites allowed to use the key) - **Limit usage per key or per IP** - **Enable / disable specific APIs** per key (e.g. Autocomplete + Place on, Route off) - **Quota per API** - **Regenerate** a key Changing quotas and per-API limits requires **administrator** permission (section 6). **Tilemap keys** have dedicated controls: tile access by IP, and selected features turned off to optimize usage. Add your **referring domains** to the tilemap key so tile usage, and the charges for it, come only from your own sites. ### Security checklist 1. Keep the **services key** on the backend, read from an environment variable. Never commit it or ship it in browser or app code. 2. For any key used in a web application or otherwise publicly accessible (the tilemap key): restrict it to your domains, add per-key or per-IP limits, and enable only the APIs it needs. 3. Review key usage in the console regularly to spot unusual activity. 4. If a key may be compromised, regenerate it in the console immediately and roll the new key out to every deployment. 5. Never paste a raw key into chat, screenshots, public repos or unrestricted client code. In code samples use `YOUR_API_KEY` / `{apikey}`. 6. **Tilemap key especially:** one map view loads many tiles (25 tile requests = 1 transaction), so referring-domain restrictions keep that volume tied to your own apps. 7. For anything unusual, contact VIETMAP support. --- ## 3. Monitor Usage ### Daily Report Console → left menu → **Daily Report**: - Total requests per API key - Breakdown of requests by API service - Daily usage over time - Filters: date range, and project via the **Consumers** dropdown Daily Report counts **requests**; apply the formulas in section 4 to turn them into transactions. Use it for **billing reconciliation** and **anomaly detection** (a sudden spike suggests an exposed key or a client stuck in a loop). ### Dashboard: Total Quota card - Shows the percentage used, a progress bar and the **Used / Total** figures (Total / Used / Available). - Progress bar color: | Usage | Color | Meaning | |-----------|--------|---------| | Below 80% | Green | Normal. | | 80%–99% | Yellow | Almost full. Top up to keep the service running. | | 100%+ | Red | Quota used up. The percentage can exceed 100% (e.g. 116%); the available figure is hidden. | - **Detail** expands the card into a per-API breakdown. - VIETMAP emails the account automatically at **80%** and **100%** of the total quota. --- ## 4. Requests vs Transactions (Billing Unit) This is the **single most important concept** to explain to customers. VIETMAP counts usage, quotas and billing in **transactions**, and `1 request ≠ 1 transaction` for every API. - **Request:** one HTTP call from the app to a VIETMAP endpoint (path, method, query/body parameters, API key). - **Transaction:** the billing/usage unit. Most APIs count 1 request as 1 transaction; requests that cover several units of work (routing with many waypoints, matrix, route optimization) count as several. ### Summary table | API | Description | Requests | Transactions | |---------------------|------------------------------------------------------|------------------:|------------------------:| | Tilemap | Tile images for map rendering | 25 tile requests | 1 | | Geocoding (Search) | Address/place → coordinates | 1 | 1 | | Reverse | Coordinates → address/place | 1 | 1 | | Autocomplete | Suggestions as the user types | 1 | 1 | | Place | `ref_id` → address details and coordinates | 1 | 1 | | Routing | Multi-stop route for different vehicle types | 1 | `1 × (⌊points/5⌋ + 1)` | | Matrix | Travel time/distance, n origins × m destinations | 1 | `n × m` | | TSP | Route optimization for 1 vehicle across m stops | 1 | `m` | | VRP | Route optimization for n vehicles across m stops | 1 | `n × m` | | Isochrone | Reachable area by mode and travel time | 1 | 1 | Each API's own page notes any special-case rule. ### Formulas - **Tilemap:** `transactions = tile requests / 25` — 100 tiles → 4 transactions. The SDKs request tiles for the current view, zoom level and user interactions; their built-in cache avoids re-fetching tiles, and each unique tile URL is counted only once. - **Routing:** `transactions = 1 × (⌊points / 5⌋ + 1)`, where `points` = number of waypoints (stops): one base transaction plus one per full group of 5 points. - Up to 4 points → 1 · 5–9 points → 2 · 10–14 points → 3 - 5 points → 2 · 8 points → 2 · 10 points → 3 · 12 points → 3 - **Matrix:** `n × m`, n = origins (vehicles), m = destinations (points, customers, …). 2 × 5 = 10 · 3 × 8 = 24 · 4 × 10 = 40 transactions. - **TSP:** `m` = number of stops (single-vehicle optimization). - **VRP:** `n × m` = vehicles × stops — 10 vehicles × 100 stops = 1,000 transactions in a single call. To estimate usage: aggregate expected daily or monthly requests per API, apply the formulas above, and sum the transactions. ### Convert transactions ⇄ VND **Pricing Converter:** https://maps.vietmap.vn/docs/map-api/console/pricing-converter/ — enter a budget (VND) to estimate transactions, or transactions to estimate the budget. Results are estimates based on the static public pricing tiers; the plans on sale are listed in Console → **Payments**. The converter uses **graduated tiers**: each block of 500,000 transactions is priced at its own rate, and the total is the sum across blocks. | Transactions (cumulative) | VND / transaction | Budget at tier start (VND) | |---------------------------|------------------:|---------------------------:| | 0 – 500,000 | 50 | 0 | | 500,000 – 1,000,000 | 46 | 25,000,000 | | 1,000,000 – 1,500,000 | 42.5 | 48,000,000 | | 1,500,000 – 2,000,000 | 39 | 69,250,000 | | 2,000,000 – 2,500,000 | 36 | 88,750,000 | | 2,500,000 – 3,000,000 | 33 | 106,750,000 | | 3,000,000 – 3,500,000 | 30.5 | 123,250,000 | | 3,500,000 – 4,000,000 | 28 | 138,500,000 | | 4,000,000 – 4,500,000 | 26 | 152,500,000 | | 4,500,000 – 5,000,000 | 24 | 165,500,000 | | 5,000,000 – 5,500,000 | 22 | 177,500,000 | | 5,500,000 – 6,000,000 | 20 | 188,500,000 | | 6,000,000 – 6,500,000 | 18.5 | 198,500,000 | | 6,500,000 – 7,000,000 | 17 | 207,750,000 | | 7,000,000 – 7,500,000 | 15.5 | 216,250,000 | | 7,500,000 – 8,000,000 | 14.5 | 224,000,000 | | 8,000,000 – 8,500,000 | 13.5 | 231,250,000 | | 8,500,000 – 9,000,000 | 12.5 | 238,000,000 | | 9,000,000 – 9,500,000 | 11.5 | 244,250,000 | | 9,500,000 – 10,000,000 | 10.5 | 250,000,000 | | 10,000,000 + | 10 | 255,250,000 | - **Transactions → VND:** `budget = tier start budget + (transactions − tier start transactions) × tier price` - **VND → transactions:** `transactions = tier start transactions + (budget − tier start budget) / tier price` - Examples: 60,000 transactions → 3,000,000 VND · 1,200,000 transactions → 48,000,000 + 200,000 × 42.5 = 56,500,000 VND · 60,000,000 VND → 1,000,000 + 12,000,000 / 42.5 ≈ 1,282,353 transactions. Quote converter figures to customers as estimates, and point them to Console → Payments or VIETMAP sales for the plan they will buy. --- ## 5. Pay and Top Up Payments top up the account balance in the Console. A Trial account that pays is granted administrator permission and higher limits (section 6). 1. **Choose a plan:** Console → **Payments** (https://maps.vietmap.vn/console-v2/payments). Plans differ in benefits and credit amounts; pick one and click **Buy Now**. **Flexible Top-Up** takes a custom amount (or custom credits) instead. 2. **VAT information:** VAT invoices are available for all payments. Fill in correct billing information before paying, or click **Skip** when no invoice is needed. 3. **Payment method:** pick a bank from the list. It lists the *receiving* banks of VIETMAP's payment gateway partner, not the payer's own bank, so any bank in the list works. Several Vietnamese banks are listed, so another one can be picked if one is unavailable at payment time. 4. **Transfer:** a QR code appears with the exact amount and reference code. Scan it in the banking app and confirm the amount and description exactly as shown; editing them may cancel processing. Once the bank confirms the transfer, the balance updates automatically, usually within a few minutes. 5. **Invoice:** appears in **Payment History**, to view or download as PDF. One invoice is emailed to the registered address for each successful payment. VAT invoices are issued after the payment is confirmed. 6. **Update VAT info for later payments:** User icon (top right) → **Update VAT Info** → **Save**. Applies to future invoices. | Field | Description | |--------------|-------------| | Company Name | Legal name of the organization | | Tax Code | Vietnamese tax identification number | | Address | Registered business address | | Email | Address that receives the invoice | Payment issues, extra invoice copies, or an invoice reissued with corrected information: Zalo OA https://zalo.me/3189066936017422854 or maps.info@vietmap.vn. --- ## 6. Usage Limits & Account Types | Account type | Limit | Description | |----------------|-----------------------------------------------|-------------| | **Trial** | **500 / day** + **100–200 / minute** per API | Free evaluation account. Paying upgrades it: administrator permission and higher limits. | | **Standard** | By total quota | Paid account billed by usage against a total quota, no per-API daily caps. | | **Enterprise** | **200 requests / minute** (default, adjustable) | Paid account with a much higher total quota, no per-API daily caps; contact support to raise the rate limit. Accounts created by VIETMAP Sales are Enterprise by default. | The services key (`default` consumer) is limited by the account type and API limits; the tilemap key (`public tile` consumer) has its own limits and permissions. ### Quota concepts - **Total Quota** — overall quota of the account: **Total / Used / Available**. - **Daily Quota** — per-day quota of the account (drives daily-limit warnings). - **Limit per API** — rate limit of one API, **Per Minute / Per Hour / Per Day** (Trial). - **Daily request per API** — today's requests for one API against its daily limit, e.g. `500/500`. ### Default Trial limits On Trial accounts, the expanded Total Quota card shows a read-only table (columns: API · Per Minute · Per Day · Today · Status). Status `x/x` (red) = the API used its daily allowance for today; `on` = enabled; `off` = enabled on request. Only Trial accounts see this table. | API (console label) | Per minute | Per day | Default | |---------------------|--------------|---------------|---------| | Auto Complete | 200 | no daily cap | On | | Reverse | 200 | 500 | On | | Geocode | 200 | 500 | On | | Match | 200 | 500 | On | | Route | 200 | 500 | On | | Static | 200 | 500 | On | | TSP | 100 | 500 | On | | VRP | 100 | 500 | On | | Matrix | 100 | 500 | On | | Isochrone | 100 | 500 | On | | Place | 100 | 500 | On | | Tile | up to 5,000 | — | Off | APIs at `Off` are enabled on request, and higher limits come with an upgrade: contact VIETMAP support. ### When a limit is reached - **Trial:** an API at **500/500** for today resumes when the daily limit resets the next day, or as soon as the account is upgraded. - **Standard:** usage is billed against the **total quota**. At 100% (red card), requests are blocked until the account is topped up. - **Enterprise:** calls above the **rate limit (200 requests/minute by default)** are rejected — wait a minute and retry, or ask support to raise the limit. The daily quota warns at 80% (yellow) and blocks at 100% (red) for the rest of the day. Top up or upgrade before reaching the cap to keep the service running without interruption. ### Permissions Adjusting quotas and per-API limits requires **administrator** permission. | Account / role | What it can do | |----------------|----------------| | **Trial** | View all information and copy the API key. Upgrading (payment) grants administrator permission and higher limits. | | **Regular user** (paid account, not admin) | View all information and copy the API key. Limit changes go through the account's administrator. | | **Administrator** | View everything, edit limits directly, then **Save**. | Every role can view all account information and copy its API key. --- ## 7. Errors Tied to Keys and Quota | Status | Meaning | What to do | |--------|---------|------------| | `401` | API key missing, wrong or unknown. Empty body. | Check the `apikey` value and that the whole services key was copied. | | `423` | Quota used up, API not enabled for this key, or tilemap key used for a Map API. Plain-text body, e.g. `Your request is limited`. | See the checklist below. | | `429` | Too many requests in a short time. | Slow down, wait and retry, lengthening the wait on each retry. | `401` has an empty body and `423` a plain-text body, so read the HTTP status before parsing JSON. **`423` checklist** 1. **Quota used up.** Trial: each API stops at 500 requests a day (Autocomplete has no daily cap) and resumes the next day. Standard: total quota used — top up in Payments. Enterprise: daily quota at 100% — blocked for the rest of the day. Check the Daily Report and the Total Quota card. 2. **API not enabled for the key.** Check that the API is on for the key (Console → Consumers → Detail), or contact VIETMAP to enable it. On Trial, Tile starts `Off`. 3. **Wrong key type.** The tilemap key only renders the map; call Map APIs with the services key. **Routing `code` field.** Route v4, TSP v4 and Matrix v4 also return `code` in the JSON body, so check it as well as the HTTP status. Quota-related values: | `code` | Meaning | What to do | |---------------------|---------|------------| | `OVER_DAILY_LIMIT` | The key went over its daily limit. | Wait for the next day, or raise the limit. | | `MAX_POINTS_EXCEED` | More points than the plan allows. | Send fewer points, or split the request. | One wrapper for every Map API call (Node.js 18+, server-side): retries `429`, reports `401` / `423`, checks routing `code`. ```js async function callVietmap(url, init, retries = 3) { for (let attempt = 0; ; attempt++) { const res = await fetch(url, init); if (res.status === 429 && attempt < retries) { await new Promise((r) => setTimeout(r, 1000 * 2 ** attempt)); // 1 s, 2 s, 4 s continue; } if (res.status === 401) throw new Error("VIETMAP 401: wrong or missing API key"); if (res.status === 423) throw new Error(`VIETMAP 423: ${await res.text()}`); if (!res.ok) throw new Error(`VIETMAP HTTP ${res.status}`); const data = await res.json(); // Static Map returns an image: use res.arrayBuffer() // Routing APIs return "OK" on success; VRP returns 0 and Geofencing null if (typeof data.code === "string" && data.code !== "OK") { throw new Error(`VIETMAP ${data.code}: ${data.messages ?? ""}`); } return data; } } ``` --- ## 8. Common Cost-Reduction Patterns When a customer's usage is higher than expected, check these: - **Autocomplete while typing, Place v4 on selection.** Call Autocomplete as the user types and Place v4 only for the result the user picks (pass its `ref_id` unchanged). Each call is 1 transaction. - **Tile caching.** Keep the SDKs' built-in tile cache: each unique tile URL is counted once, and 25 tile requests make 1 transaction. - **Restricted client-side keys.** Referring domains, IP whitelist and per-key / per-IP limits on the tilemap key keep usage tied to the customer's own apps. - **Route for one route, Matrix for many.** A route with up to 4 points is 1 transaction; Matrix is `n × m` and fits N×M comparisons. - **VRP re-planning cadence.** One VRP call costs vehicles × stops. Re-plan per planning window rather than on every vehicle update. - **Only the APIs in use.** Enable just the APIs each key needs and set per-API quotas. --- ## 9. Agent Integration Guidance When helping a customer integrate VIETMAP APIs for the first time, guide them roughly in this order: 1. **Register** at https://maps.vietmap.vn/console-v2/register and verify the email within 24 hours. 2. **Take both keys** from the "Account Registration Information" email: services key → backend environment variable (e.g. `VIETMAP_API_KEY`); tilemap key → the map style URL in client code. 3. **In the console**, before anything goes to production: - Group keys by project under **Consumers**; add keys as needed - Tilemap key: add referring domains (and IPs) - Services key: whitelist the server IPs - Set per-key, per-IP and per-API limits (administrator permission) - Enable only the APIs in use 4. **Keep keys out of source control.** Code samples use `YOUR_API_KEY` / `{apikey}`. 5. **Verify the key** with the first request in section 1, the Playground (https://tools.vietmap.vn/playground) or the Postman collection. 6. **Handle `401`, `423` and `429`** and the routing `code` field (section 7). 7. **Check the account limits** (section 6) and **estimate monthly transactions and budget** with the formulas and converter (section 4). 8. **After deploy**, watch the Daily Report and the Total Quota card for a few days to confirm usage matches expectations. VIETMAP emails at 80% and 100% of the total quota; top up before the cap (section 5). --- ## 10. Useful Links Recap | Purpose | URL | |-------------------------------------------|-----| | Register | https://maps.vietmap.vn/console-v2/register | | Console (manage keys, monitor, restrict) | https://maps.vietmap.vn/console-v2/ | | Payments (plans, top-up) | https://maps.vietmap.vn/console-v2/payments | | Pricing Converter (VND ⇄ transactions) | https://maps.vietmap.vn/docs/map-api/console/pricing-converter/ | | How pricing works | https://maps.vietmap.vn/docs/map-api/console/request-to-transaction/ | | Usage limits | https://maps.vietmap.vn/docs/map-api/console/usage-limitation/ | | Error codes | https://maps.vietmap.vn/docs/map-api/errors/ | | Quickstart | https://maps.vietmap.vn/docs/map-api/quickstart/ | | Terms and Conditions | https://maps.vietmap.vn/console/privacy-policy | | Playground (try APIs) | https://tools.vietmap.vn/playground | | Autocomplete Playground | https://tools.vietmap.vn/playground/autocomplete | | Postman collection | https://app.getpostman.com/run-collection/10912981-433d17b2-76d7-416e-beb2-468b9682b7a7?action=collection%2Ffork | | Live Map | https://tools.vietmap.vn/live | | Support (Zalo OA) | https://zalo.me/3189066936017422854 | | Support (Email) | maps.info@vietmap.vn | | Main site | https://maps.vietmap.vn |