51일차 항해일지(gps to address, address to gps)
2021. 11. 4. 20:36ㆍ항해99/TIL
728x90
오늘 한 일
위,경도를 주소를 변환하기
@Slf4j
@Component
public class GpsToAddress {
String apiKey = "api_key";
public String getAddress(double latitude, double longitude) throws Exception {
String regionAddress = getRegionAddress(getJSONData(getApiAddress(latitude, longitude)));
return regionAddress;
}
private String getApiAddress(double latitude, double longitude) {
String apiURL = "https://maps.googleapis.com/maps/api/geocode/json?latlng="
+ latitude + "," + longitude + "&language=ko"+
"&key="+apiKey;
return apiURL;
}
private String getJSONData(String apiURL) throws Exception {
String jsonString = new String();
String buf;
URL url = new URL(apiURL);
URLConnection conn = url.openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(
conn.getInputStream(), "UTF-8"));
while ((buf = br.readLine()) != null) {
jsonString += buf;
}
return jsonString;
}
private String getRegionAddress(String jsonString) {
JSONObject jObj = (JSONObject) JSONValue.parse(jsonString);
JSONArray jArray = (JSONArray) jObj.get("results");
jObj = (JSONObject) jArray.get(0);
return (String) jObj.get("formatted_address");
}
public static void main(String[] args) throws Exception {
double latitude = 37.3645764; //위도
double longitude = 127.8340380; //경도
GpsToAddress gps = new GpsToAddress();
String address = gps.getAddress(latitude, longitude);
log.info("Address = {}", address);
}
}
- 참고자료 1 : https://developers.google.com/maps/documentation/geocoding/overview?hl=ko#ReverseGeocoding
- 참고자료 2 : https://choiyb2.tistory.com/77
- 위, 경도를 주소로 바꿔주는 api와 반대로 주소를 위, 경도를 바꾸어달라는 프론트 단의 요청으로 만들게 되었다.
- 위 2개의 참고자료를 통해서 간단히 코드를 구현하였다.
- 그래도 생각보다 google geographic의 apiKey를 얻는데 조금의 에로사항이 있엇지만 잘 구현할 수 있었다.
주소를 위, 경도로 바꾸기
@Component
@Slf4j
public class AddressToGps {
public GeographicDto getAddress(String address) throws Exception {
String addr = URLEncoder.encode(address,"utf-8");
String api = "https://naveropenapi.apigw.ntruss.com/map-geocode/v2/geocode?query="+addr;
StringBuffer sb = new StringBuffer();
try {
URL url = new URL(api);
HttpsURLConnection http = (HttpsURLConnection)url.openConnection();
http.setRequestProperty("Content-Type", "application/json");
http.setRequestProperty("X-NCP-APIGW-API-KEY-ID", "st5qvd1jn8");
http.setRequestProperty("X-NCP-APIGW-API-KEY", "vNwmtJeX7FNgxYnr3DhpoKjgrDptjd9gbpsyIAB5");
http.setRequestMethod("GET");
http.connect();
InputStreamReader in = new InputStreamReader(http.getInputStream(),"utf-8");
BufferedReader br = new BufferedReader(in);
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
JSONParser parser = new JSONParser();
JSONObject jsonObject;
JSONObject jsonObject2;
JSONArray jsonArray;
String x = "";
String y = "";
//트리형태로 온 JSON 파싱
jsonObject = (JSONObject)parser.parse(sb.toString());
jsonArray = (JSONArray)jsonObject.get("addresses");
for(int i=0;i<jsonArray.size();i++){
jsonObject2 = (JSONObject) jsonArray.get(i);
if(null != jsonObject2.get("x")){
x = (String) jsonObject2.get("x").toString();
}
if(null != jsonObject2.get("y")){
y = (String) jsonObject2.get("y").toString();
}
}
br.close();
in.close();
http.disconnect();
List<String> result = new ArrayList<>();
result.add(x);
result.add(y);
GeographicDto geographicDto = new GeographicDto(y, x);
return geographicDto;
} catch (IOException e) {
log.info("execption = {}",e);
}
return null;
}
public static void main(String[] args) throws Exception {
AddressToGps addressToGps = new AddressToGps();
GeographicDto address = addressToGps.getAddress("서울특별시 마포구");
log.info("위도 = {}, 경도 = {}", address.getLatitude(), address.getLongitude());
}
}
- 참고자료 1: https://navermaps.github.io/maps.js/docs/tutorial-Geocoder-Geocoding.html
address to gps
는 네이버를 이용하였다.- 항해99 1주차때 했었던 전기차 충전소 프로젝트에서 사용한 파이썬 코드를 재활용해서 자바 코드로 바꾼 후 쉽게 만들 수 있었다.