Indonesian Geocoding API: How to Change Addresses to Coordinates and Find the Nearest Branch (curl, Node.js, Python)

By , Tim Engineering APIPedia · Published · Updated · 11 min read

APIPedia's geocoding API converts addresses into coordinates via GET /v1/maps/geocode. Nearby branch tutorial with curl, Node.js, and Python examples.

APIPedia cover: title "Address becomes coordinates, then look for the nearest branch" with chips GET /v1/maps/geocode and GET /v1/maps/reverse, and terminal card: Malang City Square geocode results (lat -7.9826131, lon 112.63082) and distance to three branches, nearest 0.70 km.

APIPedia's geocoding API (a Maps Encoder product) converts place names or addresses to coordinates via GET /v1/maps/geocode, and converts coordinates to addresses via GET /v1/maps/reverse. The result contains lat, lon, display_name, and the parsed address per section.

This tutorial uses a case that often appears in online stores and service applications: the buyer types in the address, then the system shows the nearest branch. You'll see examples of curl, Node.js, and Python, real-world responses from our tests on November 16, 2026, as well as limits you need to know before installing them.

Quick summary: what do you need to know?

Maps Encoder has two GET endpoints: one for address to coordinates, one for coordinates to address. The following table summarizes the essence.

ItemsDetails
Address to coordinatesGET https://api.apipedia.id/v1/maps/geocode?q=...
Coordinates to the addressGET https://api.apipedia.id/v1/maps/reverse?lat=...&lon=...
Geocode parametersq: name of place or address, minimum 3 characters
Reverse parameterslat (-90 to 90) and lon (-180 to 180)
AuthenticationHeader Authorization: Bearer apk_xxx
Geocode resultsjumlah and array hasil contains lat, lon, display_name, type, address
Cache24 hours at gateway side; field cached marks the results from the cache
Data sourceOpenStreetMap Nominatim, data © OpenStreetMap contributors (ODbL)
Not yet availableDistance endpoints and polylines
TiersFree in the catalog, Maps Encoder version 1.1.4

What problems does the geocoding API solve?

The geocoding API bridges human-typed address text with machine-computable coordinate numbers. Without coordinates, your system cannot answer simple questions like "which branch is closest to this buyer?".

The three most common needs:

  • Nearest branch or warehouse. The buyer types in the address, the system selects the nearest service point.
  • Fill in the address of the device location. The application gets GPS coordinates, then reverse geocodes filling in the street name, city, and postal code in the form.
  • Point on the map. Customer or partner address lists are turned into pins for internal dashboards.

Four-step flowchart features nearest branch: buyer types in an address of at least 3 characters (example q=Alun-Alun Kota Malang), backend calls GET /v1/maps/geocode and receives a list of candidates containing lat, lon, and parsed addresses, the system selects one candidate by filtering address.state or asks the buyer to select, then calculates the distance to each branch with the haversine formula and sorts them; Kiduldalem example results 0.70 km. Note: the distance is calculated in your code because distance endpoints and polylines are not yet available, and haversine gives straight-line distances, not road distances.

What do you need to prepare before starting?

You only need one APIPedia API key. Register or log in at console.apipedia.id, open the API Token menu, then create a new key. The key starts with apk_ and is sent via header Authorization: Bearer apk_xxx.

Store the key in a server environment variable, for example APIPEDIA_KEY, and call the API from the backend, not from the browser. Also prepare a list of your branches along with their coordinates. The example in this article uses three fictitious branches.

Step 1: how to convert addresses to coordinates with curl?

Send the place name or address as parameters q to GET /v1/maps/geocode. Option --data-urlencode makes spaces and punctuation in addresses encoded correctly.

curl -s -G https://api.apipedia.id/v1/maps/geocode \
  -H "Authorization: Bearer apk_xxx" \
  --data-urlencode "q=Alun-Alun Kota Malang"

Real responses from our test, with the last three candidates shortened:

