반응형

네이버 클라우드 플랫폼의 리버스 지오코딩을 사용해 보자.

 

2022.02.05 - [Android] - Naver Geocoding For Android 안드로이드 네이버 지오코딩

위 링크를 참고해 인터넷 권한과 network_security_config 옵션을 설정한다.

 

리니어 레이아웃에 텍스트뷰와 버튼을 적당히 배치한다.

 

JSON 타입의 주소 정보를 처리하기 위해 관련 클래스를 작성한다.

주소 정보 관련 클래스는 아래 파일을 사용하자.

myapplication.zip
0.00MB

 

JSON 데이터를 처리하기 위해 gson을 추가한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package com.example.myapplication;
 
import androidx.appcompat.app.AppCompatActivity;
 
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
 
import com.google.gson.Gson;
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
 
public class MainActivity extends AppCompatActivity {
 
    TextView textView;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        textView = findViewById(R.id.textView);
 
        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        requestGeocode();
                    }
                }).start();
            }
        });
    }
 
    public void requestGeocode() {
        try {
            BufferedReader bufferedReader;
            StringBuilder stringBuilder = new StringBuilder();
            String coord = "127.1234308,37.3850143";
            String query = "https://naveropenapi.apigw.ntruss.com/map-reversegeocode/v2/gc?request=coordsToaddr&coords="
                    + coord + "&sourcecrs=epsg:4326&output=json&orders=roadaddr&output=xml";
            URL url = new URL(query);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            if (conn != null) {
                conn.setConnectTimeout(5000);
                conn.setReadTimeout(5000);
                conn.setRequestMethod("GET");
                conn.setRequestProperty("X-NCP-APIGW-API-KEY-ID""Client ID");
                conn.setRequestProperty("X-NCP-APIGW-API-KEY""Client Secret");
                conn.setDoInput(true);
 
                int responseCode = conn.getResponseCode();
 
                if (responseCode == 200) {
                    bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                } else {
                    bufferedReader = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
                }
 
                String line = null;
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuilder.append(line + "\n");
                }
                //textView.setText(stringBuilder);
 
                Gson gson = new Gson();
                Address address = gson.fromJson(String.valueOf(stringBuilder), Address.class);
 
                String finalAddress = null;
                finalAddress = address.results[0].region.area1.name;
                finalAddress += address.results[0].region.area2.name;
                finalAddress += address.results[0].region.area3.name;
                finalAddress += address.results[0].region.area4.name;
                finalAddress += address.results[0].land.addition0.value;
 
                textView.setText(finalAddress);
 
                bufferedReader.close();
                conn.disconnect();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 

 

소스를 입력하고 빌드한다. 주소로 변환할 GPS 좌표는 (127.1234308, 37.3850143) 이다.

 

 

앱을 실행하고 버튼을 터치하면 GPS 좌표가 주소로 변환되어 표시된다.

아래와 같은 양식의 curl 명령으로도 같은 JSON 데이터를 얻을 수 있다.

curl "https://naveropenapi.apigw.ntruss.com/map-reversegeocode/v2/gc?request=coordsToaddr&coords=127.1234308,37.3850143&sourcecrs=epsg:4326&output=json&orders=roadaddr&output=xml" -H "X-NCP-APIGW-API-KEY-ID: Client ID" -H "X-NCP-APIGW-API-KEY: Client Secret" -v

-v, --verbose
Makes curl verbose during the operation. Useful for debugging and seeing what's going on "under the hood". A line starting with '>' means "header data" sent by curl, '<' means "header data" received by curl that is hidden in normal cases, and a line starting with '*' means additional info provided by curl.

If you only want HTTP headers in the output, --include might be the option you are looking for.
If you think this option still does not give you enough details, consider using --trace or --trace-ascii instead.
This option is global and does not need to be specified for each use of -:, --next.
Use --silent to make curl really quiet.
Example:
 curl --verbose https://example.com

 

반응형
Posted by J-sean
:
반응형

네이버 클라우드 플랫폼의 지오코딩을 사용해 보자.

 

xml 리소스 폴더를 만들고 network_security_config.xml 파일을 생성한다.

 

AndroidManifest.xml에 인터넷 권한과 networkSecurityConfig 옵션을 추가한다.

 

리니어 레이아웃에 텍스트뷰와 버튼을 적당히 배치한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package com.example.myapplication;
 
import androidx.appcompat.app.AppCompatActivity;
 
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
 
public class MainActivity extends AppCompatActivity {
 
    TextView textView;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        textView = findViewById(R.id.textView);
 
        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        requestGeocode();
                    }
                }).start();
            }
        });
    }
 
    public void requestGeocode() {
        try {
            BufferedReader bufferedReader;
            StringBuilder stringBuilder = new StringBuilder();
            String addr = "분당구 성남대로 601";
            String query = "https://naveropenapi.apigw.ntruss.com/map-geocode/v2/geocode?query=" + URLEncoder.encode(addr, "UTF-8");
            URL url = new URL(query);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            if (conn != null) {
                conn.setConnectTimeout(5000);
                conn.setReadTimeout(5000);
                conn.setRequestMethod("GET");
                conn.setRequestProperty("X-NCP-APIGW-API-KEY-ID""Client ID");
                conn.setRequestProperty("X-NCP-APIGW-API-KEY""Client Secret");
                conn.setDoInput(true);
 
                int responseCode = conn.getResponseCode();
 
                if (responseCode == 200) {
                    bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                } else {
                    bufferedReader = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
                }
 
                String line = null;
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuilder.append(line + "\n");
                }
                //textView.setText(stringBuilder);
 
                int indexFirst;
                int indexLast;
 
                indexFirst = stringBuilder.indexOf("\"x\":\"");
                indexLast = stringBuilder.indexOf("\",\"y\":");
                String x = stringBuilder.substring(indexFirst + 5, indexLast);
 
                indexFirst = stringBuilder.indexOf("\"y\":\"");
                indexLast = stringBuilder.indexOf("\",\"distance\":");
                String y = stringBuilder.substring(indexFirst + 5, indexLast);
 
                textView.setText("X: " + x + ", " + "Y: " + y);
 
                bufferedReader.close();
                conn.disconnect();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 

 

MainActivity.java에 위 소스를 입력하고 빌드한다. '분당구 성남대로 601'의 주소 정보를 여러가지 데이터가 포함된 JSON 포맷으로 가져와 간단한 문자열 조작으로 GPS 좌표만 추출한다.

 

 

앱을 실행시키고 버튼을 터치하면 '분당구 성남대로 601'의 GPS 좌표가 표시된다.

 

구글 맵에서 GPS 좌표를 확인해 보자. 서현역이다.

 

아래와 같은 양식의 curl 명령으로도 동일한 JSON 데이터를 얻을 수 있다.

curl -G "https://naveropenapi.apigw.ntruss.com/map-geocode/v2/geocode?query=%EB%B6%84%EB%8B%B9%EA%B5%AC%20%EC%84%B1%EB%82%A8%EB%8C%80%EB%A1%9C%20601" -H "X-NCP-APIGW-API-KEY-ID: Client ID" -H "X-NCP-APIGW-API-KEY: Client Secret"

※ query에는 주소를 url encoding한 값을 대입한다.

분당구 성남대로 601 = %EB%B6%84%EB%8B%B9%EA%B5%AC%20%EC%84%B1%EB%82%A8%EB%8C%80%EB%A1%9C%20601

 

아래와 같은 양식으로 웹브라우저 주소창에 입력해도 동일한 JSON 데이터를 얻을 수 있다.

https://naveropenapi.apigw.ntruss.com/map-geocode/v2/geocode?query=분당구 성남대로 601&X-NCP-APIGW-API-KEY-ID=[Client ID]&X-NCP-APIGW-API-KEY=[Client Secret]

 

 

반응형
Posted by J-sean
:
반응형

Geocoder를 사용하면 주소로 위경도를, 위경도로 주소를 확인 할 수 있다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
public class MainActivity extends AppCompatActivity {
 
    Geocoder geocoder;
 
    EditText editText;
    Button button;
    TextView textView;
 
    EditText editText2;
    EditText editText3;
    Button button2;
    TextView textView2;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        geocoder = new Geocoder(this);
 
        editText = findViewById(R.id.editText);
        textView = findViewById(R.id.textView);
        button = findViewById(R.id.button);
 
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<Address> addressList;
                String search = editText.getText().toString();
 
                try {
                    addressList = geocoder.getFromLocationName(search, 10);
                    String[] split = addressList.get(0).toString().split(",");
                    String address = split[0].substring(split[0].indexOf("\""+ 1split[0].length() - 2);
                    String latitude = split[10].substring(split[10].indexOf("="+ 1);  // 위도(수평선)
                    String longitude = split[12].substring(split[12].indexOf("="+ 1); // 경도(수직선)
 
                    String data = "Address: " + address + "\n" + "Latitude: " + latitude + "\n" + "Longitude: " + longitude;
                    textView.setText(data);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
 
        editText2 = findViewById(R.id.editText2);
        editText3 = findViewById(R.id.editText3);
        textView2 = findViewById(R.id.textView2);
        button2 = findViewById(R.id.button2);
 
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<Address> addressList;
                double latitude = Double.parseDouble(editText2.getText().toString());
                double longitude = Double.parseDouble(editText3.getText().toString());
 
                try {
                    addressList = geocoder.getFromLocation(latitude, longitude, 10);
                    textView2.setText("Address: " + addressList.get(0).getAddressLine(0));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}




실행 화면


간단한 주소를 입력하고 SEARCH GEOGRAPHIC COORDINATE 버튼을 클릭 하면 정확한 주소와 위경도가 표시 된다.


위경도를 입력하고 SEARCH ADDRESS 버튼을 클릭 하면 주소가 표시된다.


주소로 서현역을 검색 하거나 서현역 위경도로 검색하면 addressList[0]에 입력되는 내용은 아래와 같다. (똑같은 양식으로 입력 된다)


Address[addressLines=[0:"대한민국 경기도 성남시 분당구 서현동 성남대로 지하 601 서현"],feature=서현,admin=경기도,sub-admin=null,locality=성남시,thoroughfare=null,postalCode=463-050,countryCode=KR,countryName=대한민국,hasLatitude=true,latitude=37.384938999999996,hasLongitude=true,longitude=127.12326300000001,phone=null,url=null,extras=null]


반응형
Posted by J-sean
: