본문 바로가기

JSON

JSON - 카카오API활용예제(지역)

검색 유틸 메서드

package util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.json.JSONArray;
import org.json.JSONObject;

import json.vo.KakaoLocalVo;

public class KakaoSearchUtils {
	
	public static List<KakaoLocalVo> searchJson(String query, String y, String x, int page, int size, int radius){
		List<KakaoLocalVo> list = new ArrayList<KakaoLocalVo>();
		
		try {
			// query Encoding
			query = URLEncoder.encode(query,"utf-8");
			
			String str_url = String.format("https://dapi.kakao.com/v2/local/search/keyword.json?query=%s&y=%s&x=%s&page=%d&size=%d&radius=%d",
					query,y,x,page,size,radius);
			String KAKAO_APIKEY = MyOpenAPIKey.Kakao.API_Key;
			
			URL url = new URL(str_url);
			HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
			
			urlConn.setRequestProperty("Authorization", KAKAO_APIKEY);
			urlConn.setRequestProperty("Content-Type", "application/json");
			urlConn.connect();
			
			InputStreamReader isr = new InputStreamReader(urlConn.getInputStream(),"utf-8");
			BufferedReader br = new BufferedReader(isr);
			
			StringBuilder sb = new StringBuilder();
			
			while(true) {
				String data = br.readLine();
				if(data==null) {
					break;
				}
				sb.append(data);
				
			}// end:while
			
			JSONObject json = new JSONObject(sb.toString());
			JSONArray localArray = json.getJSONArray("documents");
			
			for(int i = 0; i<localArray.length(); i++) {
				JSONObject local = localArray.getJSONObject(i);
				
				String place_name 			= local.getString("place_name");
				String place_url 			= local.getString("place_url");
				String address_name 		= local.getString("address_name");
				String road_address_name 	= local.getString("road_address_name");
				String phone 				= local.getString("phone");
				String xx					= local.getString("x");
				String yy					= local.getString("y");
				int distance = 0;
				try {
					distance = local.getInt("distance");
				} catch (Exception e) {
					// TODO: handle exception
				}
				
				// KakaoLocalVo 포장
				KakaoLocalVo vo = new KakaoLocalVo();
				vo.setPlace_name(place_name);
				vo.setPlace_url(place_url);
				vo.setAddress_name(address_name);
				vo.setRoad_address_name(road_address_name);
				vo.setPhone(phone);
				vo.setX(xx);
				vo.setY(yy);
				vo.setDistance(distance);
				
				// ArrayList 추가
				list.add(vo);
			}
			
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		return list;
	}

 

)Vo

package json.vo;

public class KakaoLocalVo {

	String place_name;
	String place_url;
	String address_name; // 주소
	String road_address_name; // 도로명 주소
	String phone;
	int distance; // 거리
	String y; // 위도
	String x; // 경도
	
	public String getPlace_name() {
		return place_name;
	}
	public void setPlace_name(String place_name) {
		this.place_name = place_name;
	}
	public String getPlace_url() {
		return place_url;
	}
	public void setPlace_url(String place_url) {
		this.place_url = place_url;
	}
	public String getAddress_name() {
		return address_name;
	}
	public void setAddress_name(String address_name) {
		this.address_name = address_name;
	}
	public String getRoad_address_name() {
		return road_address_name;
	}
	public void setRoad_address_name(String road_address_name) {
		this.road_address_name = road_address_name;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public int getDistance() {
		return distance;
	}
	public void setDistance(int distance) {
		this.distance = distance;
	}
	public String getY() {
		return y;
	}
	public void setY(String y) {
		this.y = y;
	}
	public String getX() {
		return x;
	}
	public void setX(String x) {
		this.x = x;
	}
	
}

 

)검색 폼 html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<style type="text/css">

	#box {
		width: 1000px;
		margin: auto;
		margin-top: 50px;
	}
</style>

<script type="text/javascript">

	let latitude;  // 위도
	let longitude; // 경도

	// window.onload
	$(document).ready(function(){
		// 현재위치 구하기
		getLocation();
	});
	
	function getLocation() {
		  if (navigator.geolocation) {
		    navigator.geolocation.getCurrentPosition(function(position){
		    	
		    	latitude = position.coords.latitude;
				longitude = position.coords.longitude;
		    });
		  } else {
		    alert("Geolocation is not supported by this browser.");
		  }
	}
	// 밑의 함수를 하나로 합쳐놓은 것이다.
	
