105 lines
1.8 KiB
Markdown
105 lines
1.8 KiB
Markdown
|
|
---
|
|
|
|
## ✅ Contoh dasar (JavaScript)
|
|
|
|
```js
|
|
async function getAlamat(lat, lng) {
|
|
const res = await fetch(
|
|
`https://nominatim.openstreetmap.org/reverse?lat=${lat}&lon=${lng}&format=json`
|
|
);
|
|
|
|
if (!res.ok) {
|
|
throw new Error(`HTTP error! status: ${res.status}`);
|
|
}
|
|
|
|
const data = await res.json();
|
|
return data.display_name;
|
|
}
|
|
|
|
// pakai
|
|
(async () => {
|
|
try {
|
|
const alamat = await getAlamat(-6.2, 106.816666);
|
|
console.log(alamat);
|
|
} catch (err) {
|
|
console.error(err);
|
|
}
|
|
})();
|
|
```
|
|
|
|
---
|
|
|
|
## ✅ Dengan **Google Maps API**
|
|
|
|
```js
|
|
async function getAlamatGoogle(lat, lng) {
|
|
const apiKey = "API_KEY_KAMU";
|
|
const url = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lng}&key=${apiKey}`;
|
|
|
|
const res = await fetch(url);
|
|
const data = await res.json();
|
|
|
|
if (data.status !== "OK") {
|
|
throw new Error(data.status);
|
|
}
|
|
|
|
return data.results[0].formatted_address;
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
## ✅ Ambil field detail (jalan, kota, dll)
|
|
|
|
```js
|
|
async function getAlamatDetail(lat, lng) {
|
|
const res = await fetch(
|
|
`https://nominatim.openstreetmap.org/reverse?lat=${lat}&lon=${lng}&format=json`
|
|
);
|
|
const data = await res.json();
|
|
|
|
const a = data.address;
|
|
return {
|
|
jalan: a.road,
|
|
kecamatan: a.suburb,
|
|
kota: a.city || a.town,
|
|
provinsi: a.state,
|
|
negara: a.country,
|
|
kodepos: a.postcode,
|
|
};
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
## ⚠️ Best practice (penting)
|
|
|
|
### 🔹 Tambahkan User-Agent (wajib untuk OSM)
|
|
|
|
```js
|
|
fetch(url, {
|
|
headers: {
|
|
"User-Agent": "MyApp/1.0 (email@example.com)"
|
|
}
|
|
});
|
|
```
|
|
|
|
### 🔹 Hindari spam request
|
|
|
|
* Cache hasil
|
|
* Delay antar request
|
|
|
|
---
|
|
|
|
## 🔥 Versi super ringkas
|
|
|
|
```js
|
|
const alamat = await (
|
|
await fetch(`https://nominatim.openstreetmap.org/reverse?lat=-6.2&lon=106.816666&format=json`)
|
|
).json();
|
|
|
|
console.log(alamat.display_name);
|
|
```
|
|
|