{
  "is_success": true,
  "message": "Geocoding results retrieved. Data © OpenStreetMap contributors (ODbL).",
  "data": {
    "q": "Alun-Alun Kota Malang",
    "jumlah": 5,
    "hasil": [
      {
        "lat": -7.9826131,
        "lon": 112.63082,
        "display_name": "Alun-Alun Merdeka, Kiduldalem, Kota Malang, Klojen, Jawa Timur, Indonesia",
        "type": "park",
        "address": {
          "road": null,
          "village": null,
          "suburb": "Kiduldalem",
          "city_district": null,
          "city": "Kota Malang",
          "county": null,
          "state": "Jawa Timur",
          "postcode": null,
          "country": "Indonesia"
        }
      },
      {
        "lat": -7.977166,
        "lon": 112.6340385,
        "display_name": "Alun-Alun Bundar Malang, RW. 08, KEL. KIDUL DALEM, KOTA MALANG, Kiduldalem, Klojen, Jawa Timur, Indonesia",
        "type": "park"
      }
    ],
    "cached": false
  }
}
FieldsMeaning
jumlahThe number of candidates found. In this test there are 5.
hasil[].lat, hasil[].lonCoordinates in decimal degrees, number type.
hasil[].display_nameComplete address on one line, suitable for displaying to users.
hasil[].typeThe type of object on the map, for example park, hotel, or mall.
hasil[].addressParsed addresses: road, village, suburb, city_district, city, county, state, postcode, country.
cachedtrue if the answer is retrieved from the gateway cache.

Two things are apparent from this response. First, one keyword can produce several candidates: besides the two squares, the test results also contain a hotel and a mall with similar names. Second, the unknown part address is worth null, including postcode in the first candidate.

Step 2: how to find the nearest branch in Node.js?

Take the coordinates of the buyer's address from the geocode, then calculate the distance to each branch with the haversine formula in your own code. Maps Encoder doesn't have a distance endpoint, so this calculation is done on the application side. The following example runs on Node.js 18 and above without any additional dependencies.

const BASE = "https://api.apipedia.id/v1";
const headers = { Authorization: `Bearer ${process.env.APIPEDIA_KEY}` }; // apk_xxx

// Daftar cabang fiktif. Simpan koordinat cabang Anda di database.
const CABANG = [
  { nama: "Cabang Sumbersari", lat: -7.9633709, lon: 112.6192541 },
  { nama: "Cabang Kiduldalem", lat: -7.977166, lon: 112.6340385 },
  { nama: "Cabang Surabaya", lat: -7.2573672, lon: 112.7520999 },
];

async function geocode(alamat) {
  const url = `${BASE}/maps/geocode?q=${encodeURIComponent(alamat)}`;
  const res = await fetch(url, { headers });
  const body = await res.json();
  if (!body.is_success) throw new Error(`HTTP ${res.status}: ${body.message}`);
  return body.data.hasil; // bisa kosong
}

// Jarak garis lurus (haversine), dalam kilometer.
function jarakKm(a, b) {
  const rad = (x) => (x * Math.PI) / 180;
  const dLat = rad(b.lat - a.lat);
  const dLon = rad(b.lon - a.lon);
  const h =
    Math.sin(dLat / 2) ** 2 +
    Math.cos(rad(a.lat)) * Math.cos(rad(b.lat)) * Math.sin(dLon / 2) ** 2;
  return 2 * 6371 * Math.asin(Math.sqrt(h));
}

export async function cabangTerdekat(alamat, provinsi) {
  const hasil = await geocode(alamat);
  const kandidat = provinsi
    ? hasil.filter((h) => h.address.state === provinsi)
    : hasil;
  if (kandidat.length === 0) return { ok: false, alasan: "Alamat tidak ditemukan." };

  const titik = kandidat[0];
  const urut = CABANG
    .map((c) => ({ ...c, km: Number(jarakKm(titik, c).toFixed(2)) }))
    .sort((x, y) => x.km - y.km);
  return { ok: true, alamat: titik.display_name, terdekat: urut[0], semua: urut };
}

