프로젝트를 하던 중 zipCode 우편번호를 받으면 위도, 경도를 반환해주는 api를 짜고 싶어서 Google의 Geocoding API로 해봤다. 구글링을 해도 최신 글이 없어서 삽질하다가 성공해서 이렇게 정리하는 중이다!!
https://console.cloud.google.com/
Google 클라우드 플랫폼
로그인 Google 클라우드 플랫폼으로 이동
accounts.google.com
1. 이 링크에 들어가서 api를 생성한다.
이때 주의할 점은 구글 계정에 카드가 연결되어있어야한다. 그리고 활성화까지 해줘야 함!!
90일간은 무료로 사용할 수 있다고 한다.
2. 발급 받은 api key를 application.yml에 추가한다.
google:
maps:
api:
key: 발급 받은 key 값
3. build.gradle에 dependency를 추가한다.
implementation group: 'com.google.maps', name: 'google-maps-services', version: '2.2.0'
버전은 최신 버전으로 해야하는데
https://mvnrepository.com/artifact/com.google.maps/google-maps-services
여기에서 확인하면 된다. 지금 시점은 2.2.0이 최신 버전이라서 구버전으로 했을 때 작동이 안됐다.
나는 pathVariable로 zipCode를 보냈을 때, 위도와 경도를 반환하도록 했다.
4. GeoCodingService.java 코드
import com.example.umc_insider.dto.response.GetLatLngRes;
import com.google.maps.GeoApiContext;
import com.google.maps.GeocodingApi;
import com.google.maps.model.GeocodingResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class GeoCodingService {
private String googleMapsApiKey;
@Value("${google.maps.api.key}")
public void setGoogleMapsApiKey(String googleMapsApiKey) {
this.googleMapsApiKey = googleMapsApiKey;
}
public GetLatLngRes getLatLngByAddress(String address) {
try {
String a = "대한민국 " + address;
GeoApiContext context = new GeoApiContext.Builder()
.apiKey(googleMapsApiKey)
.build();
GeocodingResult[] results = GeocodingApi.geocode(context, a)
.region("kr")
.await();
if (results.length > 0) {
GeocodingResult result = results[0];
double latitude = result.geometry.location.lat;
double longitude = result.geometry.location.lng;
return new GetLatLngRes(latitude, longitude);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
GetLatLngRes.java 코드(어떻게 반환할지 알려주는 response 코드이다)
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class GetLatLngRes {
private double latitude;
private double longitude;
public GetLatLngRes(double latitude, double longitude) {
this.latitude = latitude;
this.longitude = longitude;
}
// getter 및 setter 메소드
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
}
Cotroller.java 코드
@GetMapping("/address/{zipCode}")
public GetLatLngRes getLatLng(@PathVariable String zipCode){
GetLatLngRes getLatLngRes = geoCodingService.getLatLngByAddress(zipCode);
return getLatLngRes;
}
5. postman으로 테스트
'Server > Spring Boot' 카테고리의 다른 글
데이터베이스 조작이 편해지는 ORM (0) | 2023.11.07 |
---|---|
스프링 부트3 테스트 (1) | 2023.10.31 |
스프링 부트3 구조 이해하기 (0) | 2023.10.25 |
스프링, 스프링부트 차이 & 스프링 개념 & 코드 분석 (1) | 2023.10.04 |
[Trouble Shooting] 스프링 부트 DB 없이 실행시키기 (0) | 2023.10.03 |