/* 	function getLocation() {
		  if (navigator.geolocation) {
		    navigator.geolocation.getCurrentPosition(showPosition);
		  } else {
		    alert("Geolocation is not supported by this browser.");
		  }
		}
	
		function showPosition(position) {
		  latitude = position.coords.latitude;
		  longitude = position.coords.longitude;
		  console.log("latitude", latitude);
		  console.log("longitude", longitude);
		} */
		
	function search() {
		let keyword = $("#keyword").val().trim();
		let page = $("#page").val();
		let size = $("#size").val();
		let radius = $("#radius").val();
		
		if(keyword=='') {
			alert("입력 하셔야지요");
			$("#keyword").val("");
			$("#keyword").focus();
			return;
		}
		
		// Ajax요청
		$.ajax({
			url			:	"search.do", // KakaoSearchAction
			data		:	{
							"query":keyword,"page":page,
							"size":size,"radius":radius,
							"latitude":latitude,"longitude":longitude
							},
			success		:	function(res_data){
				$("#disp").html(res_data);
			},
			error		:	function(err){
				alert(err.responseText);
			}
		});
		
	}

</script>
</head>
<body>
<form class="form-inline">
	<div id="box">
		검색어:<input class="form-control" id="keyword">
		<input class=" btn btn-primary" type="button" value="검색" onclick="search();">
		
		&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
		페이지: <select class="form-control" id="page">
			<option value="1">1</option>
			<option value="2">2</option>
			<option value="3">3</option>
			<option value="4">4</option>
			<option value="5">5</option>
		</select>
		
		페이지당 건수: <select class="form-control" id="size">
			<option value="5">5</option>
			<option value="10">10</option>
			<option value="15">15</option>
		</select>
		
		반경: <select class="form-control" id="radius">
			<option value="1000">1000m</option>
			<option value="500">500m</option>
			<option value="5000">5000m</option>
		</select>
</form>
		<hr>
		<div id="disp"></div>
	</div>
</body>
</html>

 

)검색 서블릿

package action;

import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import json.vo.KakaoLocalVo;
import util.KakaoSearchUtils;

import java.io.IOException;
import java.util.List;

/**
 * Servlet implementation class KakaoSearchAction
 */
@WebServlet("/search.do")
public class KakaoSearchAction extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		// https://dapi.kakao.com/v2/local/search/keyword.json?query=학원&y=37.4809615&x=126.9521689&radius=1000&sort=distance&size=3&page=2
		
		// 0.수신인코딩
		request.setCharacterEncoding("utf-8");
		
		// 1. parameter 받기
		String query = request.getParameter("query");
		
		int page = 1;
		int size = 5;
		int radius = 1000;
		
		try {
			page = Integer.parseInt(request.getParameter("page"));
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		try {
			size = Integer.parseInt(request.getParameter("size"));
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		try {
			radius = Integer.parseInt(request.getParameter("radius"));
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		String y = request.getParameter("latitude");
		String x = request.getParameter("longitude");
		
		// Kakao 검색
		List<KakaoLocalVo> list = KakaoSearchUtils.searchJson(query, y, x, page, size, radius);
		
		request.setAttribute("list", list);

		// Dispatcher형식으로 호출
		String forward_page = "search_list.jsp";
		RequestDispatcher disp = request.getRequestDispatcher(forward_page);
		disp.forward(request, response);

	}

}

 

)리스트 jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
	<table class="table">
		<tr class="info">
			<th>상호</th>
			<th>주소(지번/도로명)</th>
			<th>전화</th>
			<th>거리(m)</th>
			<th>위치(위도/경도)</th>
		</tr>
		<!-- for(KakaoLocalVo vl : list) -->
		<c:forEach var="vo" items="${ list }">
			<tr>
				<td><a href="${ vo.place_url }" target="_blank">${ vo.place_name }</a></td>
				<td>
					지번:${ vo.address_name }<br>
					도로명:${ vo.road_address_name }<br>
				</td>
				<td>${ vo.phone }</td>
				<td>${ vo.distance }</td>
				<td>
					위도:${ vo.y } <br>
					경도:${ vo.x }
				</td>
			</tr>
		</c:forEach>
	</table>
	

</body>
</html>

'JSON' 카테고리의 다른 글

JSON - 카카오 API 설정  (0) 2024.07.09
JSON - 데이터 파싱  (0) 2024.07.09