From 6202a0e814c51bb560b6a52d4c785f83c9d00166 Mon Sep 17 00:00:00 2001 From: androidlover5842 Date: Sat, 31 Jan 2026 11:12:51 +0530 Subject: [PATCH] Fallback geocode when postal code has zero results --- .../component/GoogleGeocodingClient.kt | 31 ++++++++++++++++--- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/src/main/kotlin/com/android/trisolarisserver/component/GoogleGeocodingClient.kt b/src/main/kotlin/com/android/trisolarisserver/component/GoogleGeocodingClient.kt index dd88945..eeefd7c 100644 --- a/src/main/kotlin/com/android/trisolarisserver/component/GoogleGeocodingClient.kt +++ b/src/main/kotlin/com/android/trisolarisserver/component/GoogleGeocodingClient.kt @@ -28,16 +28,39 @@ class GoogleGeocodingClient( .queryParam("region", "IN") .queryParam("key", apiKey) .toUriString() - val response = restTemplate.getForEntity(url, String::class.java) - val body = response.body ?: return GeocodeResult(null, null, "EMPTY_BODY") - val parsed = parseCityState(body) - GeocodeResult(parsed, body, "OK") + val primary = fetch(url) + if (primary.status == "OK") { + return primary + } + if (primary.status == "ZERO_RESULTS") { + val fallbackUrl = UriComponentsBuilder.fromUriString(baseUrl) + .queryParam("address", "$pinCode India") + .queryParam("region", "IN") + .queryParam("key", apiKey) + .toUriString() + val fallback = fetch(fallbackUrl) + if (fallback.resolvedCityState != null) return fallback + return primary + } + primary } catch (ex: Exception) { logger.warn("Geocoding failed: {}", ex.message) GeocodeResult(null, null, "ERROR") } } + private fun fetch(url: String): GeocodeResult { + val response = restTemplate.getForEntity(url, String::class.java) + val body = response.body ?: return GeocodeResult(null, null, "EMPTY_BODY") + val status = parseStatus(body) + val parsed = if (status == "OK") parseCityState(body) else null + return GeocodeResult(parsed, body, status ?: "UNKNOWN_STATUS") + } + + private fun parseStatus(body: String): String? { + return objectMapper.readTree(body).path("status").asText(null) + } + private fun parseCityState(body: String): String? { val root = objectMapper.readTree(body) val results = root.path("results")