구글 api를 이용하여 주소를 좌표로 변환하는 메서드이다. 우선 메이븐에 json 라이브러리를 추가한다
json으로 받아서 double 배열에 담아서 리턴한다.<dependency> <groupId>com.googlecode.json-simple</groupId> <artifactId>json-simple</artifactId> <version>1.1.1</version> </dependency>
public static double [] getAdressToPosition(String korAddress) { String urlStr; HttpURLConnection connection = null; BufferedReader reader = null; StringBuilder stringBuilder; double position[]; try { urlStr = "http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=" + URLEncoder.encode(korAddress, "utf-8"); URL url = new URL(urlStr); connection = (HttpURLConnection) url.openConnection(); connection.setReadTimeout(1000); // read the output from the server if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); stringBuilder = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { stringBuilder.append(line + "\n"); } Object obj = JSONValue.parse(stringBuilder.toString()); System.out.println(obj); JSONObject location = (JSONObject) obj; JSONArray arr = (JSONArray) location.get("results"); location = (JSONObject) arr.get(0); location = (JSONObject) location.get("geometry"); location = (JSONObject) location.get("location"); position = new double[2]; position[0] = Double.parseDouble(String.valueOf(location.get("lat"))); position[1] = Double.parseDouble(String.valueOf(location.get("lng"))); } else { position = null; } } catch (IOException e) { position = null; e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return position; }
'Programming > 과거포스팅' 카테고리의 다른 글
자바 날짜 포멧 변환 (java String date format change) (0) | 2014.12.23 |
---|---|
Tomcat DNS(톰캣 도메인 설정) (0) | 2014.08.14 |
poi excel geCellValue (0) | 2014.06.12 |
jquery tr 아래위로 이동 (jquery tr up down) (0) | 2014.05.29 |
radio 버튼 체크된 값 가져오기 (0) | 2014.05.28 |