72 lines
1.8 KiB
PHP
72 lines
1.8 KiB
PHP
<?php
|
|
// api/geocode.php
|
|
// Reverse Geocoding via Nominatim (OpenStreetMap)
|
|
|
|
header('Content-Type: application/json; charset=utf-8');
|
|
header('Access-Control-Allow-Origin: *');
|
|
|
|
$lat = $_GET['lat'] ?? null;
|
|
$lng = $_GET['lng'] ?? null;
|
|
|
|
if (!$lat || !$lng) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'error' => 'lat dan lng diperlukan']);
|
|
exit;
|
|
}
|
|
|
|
$lat = (float)$lat;
|
|
$lng = (float)$lng;
|
|
|
|
$url = "https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat={$lat}&lon={$lng}&zoom=18&addressdetails=1";
|
|
|
|
$context = stream_context_create([
|
|
'http' => [
|
|
'method' => 'GET',
|
|
'header' => "User-Agent: SIG-Kemiskinan/1.0 (sig@example.com)\r\n",
|
|
'timeout' => 8,
|
|
]
|
|
]);
|
|
|
|
$response = @file_get_contents($url, false, $context);
|
|
|
|
if ($response === false) {
|
|
// Fallback: koordinat saja
|
|
echo json_encode([
|
|
'success' => true,
|
|
'alamat' => "Koordinat: {$lat}, {$lng}",
|
|
'detail' => null
|
|
]);
|
|
exit;
|
|
}
|
|
|
|
$data = json_decode($response, true);
|
|
|
|
if (!$data || isset($data['error'])) {
|
|
echo json_encode([
|
|
'success' => true,
|
|
'alamat' => "Koordinat: {$lat}, {$lng}",
|
|
'detail' => null
|
|
]);
|
|
exit;
|
|
}
|
|
|
|
// Susun alamat yang rapi
|
|
$addr = $data['address'] ?? [];
|
|
$parts = array_filter([
|
|
$addr['road'] ?? $addr['pedestrian'] ?? $addr['path'] ?? null,
|
|
$addr['house_number'] ?? null,
|
|
$addr['neighbourhood'] ?? $addr['suburb'] ?? null,
|
|
$addr['city'] ?? $addr['town'] ?? $addr['village'] ?? $addr['county'] ?? null,
|
|
]);
|
|
|
|
$alamat = !empty($parts)
|
|
? implode(', ', $parts)
|
|
: ($data['display_name'] ?? "Koordinat: {$lat}, {$lng}");
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'alamat' => $alamat,
|
|
'display_name' => $data['display_name'] ?? '',
|
|
'detail' => $addr
|
|
]);
|