본 예제는 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 실전 프로젝트의 내용을 실습 하며 정리한 내용 입니다.

+ Recent posts