본 예제는 1. Java Geocoding (위도 경도 추출) 예제에 이어서 진행을 한 예제 입니다.

 

 * 네이버 클라우드 플랫폼의 Geocoding, Static Map API를 사용
 * https://api.ncloud-docs.com/docs/ai-naver-mapsgeocoding-geocode
 * https://api.ncloud-docs.com/docs/ai-naver-mapsstaticmap-raster

 

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.*;
import java.net.*;
import java.util.Date;

public class Project01_E {
    // 추가된 함수
    public static void map_services(String point_x, String point_y, String address) {
        String URL_STATICMAP = "https://naveropenapi.apigw.ntruss.com/map-static/v2/raster?";
        try {
            String pos = URLEncoder.encode(point_x + " " + point_y, "UTF-8");
            String url = URL_STATICMAP;
            url += "center=" + point_x + "," + point_y;
            url += "&level=16&w=700&h=500";
            url += "&markers=type:t|size:mid|pos:" + pos + "|label:" + URLEncoder.encode(address, "UTF-8");

            URL u = new URL(url);
            HttpURLConnection con = (HttpURLConnection) u.openConnection();
            con.setRequestMethod("GET");
            con.setRequestProperty("X-NCP-APIGW-API-KEY-ID", "네이버 클라우드 플랫폼 Application Client ID");
            con.setRequestProperty("X-NCP-APIGW-API-KEY", "네이버 클라우드 플랫폼 Application Client Secret");

            int responseCode = con.getResponseCode();
            BufferedReader br;
            if(responseCode==200) { // 정상 호출
                InputStream is = con.getInputStream();
                int read = 0;
                byte[] bytes = new byte[1024];
                // 랜덤한 이름으로 파일 생성
                String tempname = Long.valueOf(new Date().getTime()).toString();
                File f = new File(tempname + ".jpg");
                f.createNewFile();
                OutputStream outputStream = new FileOutputStream(f);
                while ((read = is.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, read);
                }
                is.close();
            } else { // 에러 발생
                br = new BufferedReader(new InputStreamReader(con.getErrorStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();
                while ((inputLine = br.readLine()) != null) {
                    response.append(inputLine);
                }
                br.close();
                System.out.println(response.toString());
            }
        } catch (Exception e) {
            System.out.println(e);
        }

    }

    public static void main(String[] args) {
        String client_id = "네이버 클라우드 플랫폼 Application Client ID";
        String client_secret = "네이버 클라우드 플랫폼 Application Client Secret";

        BufferedReader io = new BufferedReader(new InputStreamReader(System.in));

        try {
            System.out.print("주소를 입력 하세요 : ");
            String address = io.readLine();
            String addr = URLEncoder.encode(address, "UTF-8");
            String reqUrl = "https://naveropenapi.apigw.ntruss.com/map-geocode/v2/geocode?query="+addr;

            URL url = new URL(reqUrl);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("GET");
            con.setRequestProperty("X-NCP-APIGW-API-KEY-ID", client_id);
            con.setRequestProperty("X-NCP-APIGW-API-KEY", client_secret);

            BufferedReader br;
            int responseCode = con.getResponseCode();

            if (responseCode == 200) {
                br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
            } else {
                br = new BufferedReader(new InputStreamReader(con.getErrorStream()));
            }

            String line;
            StringBuffer response = new StringBuffer();

            String x = ""; String y = ""; String z = ""; // 추가된 부분
            while ((line = br.readLine()) != null) {
                response.append(line);
            }
            br.close();

            JSONTokener tokener = new JSONTokener(response.toString());
            JSONObject object = new JSONObject(tokener);
            System.out.println(object.toString(2));

            JSONArray arr = object.getJSONArray("addresses");
            for(int i=0; i<arr.length(); i++) {
                JSONObject temp = (JSONObject) arr.get(i);
                System.out.println("address: " + temp.get("roadAddress"));
                System.out.println("jibunAddress: " + temp.get("jibunAddress"));
                System.out.println("경도 : " + temp.get("x"));
                System.out.println("위도 : " + temp.get("y"));

                // 추가된 부분
                x = (String) temp.get("x");
                y = (String) temp.get("y");
                z = (String) temp.get("roadAddress");
            }
            // 추가된 부분
            map_services(x,y,z);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

 

실행을 하면 주소를 입력하라는 메시지가 나온다.

 

주소 입력시 아래 그림과 같이 jpg 파일 하나가 생성이 된다.

 

생성된 jpg 파일을 열어보면 이렇게 지도 이미지가 생성된 것을 확인할 수 있다.

 

# 출처 : Inflearn - Java TPC 실전 프로젝트의 내용을 실습 하며 정리한 내용 입니다.

사용된 API : Naver Maps OpenAPI

네이버 클라우드 플랫폼의Geocoding API를 사용
https://api.ncloud-docs.com/docs/ai-naver-mapsgeocoding-geocode

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.*;

public class Project01_D {
    public static void main(String[] args) {
        // https://www.ncloud.com/ 로부터 가입후 얻어온 client_id, client_secret 값을 넣어준다.
        String client_id = "6yd5dlj11z";
        String client_secret = "7YyQB64C4CWyCuUR44plpdqZcECSqCT6pVGqoeBl";

        // System.in 을 이용해서 키보드로부터 값을 byte stream으로 입력 받는다
        // 주소는 문자이기 떄문에 InputStreamReader 클래스로 연결해서 받는다.
        // 문자 스트림을 한줄 단위로 읽어 들이기 위해 BufferedReader 로 연결 해준다.
        BufferedReader io = new BufferedReader(new InputStreamReader(System.in));

        try {
            System.out.print("주소를 입력 하세요 : ");
            String address = io.readLine(); // 한 라인을 읽어 들인다.
            String addr = URLEncoder.encode(address, "UTF-8"); // 입력한 주소의 공백 등을 문자로 처리 하기 위해 인코딩 해준다.(공백=>%20으로 변경)
            String reqUrl = "https://naveropenapi.apigw.ntruss.com/map-geocode/v2/geocode?query="+addr;

            URL url = new URL(reqUrl); // 입력 받은 url이 정상적인지 확인하기 위하여 URL객체로 생성.
            HttpURLConnection con = (HttpURLConnection) url.openConnection(); // URL객체에 openConnection을 사용하여 연결 시도
            // 요청 헤더의 메서드와 필수 값인 X-NCP-APIGW-API-KEY-ID, X-NCP-APIGW-API-KEY 값을 싣어 전송해준다.
            con.setRequestMethod("GET");
            con.setRequestProperty("X-NCP-APIGW-API-KEY-ID", client_id);
            con.setRequestProperty("X-NCP-APIGW-API-KEY", client_secret);

            BufferedReader br;
            int responseCode = con.getResponseCode(); // 정상적으로 연결이 되었을 경우 200 값이 넘어 온다.

            // getInputStream() 을 통해 값을 읽어 오는데 이것은 byte 스트림 이다.
            // 문자 단위로 바꾸기 위해 InputStreamReader를 사용.
            // 라인 단위로 읽어 들이기 위해 다시한번 BufferedReader를 사용.
            if (responseCode == 200) {
                br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); // 성공시
            } else {
                br = new BufferedReader(new InputStreamReader(con.getErrorStream())); // 에러시 getErrorStream을 사용
            }

            String line;
            StringBuffer response = new StringBuffer();
            while ((line = br.readLine()) != null) { // 가져온 주소 데이터의 readLine()를 이용해 한줄을 읽어서 line 스트링 변수에 담는다.
                response.append(line); // 스프링버퍼 변수에 읽어 들인 값을 담아주면 response 값에 모든 값이 문자열로 담긴다.
            }
            br.close();

            // response 안에 있는 JSON을 String Tokenizer를 이용해서 JSON 객체로 바꾸는 작업.
            JSONTokener tokener = new JSONTokener(response.toString()); // JSON 객체로 문자열을 메모리에 올린다.
            JSONObject object = new JSONObject(tokener); // JSON Object로 만들어준다.
            System.out.println(object.toString(2));

            JSONArray arr = object.getJSONArray("addresses"); // 객체안에 있는 Address의 값들을 배열로 읽어 들인다.
            // 주소 정보는 거의 1개가 오기 때문에 굳이 반복문을 쓸 필요는 없음.
            for(int i=0; i<arr.length(); i++) {
                JSONObject temp = (JSONObject) arr.get(i);
                System.out.println("address: " + temp.get("roadAddress"));
                System.out.println("jibunAddress: " + temp.get("jibunAddress"));
                System.out.println("경도 : " + temp.get("x"));
                System.out.println("위도 : " + temp.get("y"));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

 

# 출처 : Inflearn - Java TPC 실전 프로젝트의 내용을 실습 하며 정리한 내용 입니다.

+ Recent posts