Fallback geocode when postal code has zero results
All checks were successful
build-and-deploy / build-deploy (push) Successful in 32s
All checks were successful
build-and-deploy / build-deploy (push) Successful in 32s
This commit is contained in:
@@ -28,16 +28,39 @@ class GoogleGeocodingClient(
|
|||||||
.queryParam("region", "IN")
|
.queryParam("region", "IN")
|
||||||
.queryParam("key", apiKey)
|
.queryParam("key", apiKey)
|
||||||
.toUriString()
|
.toUriString()
|
||||||
val response = restTemplate.getForEntity(url, String::class.java)
|
val primary = fetch(url)
|
||||||
val body = response.body ?: return GeocodeResult(null, null, "EMPTY_BODY")
|
if (primary.status == "OK") {
|
||||||
val parsed = parseCityState(body)
|
return primary
|
||||||
GeocodeResult(parsed, body, "OK")
|
}
|
||||||
|
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) {
|
} catch (ex: Exception) {
|
||||||
logger.warn("Geocoding failed: {}", ex.message)
|
logger.warn("Geocoding failed: {}", ex.message)
|
||||||
GeocodeResult(null, null, "ERROR")
|
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? {
|
private fun parseCityState(body: String): String? {
|
||||||
val root = objectMapper.readTree(body)
|
val root = objectMapper.readTree(body)
|
||||||
val results = root.path("results")
|
val results = root.path("results")
|
||||||
|
|||||||
Reference in New Issue
Block a user