본문 바로가기

Programming/과거포스팅

주소를 좌표로 (google maps api) address to postion


구글 api를 이용하여 주소를 좌표로 변환하는 메서드이다. 우선 메이븐에 json 라이브러리를 추가한다
<dependency>
	<groupId>com.googlecode.json-simple</groupId>
	<artifactId>json-simple</artifactId>
	<version>1.1.1</version>
</dependency>
json으로 받아서 double 배열에 담아서 리턴한다.
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;
}