fixed GeocodingService add alter city
This commit is contained in:
119
src/main/java/com/krylov/refound/service/GeocodingService.java
Normal file
119
src/main/java/com/krylov/refound/service/GeocodingService.java
Normal file
@@ -0,0 +1,119 @@
|
||||
package com.krylov.refound.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.krylov.refound.dto.AddressInfo;
|
||||
import com.krylov.refound.enums.ErrorCode;
|
||||
import com.krylov.refound.exception.ApiException;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.URLEncoder;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class GeocodingService {
|
||||
|
||||
private final ObjectMapper mapper;
|
||||
|
||||
// Поля address-объекта Nominatim, которые в сумме считаем "городом" (в порядке приоритета)
|
||||
private static final List<String> CITY_FIELDS = List.of("city", "town", "village", "municipality");
|
||||
|
||||
// HttpClient потокобезопасен и предназначен для переиспользования — не создаём его на каждый запрос
|
||||
private final HttpClient httpClient = HttpClient.newBuilder()
|
||||
.connectTimeout(Duration.ofSeconds(5))
|
||||
.build();
|
||||
|
||||
/**
|
||||
* Определяет город и остальную часть адреса по координатам через Nominatim reverse geocoding.
|
||||
*/
|
||||
public AddressInfo getAddress(String lat, String lon) {
|
||||
String url = "https://nominatim.openstreetmap.org/reverse"
|
||||
+ "?lat=" + encode(lat)
|
||||
+ "&lon=" + encode(lon)
|
||||
+ "&format=jsonv2"
|
||||
+ "&addressdetails=1";
|
||||
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(URI.create(url))
|
||||
.timeout(Duration.ofSeconds(5))
|
||||
.header("User-Agent", "MyApp/1.0")
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
JsonNode root;
|
||||
try {
|
||||
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
if (response.statusCode() != 200) {
|
||||
log.warn("Nominatim вернул статус {} для lat={}, lon={}", response.statusCode(), lat, lon);
|
||||
throw new ApiException(ErrorCode.INTERNAL_ERROR, "Сервис геокодирования недоступен.", HttpStatus.SERVICE_UNAVAILABLE);
|
||||
}
|
||||
root = mapper.readTree(response.body());
|
||||
} catch (IOException e) {
|
||||
log.error("Ошибка при обращении к Nominatim: {}", e.getMessage(), e);
|
||||
throw new ApiException(ErrorCode.INTERNAL_ERROR, "Сервис геокодирования недоступен.", HttpStatus.SERVICE_UNAVAILABLE);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new ApiException(ErrorCode.INTERNAL_ERROR, "Запрос к сервису геокодирования прерван.", HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
|
||||
return toAddressInfo(root);
|
||||
}
|
||||
|
||||
private AddressInfo toAddressInfo(JsonNode root) {
|
||||
JsonNode address = root.path("address");
|
||||
String displayName = root.path("display_name").asText("");
|
||||
|
||||
String city = CITY_FIELDS.stream()
|
||||
.map(field -> address.path(field).asText(null))
|
||||
.filter(value -> value != null && !value.isBlank())
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
|
||||
String district = buildDistrict(displayName, city);
|
||||
|
||||
return new AddressInfo(city, district);
|
||||
}
|
||||
|
||||
/**
|
||||
* display_name — это склеенные через запятую компоненты адреса от самого точного к самому общему.
|
||||
* Убираем из этого списка компонент, совпавший с городом, и склеиваем остальное обратно.
|
||||
*/
|
||||
private String buildDistrict(String displayName, String city) {
|
||||
if (displayName.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String[] parts = displayName.split(",");
|
||||
StringBuilder result = new StringBuilder();
|
||||
boolean cityRemoved = false;
|
||||
|
||||
for (String part : parts) {
|
||||
String trimmed = part.trim();
|
||||
if (!cityRemoved && trimmed.equalsIgnoreCase(city)) {
|
||||
cityRemoved = true;
|
||||
continue;
|
||||
}
|
||||
if (!result.isEmpty()) {
|
||||
result.append(", ");
|
||||
}
|
||||
result.append(trimmed);
|
||||
}
|
||||
|
||||
return result.isEmpty() ? null : result.toString();
|
||||
}
|
||||
|
||||
private String encode(String value) {
|
||||
return URLEncoder.encode(value, StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user