지도에 특정 위치를 표시해주는 기능이 필요한 경우,
주소를 위/경도로 변환해주는 기능이 필요하다.(Geocoding)
앱에서는 원하는 위치를 표시하기 위해 서버어게 전달할 정보중 쉽게 얻을 수 있는 것은 주소이다.
앱에서 서버로 주소를 보내면 주소를 받아 Geocoding API를 이용하여 위/경도 값으로 바꾸고 리턴해주면 앱에서는 위/경도 값만 지도에 표시해주면 된다.
- https://console.cloud.google.com/apis/dashboard 접속
- 상단에 [+ API 및 서비스 사용 설정] 클릭
- geocoding 검색
- Geocoding API 클릭 - 사용 클릭
- 계정 결제, 결제프로필 입력 후 [결제 제출 및 사용 설정] : 무료체험중에는 자동결제 진행이 안됨
- 아래 사진처럼 계정 선택 - [계정설정] 클릭
- Geocoding API키 를 받을 수 있음.
- ‘사용’ 클릭하면 해당 API 키를 가지고 아래에 있는 예제 소스코드를 참고하여 사용가능
- 사용을 안하면 [중지] 하기
프로젝트 스펙
id 'java'id 'war'
id 'org.springframework.boot' version '3.1.7'
id 'io.spring.dependency-management' version '1.1.4'
sourceCompatibility = '17'
gradle
** json관련 오류로 실행이 안될 때
// <https://mvnrepository.com/artifact/org.json/json>
implementation group: 'org.json', name: 'json', version: '20231013'
소스코드
package com.example.gpscoordinatesexample;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class GeoDataByAddress {
public static void main(String[] args) {
Map<String, String> geoDataByAddress = getGeoDataByAddress("서울특별시 송파구 송파대로 570");
System.out.println("geoDataByAddress = " + geoDataByAddress);
}
private static Map<String, String> getGeoDataByAddress(String completeAddress) {
try {
String API_KEY = "발급받은 API 키";
String surl = "https://maps.googleapis.com/maps/api/geocode/json?address=" + URLEncoder.encode(completeAddress, "UTF-8") + "&key=" + API_KEY;
URL url = new URL(surl);
InputStream is = url.openConnection().getInputStream();
BufferedReader streamReader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
System.out.println(">>>>>>>>>> >>>>>>>>>> InputStream Start <<<<<<<<<< <<<<<<<<<<");
while ((inputStr = streamReader.readLine()) != null) {
System.out.println(">>>>>>>>>> " + inputStr);
responseStrBuilder.append(inputStr);
}
System.out.println(">>>>>>>>>> >>>>>>>>>> InputStream End <<<<<<<<<< <<<<<<<<<<");
JSONObject jo = new JSONObject(responseStrBuilder.toString());
JSONArray results = jo.getJSONArray("results");
String region = null;
String province = null;
String zip = null;
Map<String, String> ret = new HashMap<String, String>();
if (results.length() > 0) {
JSONObject jsonObject;
jsonObject = results.getJSONObject(0);
Double lat = jsonObject.getJSONObject("geometry").getJSONObject("location").getDouble("lat");
Double lng = jsonObject.getJSONObject("geometry").getJSONObject("location").getDouble("lng");
ret.put("lat", lat.toString());
ret.put("lng", lng.toString());
System.out.println("LAT:\t\t" + lat);
System.out.println("LNG:\t\t" + lng);
JSONArray ja = jsonObject.getJSONArray("address_components");
for (int l = 0; l < ja.length(); l++) {
JSONObject curjo = ja.getJSONObject(l);
String type = curjo.getJSONArray("types").getString(0);
String short_name = curjo.getString("short_name");
if (type.equals("postal_code")) {
System.out.println("POSTAL_CODE: " + short_name);
ret.put("zip", short_name);
} else if (type.equals("administrative_area_level_3")) {
System.out.println("CITY: " + short_name);
ret.put("city", short_name);
} else if (type.equals("administrative_area_level_2")) {
System.out.println("PROVINCE: " + short_name);
ret.put("province", short_name);
} else if (type.equals("administrative_area_level_1")) {
System.out.println("REGION: " + short_name);
ret.put("region", short_name);
}
}
return ret;
}
} catch(Exception e){
e.printStackTrace();
}
return null;
}
}
결과
'공부내용 정리 > 프로그래밍' 카테고리의 다른 글
[SSL] Lets'Encrypt 로 인증서 발급받기 (0) | 2025.03.06 |
---|---|
[패스트캠퍼스강의] 게시판 서비스 프로젝트 #3 (0) | 2023.11.07 |
DBCP, DataBase Connection Pool 개념 정리 (1) | 2023.10.27 |
[패스트캠퍼스강의] 게시판 서비스 프로젝트 #2 (0) | 2023.10.25 |
[패스트캠퍼스강의] 게시판 서비스 프로젝트 #1 (0) | 2023.10.25 |