티스토리 뷰

Google Developers


초기 설정

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
public class cGPlacesAPI
{
    Context                 mContext;
    StringBuilder           mResponseBuilder = new StringBuilder();
 
    LinkedList<cList>       mList = new LinkedList<>();
 
    cGPlacesAPI(Context _con, double _lat, double _lon, double _radius, String _type)
    {
        mContext            = _con;
        try
        {
            String          uStr = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=" + _lat + "," + _lon + "&radius=" + _radius + "&types=" + _type + "&key=key";
            URL             url = new URL(uStr);
            BufferedReader  in = new BufferedReader(new InputStreamReader(url.openStream()));
            String          inputLine;
 
            while ((inputLine = in.readLine()) != null)
            {
                mResponseBuilder.append(inputLine);
            }
            in.close();
        }
        catch (MalformedURLException me)
        {
            me.printStackTrace();
        }
        catch (UnsupportedEncodingException ue)
        {
            ue.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}
 
cs
  • GET 형식으로 매개변수를 입력하여 지도 검색 요청.

    • 다음 예는 영국 런던 인근의 박물관 목록을 반환합니다.

https://maps.googleapis.com/maps/api/place/radarsearch/json?location=51.503186,-0.126446&radius=5000&types=museum&key=AddYourOwnKeyHere


검색 결과 파싱

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
 
    public void parsing()    {
        try
        {
            JSONArray       jArr;
            JSONObject      jObj;
 
            jObj            = new JSONObject(mResponseBuilder.toString());
            jArr            = jObj.getJSONArray("results");
 
            Log.d("LOG", Integer.toString(jArr.length()));
 
            for (int i = 0; i < jArr.length(); i++)
            {
                // 결과별로 결과 object 얻기
                JSONObject  result = jArr.getJSONObject(i);
 
                // 위도, 경도 얻기
                JSONObject  geo = result.getJSONObject("geometry");
                JSONObject  location = geo.getJSONObject("location");
                String      sLat = location.getString("lat");
                String      sLon = location.getString("lng");
 
                // 이름 얻기
                String      name = result.getString("name");
 
                // Rating 얻기
                String      rating = "0";
                if (result.has("rating"== true)
                    rating  = result.getString("rating");
 
                mList.add(new cList(Float.valueOf(rating), Double.valueOf(sLat), Double.valueOf(sLon), name));
            }
        }
        catch (JSONException e)
        {
            e.printStackTrace();
        }
    }
cs
  • 파싱은 JSON을 이용해 파싱을하는데, 방법은 JSONObject와 JSONArray를 사용한다. 둘 다 안드로이드에서 기본으로 사용 가능하다.
  • 두가지 차이점
    • ":[" 으로 묶인 Object는 배열 data이다. JSONArray를 사용해야하며, 얻어오는 방법은 getJSONArray(...) 이다.
    • ":{" 으로 묶인 Object는 JSONObject를 사용해야 하며, 얻어오는 방법은 getJSONObject(...) 이다.
  • 최종적으로 파싱하여 얻을 Data는 String으로 받으며, getString(...)을 사용하면 된다.
    • 즉, String을 가지고 다시 JSONObject 로 사용 불가능하다.
  • http://cy.cyworld.com/home/26568755/post/4096293

MainActivity 소스
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
public class MainActivity extends AppCompatActivity implements Runnable{
    cGPlacesAPI             places;
 
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        Thread              t = new Thread(this);
        t.start();
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
 
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
 
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
 
        return super.onOptionsItemSelected(item);
    }
 
    @Override
    public void run()
    {
        if (gps.isGetLocation())
        {
            places          = new cGPlacesAPI(this, gps.getLatitude(), gps.getLongitude(), 500"food|restaurant");
            places.parsing();
        }
 
        while (true)
        {
            try
            {
                Thread.sleep(50);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }
}
cs
  • 사용할 땐, Thread 내부에서 사용해야 GET을 보낼 수 있다.
    • Thread 만들고 run() 내부에서 호출하라는 뜻.


전체 소스 코드

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
public class cGPlacesAPI
{
    Context                 mContext;
    StringBuilder           mResponseBuilder = new StringBuilder();
 
    LinkedList<cList>       mList = new LinkedList<>();
 
    cGPlacesAPI(Context _con, double _lat, double _lon, double _radius, String _type)
    {
        mContext            = _con;
        try
            {
                String          uStr = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=" + _lat + "," + _lon + "&radius=" + _radius + "&types=" + _type + "&key=key";
                URL             url = new URL(uStr);
                BufferedReader  in = new BufferedReader(new InputStreamReader(url.openStream()));
                String          inputLine;
 
                while ((inputLine = in.readLine()) != null)
                {
                    mResponseBuilder.append(inputLine);
                }
                in.close();
            }
            catch (MalformedURLException me)
            {
                me.printStackTrace();
            }
            catch (UnsupportedEncodingException ue)
            {
            ue.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
 
    public void parsing()
    {
        try
        {
            JSONArray       jArr;
            JSONObject      jObj;
 
            jObj            = new JSONObject(mResponseBuilder.toString());
            jArr            = jObj.getJSONArray("results");
 
            Log.d("LOG", Integer.toString(jArr.length()));
 
            for (int i = 0; i < jArr.length(); i++)
            {
                // 결과별로 결과 object 얻기
                JSONObject  result = jArr.getJSONObject(i);
 
                // 위도, 경도 얻기
                JSONObject  geo = result.getJSONObject("geometry");
                JSONObject  location = geo.getJSONObject("location");
                String      sLat = location.getString("lat");
                String      sLon = location.getString("lng");
 
                // 이름 얻기
                String      name = result.getString("name");
 
                // Rating 얻기
                String      rating = "0";
                if (result.has("rating"== true)
                    rating  = result.getString("rating");
 
                mList.add(new cList(Float.valueOf(rating), Double.valueOf(sLat), Double.valueOf(sLon), name));
            }
        }
        catch (JSONException e)
        {
            e.printStackTrace();
        }
    }
 
    public LinkedList<cList> getList()
    {
        return mList;
    }
}
 
cs


http://blog.naver.com/hyuki0920/140111581692

'Programming > Android' 카테고리의 다른 글

font size px to sp  (0) 2016.04.22
디스플레이에 따른 이미지 크기 및 위치 설정  (0) 2016.03.28
Activity로 Dialog Popup 만들기  (0) 2016.03.05
시간 데이터 얻어오기.  (0) 2015.12.05
Android GPS 사용  (0) 2015.12.05
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
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
글 보관함