Updated:

Google API 설정

 Google Cloud에서 새로운 프로젝트를 생성한다.

 다음으로 Geocoding API를 설정해준다.

 이제 다음 페이지에서 “사용자 인증 정보”를 선택해 새로운 API 키를 발급한다.

Spring

 먼저, application.property에 다음을 추가한다.

## geocoding
google.api.key=API키

 이후 다음과 같이 GeocodingService와 GeocodingServiceImpl을 추가해준다.

package com.Member.aiml_server_2024.navigation;

public interface GeocodingService {
    String getGeocode(double latitude, double longitude);

    String getAddressFromGeocode(double latitude, double longitude);
}
package com.Member.aiml_server_2024.navigation;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

@Service
public class GeocodingServiceImpl implements GeocodingService {

    private final String apiKey = "API키";
    private final RestTemplate restTemplate = new RestTemplate();

    @Override
    public String getGeocode(double latitude, double longitude) {
        String url = "https://maps.googleapis.com/maps/api/geocode/json";

        UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromHttpUrl(url)
                .queryParam("latlng", latitude + "," + longitude)
                .queryParam("key", apiKey);

        String response = restTemplate.getForObject(uriBuilder.toUriString(), String.class);

        return response;
    }

    @Override
    public String getAddressFromGeocode(double latitude, double longitude) {
        String response = getGeocode(latitude, longitude);

        ObjectMapper mapper = new ObjectMapper();
        try {
            JsonNode root = mapper.readTree(response);
            JsonNode results = root.path("results");
            if (results.isArray() && results.size() > 0) {
                JsonNode addressComponents = results.get(0).path("formatted_address");
                return addressComponents.asText();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println();
        return null;
    }
}

 이제 다음과 같은 테스트 코드를 실행한다.

package com.Member.aiml_server_2024.navigation;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import static org.junit.jupiter.api.Assertions.*;

@SpringBootTest
class GeocodingServiceImplTest {

    @Autowired
    private GeocodingServiceImpl geocodingService;

    @Test
    void 주소확인() {
        double lat = 37.54776;
        double log = 126.9230;

        String address = geocodingService.getAddressFromGeocode(lat, log);

        System.out.println(address);
    }

}

 위 코드를 실행하면 “Sangsu station, Seoul, South Korea”가 출력된다. 하자만 나는 한글 주소가 필요하므로 GeocodingServiceImpl의 getGeocode 메서드를 다음과 같이 수정한다.

public String getGeocode(double latitude, double longitude) {
    String url = "https://maps.googleapis.com/maps/api/geocode/json";

    UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromHttpUrl(url)
            .queryParam("latlng", latitude + "," + longitude)
            .queryParam("key", apiKey)
            .queryParam("language", "ko");

    String response = restTemplate.getForObject(uriBuilder.toUriString(), String.class);

    return response;
}

 이제 “대한민국 서울특별시 상수역”이 출력된다.

태그: ,

카테고리:

업데이트:

댓글남기기