console.log(await cabangTerdekat("Alun-Alun Kota Malang", "Jawa Timur"));

Given the coordinates from the response in Step 1, this function produces the following sequence:

BranchStraight line distance
Kiduldalem Branch0.70km
Sumbersari Branch2.49 km
Surabaya Branch81.74 km

Parameter provinsi is useful for filtering out candidates with the wrong area. Many place names in Indonesia are used in more than one city, so filtering through address.state reduces the number of wrong choices. If there is still more than one candidate, display display_name as options and let the buyer choose.

Step 3: how to convert coordinates to address?

Send lat and lon to GET /v1/maps/reverse, and the API returns the single closest address to that point. This pattern is used when the application already holds the coordinates from the device's GPS and wants to fill in the address form.

curl -s -G https://api.apipedia.id/v1/maps/reverse \
  -H "Authorization: Bearer apk_xxx" \
  -d lat=-7.2575 -d lon=112.7521

Real response from our test:

{
  "is_success": true,
  "message": "Address retrieved from coordinates. Data © OpenStreetMap contributors (ODbL).",
  "data": {
    "lat": -7.2573672,
    "lon": 112.7520999,
    "display_name": "Jalan Kanginan I, RW 01, Ketabang, Genteng, Surabaya, Jawa Timur, 60272, Indonesia",
    "type": "living_street",
    "address": {
      "road": "Jalan Kanginan I",
      "village": "Ketabang",
      "suburb": null,
      "city_district": null,
      "city": "Surabaya",
      "county": null,
      "state": "Jawa Timur",
      "postcode": "60272",
      "country": "Indonesia"
    },
    "cached": false
  }
}

Note that lat and lon in the response are slightly different from those sent. That's the coordinates of the nearest map object (here a road section), not the exact point you requested.

Comparison of two Maps Encoder endpoints with real test data. Geocode, GET /v1/maps/geocode: input q Alun-Alun Kota Malang produces 5 candidates, the first candidate is lat -7.9826131 and lon 112.63082, type park, address.state Jawa Timur, address.postcode is null because it is not always filled in. Reverse, GET /v1/maps/reverse: input lat -7.2575 and lon 112.7521 produces address.road Jalan Kanginan I, village Ketabang, city Surabaya, state Jawa Timur, postcode 60272. Note: 24 hour cache, there is a cached field, no route distance, no polylines, and the completeness of the OpenStreetMap data varies between regions.

Step 4: what is an example of reverse geocode in Python?

In Python, send lat and lon with requests, then map part address to your form fields. Since some fields can be null, prepare a backup for each column.

import os
from math import asin, cos, radians, sin, sqrt

import requests  # pip install requests

BASE = "https://api.apipedia.id/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['APIPEDIA_KEY']}"}  # apk_xxx


def alamat_dari_koordinat(lat, lon):
    res = requests.get(
        f"{BASE}/maps/reverse",
        headers=HEADERS,
        params={"lat": lat, "lon": lon},
        timeout=15,
    )
    body = res.json()
    if not body.get("is_success"):
        raise RuntimeError(f"HTTP {res.status_code}: {body.get('message')}")
    a = body["data"]["address"]
    return {
        "lengkap": body["data"]["display_name"],
        "jalan": a.get("road"),
        "kelurahan": a.get("village") or a.get("suburb"),
        "kota": a.get("city") or a.get("county"),
        "provinsi": a.get("state"),
        "kode_pos": a.get("postcode"),
    }


def jarak_km(lat1, lon1, lat2, lon2):
    d_lat, d_lon = radians(lat2 - lat1), radians(lon2 - lon1)
    h = sin(d_lat / 2) ** 2 + cos(radians(lat1)) * cos(radians(lat2)) * sin(d_lon / 2) ** 2
    return 2 * 6371 * asin(sqrt(h))


