본문 바로가기
ETC.../Android

구글맵 주소로 위, 경도 얻어오기

by izen8 2014. 5. 15.
반응형

 

- 구글맵에 Geocoder를 사용하면 주소로 위도경도를 받아올수 있는데 세팅하기가 엄청 귀찮습니다.

- 편리하게(?) 주소를 입력하면 위도경도를  받아오는 방법을 소개할까 합니다.

 

////////////////////////////////////////////////////////////////////////////////////////////////////

1. 매니페스트에     <uses-permission android:name="android.permission.INTERNET" /> 을 추가해준다~

 

2. String findAddress="부산시 북구 만덕2동";

     geoPointTask = new geoPointTask().execute(findAddress); 

 //네트워크 작업이기 때문에 어싱크태스크로 돌려줍니다

 

 

 

private class geoPointTask extends AsyncTask<String, Void, Void> {

@Override

protected void onPreExecute() {

super.onPreExecute();

}

 

@Override

protected Void doInBackground(String... params) {

getGeoPoint(getLocationInfo(params[0].replace("\n", " ")

.replace(" ", "%20")));  //주소를 넘겨준다(공백이나 엔터는 제거합니다)

 

return null;

}


@Override

protected void onPostExecute(Void result) {

 

}

}

 

public static JSONObject getLocationInfo(String address) {

 

HttpGet httpGet = new HttpGet(

"http://maps.google.com/maps/api/geocode/json?address="

+ address + "&ka&sensor=false"); 

//해당 url을 인터넷창에 쳐보면 다양한 위도 경도 정보를 얻을수있다(크롬 으로실행하세요)

HttpClient client = new DefaultHttpClient();

HttpResponse response;

StringBuilder stringBuilder = new StringBuilder();

 

try {

response = client.execute(httpGet);

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 = new JSONObject();

try {

jsonObject = new JSONObject(stringBuilder.toString());

} catch (JSONException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

 

return jsonObject;

}

 

 

public static void getGeoPoint(JSONObject jsonObject) {

 

 

Double lon = new Double(0);

Double lat = new Double(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 (JSONException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

 

 

Log.d("myLog", "경도:" + lon ); //위도/경도 결과 출력

   Log.d("myLog", "위도:" + lat  );

 

 

 

}

반응형

댓글