프로젝트/싹쓰리

[프로젝트] 스프링에서 구글 GeoCoding으로 주소로부터 위도 경도 얻기

라임온조 2023. 8. 24. 16:45

1. 왜 사용했나

프로젝트 기능 중에 사용자와 가게 사이의 거리를 구해야 했다. 그래서 거리 구하는 방법을 찾아보다 위도와 경도를 이용해서 두 위치 사이 거리를 구할 수 있음을 발견하여 적용해보고 싶었다. 

이를 위해서는 주어진 주소를 위도 경도로 변환해야 했다. 그래서 구글에서 제공하는 api를 사용해 특정 주소를 위도와 경도로 변환하고자 하였다.

 

2. Google Cloud Console 사전 설정

1) Google Cloud Console로 이동하여 프로젝트 생성

2) Geolocation API 를 찾아 사용버튼 클릭

3) 카드 등록

  • 90일 무료 사용 가능
  • 결제는 90일 이후 본인이 더 원할 경우에 진행됨. 자동 결제 아님

4) 제한 사항 설정(안 해도 괜찮음)

5) API 복사해 놓기

 

3. 스프링

1) application.properties

## geocoding
google.api.key=아까 복사해 놓은 api key

2) LocationService

public class LocationService {

    @Value("${google.api.key}")
    private String apiKey;

    public static final double EARTH_RADIUS = 6371.0088; // 지구 반지름 상수 선언

    // 주소 가지고 위도 경도 구하기
    public LatLng getLocation(String address) throws Exception{
        if(address.equals("")){
            return null;
        }
        GeoApiContext context = new GeoApiContext.Builder().apiKey(apiKey).build();
        GeocodingResult[] results = GeocodingApi.geocode(context, address).await();
        if(results.length != 0){
            LatLng location = results[0].geometry.location;
            return location;
        }
        return null;
    }
}

3) 사용

LatLng location = locationService.getLocation(address);
double latitude = location.lat;
double longitude = location.lng;