Android

주소와 GeoCode

macro 2013. 10. 10. 12:49
반응형
1. 주소 -> geocode

publicstaticJSONObject getLocationInfo(String address){StringBuilder stringBuilder =newStringBuilder();try{

    address = address.replaceAll(" ","%20");HttpPost httppost =newHttpPost("http://maps.google.com/maps/api/geocode/json?address="+ address +"&sensor=false");HttpClient client =newDefaultHttpClient();HttpResponse response;
    stringBuilder =newStringBuilder();


        response = client.execute(httppost);HttpEntity entity = response.getEntity();InputStream stream = entity.getContent();int b;while((b = stream.read())!=-1){
            stringBuilder.append((char) b);}}catch(ClientProtocolException e){}catch(IOException e){}JSONObject jsonObject =newJSONObject();try{
        jsonObject =newJSONObject(stringBuilder.toString());}catch(JSONException e){// TODO Auto-generated catch block
        e.printStackTrace();}return jsonObject;}

이 함수 호출하고, 다음을 호출하면 된다.

publicstaticGeoPoint  getLatLong(JSONObject jsonObject){Double lon =newDouble(0);Double lat =newDouble(0);try{

            lon =((JSONArray)jsonObject.get("results")).getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getDouble("lng");

            lat =((JSONArray)jsonObject.get("results")).getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getDouble("lat");}catch(Exception e){
            e.printStackTrace();}returnnewGeoPoint((int)(lat *1E6),(int)(lon *1E6));}
 


2. 지오코드를 주소로.

private class HttpNetAddr extends AsyncTask<String, String, Boolean> {
// private ProgressDialog dialog;// private BitmapDrawable image;
private String address;private ProgressDialog dialog;
@Overrideprotected Boolean doInBackground(String... params) {// TODO Auto-generated method stub
return httpGetAddr();}
@Overrideprotected void onPostExecute(Boolean result) {// TODO Auto-generated method stubdialog.cancel();if (!result) {Toast toast = Toast.makeText(getApplicationContext(),"위치를 가져올 수 없습니다. GPS를 켜고 실행하세요.", Toast.LENGTH_SHORT);toast.show();finish();return;}
// 주소를 얻어왔으니, 화면에 다시 보여준다.TextView txt_addr = (TextView) findViewById(R.id.txt_addr);txt_addr.setText(address);// 그리고 리스트를 가져오는 쓰레드 수행시킨다.getPostingList();}
@Overrideprotected void onPreExecute() {// TODO Auto-generated method stubdialog = ProgressDialog.show(MainActivity.this, "","위치정보 갱신중...", true);
}
private Boolean httpGetAddr() {// TODO Auto-generated method stubtry {
// 이 부분은 이미지를 올리기 때문에 시간이 많이 걸리므로 다른 커넥션을 이용해야 한다. 그래야 다를 작업을// 수행가능함.HttpClient http_client = new DefaultHttpClient();// HttpClient http_client = HttpSingleton.getInstance();HttpGet http_get = new HttpGet("http://maps.googleapis.com/maps/api/geocode/json?latlng="+ lat + "," + lon + "&sensor=true&language="+ Locale.getDefault().getLanguage());
HttpResponse response = http_client.execute(http_get);
// //Log.i("ttttttttttt", "excute and response");
// 1. 버퍼로 json 읽기.BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"), 8);StringBuilder builder = new StringBuilder();for (String line = null; (line = reader.readLine()) != null;) {builder.append(line).append("\n");}
// 2. json 형식으로 만들기.JSONObject jObject = new JSONObject(builder.toString());
// 2-1. 에러 체크.if (jObject.getJSONArray("results").length() == 0) {
return false;}address = jObject.getJSONArray("results").getJSONObject(0).getString("formatted_address");
} catch (Exception e) {// TODO: handle exception// 네트워크 에러 처리return false;}return true;}}


반응형