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);
    }

}

주소를 위, 경도로 바꾸기

@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());
    }

}

'항해99 > TIL' 카테고리의 다른 글

53일차 항해일지  (0) 2021.11.04
52일차 항해일지  (0) 2021.11.04
50일차 항해일지  (0) 2021.11.02
47일차 항해일지  (0) 2021.11.01
46일차 항해일지  (0) 2021.11.01