if __name__ == "__main__":
    print(alamat_dari_koordinat(-7.2575, 112.7521))
    print(round(jarak_km(-7.9826131, 112.63082, -7.977166, 112.6340385), 2), "km")  # 0.7 km

In the Surabaya response above, the subdistrict name is at village, while in the Malang response in Step 1 it is at suburb. That's the reason the code checks both.

What Maps Encoder limits do you need to know?

Maps Encoder only performs geocoding and reverse geocoding; it does not calculate mileage, routes, or polylines. According to the APIPedia catalog, distance and polyline endpoints are not yet implemented.

  • Haversine is not a distance on the road. The 0.70 km figure above is a straight line. The actual mileage is almost always longer, so don't use this figure for the rate per kilometer.
  • Data completeness follows OpenStreetMap. The city center is usually neatly mapped, while small alleys or new housing may not yet exist.
  • Postal codes are not always filled in. If postcode is null, complete via region and postal code API.
  • There is a speed limitation. The gateway limits requests to Nominatim policies, so the product is not designed for mass geocoding of thousands of addresses at once.
  • Must include attribution. When the results are displayed publicly, write "© OpenStreetMap contributors" according to the ODbL license.

What common mistakes should you avoid?

The most common error is calling the geocode every time the page is opened, even though the same address produces the same coordinates. Store lat and lon in the database when the address is first saved. Also check the following things.

  • Directly use hasil[0]. The first candidate is not necessarily the intended buyer. Filter by address.state or show options.
  • Does not handle empty results. Check jumlah or hasil length before reading the contents.
  • Does not encode addresses. Spaces, commas and periods must be encoded. Use encodeURIComponent or --data-urlencode.
  • Sending keywords too short. Parameter q is a minimum of 3 characters. Add the name of the city to make the results more precise.
  • Swap lat and lon. For Indonesia, lat ranges from -11 to 6 and lon 95 to 141.
  • Calling from a browser. Key apk_xxx will be read by anyone. Call from backend.
  • Call the haversine distance the distance traveled. Label "straight line distance" in the interface.

Status code that needs to be addressed

StatusMeaningAction
200Request successfulCheck jumlah, then read hasil
400Invalid parameter, for example q is less than 3 charactersRead message and correct input
401Token is missing, unknown, or expiredCheck header Authorization
429Request limit exceededWait, then repeat with a pause

A complete explanation of question 429 is in the rate limit and error 429 article.

Frequently asked questions

Is APIPedia's geocoding API free?

The Maps Encoder product is listed in the Free tier in the APIPedia catalog. Each call still counts towards your account's request quota.

Where does the map data come from?

From OpenStreetMap via Nominatim. All map data comes from OpenStreetMap contributors with an ODbL license, so attribution needs to be included when the results are displayed.

Can you calculate the distance or route between two points?

Not yet. Distance and polyline endpoints are not yet available in Maps Encoder. For straight line distance, use the haversine formula as in the example above.

Why does one address produce multiple candidates?

Because searches match names, and many places have similar names. In our test, "Malang City Square" produced 5 candidates, including two different squares.

Can geocode results be stored in a database?

Yes, and that's the recommended way to avoid calling the API repeatedly for the same address. The gateway itself stores cache for 24 hours.

Can AI assistants use this API?

Can. The APIPedia MCP server provides tools maps_geocode and maps_reverse that call the same endpoint. How to connect is in the guide for connecting APIPedia to Claude via MCP.

Next step: try it on the console

The nearest branch feature only requires one geocode request and one haversine function in the backend. Create a key at console.apipedia.id, run the curl example above with your own store address, then install function cabangTerdekat on the checkout page or location page.

To complete the flow, read the region and zip code API for the address dropdown and the postage check API for shipping cost estimates.

Topics:

About the author

Tim APIPedia — Tim Engineering APIPedia

Tim engineering di balik APIPedia yang membangun dan memelihara API data Indonesia - ongkir, OCR KTP, data wilayah, BMKG, hingga server MCP - dan menulis panduan integrasinya dari pengalaman langsung.