84 lines
3.2 KiB
Java
84 lines
3.2 KiB
Java
package SuMoC.backend.geocoding;
|
|
|
|
import org.slf4j.Logger;
|
|
import org.slf4j.LoggerFactory;
|
|
import org.springframework.web.reactive.function.client.WebClient;
|
|
import reactor.core.publisher.Mono;
|
|
|
|
import java.util.HashMap;
|
|
import java.util.Map;
|
|
|
|
public class CartaLocationClient implements GeocodingClient {
|
|
|
|
private static final Logger logger = LoggerFactory.getLogger(CartaLocationClient.class);
|
|
|
|
private final WebClient cartaLocationClient;
|
|
|
|
public CartaLocationClient(WebClient cartaLocationClient) {
|
|
this.cartaLocationClient = cartaLocationClient;
|
|
}
|
|
|
|
@Override
|
|
public Mono<GeocodingResponse> reverse(double lat, double lon) {
|
|
String query = lat + "," + lon;
|
|
logger.debug("Calling Carta location API with query: {}, type: BUILDING, limit: 3", query);
|
|
|
|
return cartaLocationClient.get()
|
|
.uri(uriBuilder -> {
|
|
var uri = uriBuilder.path("/location/search")
|
|
.queryParam("q", query)
|
|
.queryParam("type", "BUILDING")
|
|
.queryParam("limit", 3)
|
|
.build();
|
|
logger.debug("Full Carta location API URL: {}", uri);
|
|
return uri;
|
|
})
|
|
.retrieve()
|
|
.bodyToMono(CartaLocationResponse[].class)
|
|
.doOnNext(responses -> logger.debug("Received {} results from Carta location API",
|
|
responses != null ? responses.length : 0))
|
|
.map(responses -> {
|
|
if (responses == null || responses.length == 0) {
|
|
logger.error("Carta location API returned empty response for coordinates: lat={}, lon={}", lat, lon);
|
|
return new GeocodingResponse(null);
|
|
}
|
|
logger.debug("Using first result: {}", responses[0]);
|
|
return mapToGeocodingResponse(responses[0]);
|
|
})
|
|
.onErrorResume(error -> {
|
|
logger.error("Error calling Carta location API for coordinates: lat={}, lon={}", lat, lon, error);
|
|
return Mono.just(new GeocodingResponse(null));
|
|
});
|
|
}
|
|
|
|
private GeocodingResponse mapToGeocodingResponse(CartaLocationResponse response) {
|
|
Map<String, String> addressMap = new HashMap<>();
|
|
|
|
// Map Carta fields to Nominatim-style address format
|
|
if (response.building() != null) {
|
|
addressMap.put("house_number", response.building());
|
|
}
|
|
if (response.street() != null) {
|
|
addressMap.put("road", response.street());
|
|
}
|
|
if (response.suburb() != null) {
|
|
addressMap.put("suburb", response.suburb());
|
|
}
|
|
if (response.city() != null) {
|
|
addressMap.put("city", response.city());
|
|
}
|
|
if (response.state() != null) {
|
|
addressMap.put("state", response.state());
|
|
}
|
|
if (response.postcode() != null) {
|
|
addressMap.put("postcode", response.postcode());
|
|
}
|
|
if (response.country() != null) {
|
|
addressMap.put("country", response.country());
|
|
}
|
|
|
|
return new GeocodingResponse(addressMap);
|
|
}
|
|
}
|
|
|