본문 바로가기

spring/소스코드

KAKAOAPI를 이용한 지역검색,마커,페이징

페이징 클래스 : Creteria.java

//시작 페이지,DISPLAY,페이지 정보
package com.example.domain;
public class Criteria{
	  private int page;
	  private int perPageNum;
	  //한 페이지에 출력할 수 있는 개수
	  public Criteria(){
	    this.page = 1;
	    this.perPageNum = 3;
	    //한 페이지당 3개가 나온다.
	  }
	  //페이지를 입력 안했을때 설정
	  public void setPage(int page){
	    if (page <= 0){
	      this.page = 1;
	      return;
	    }
	    this.page = page;
	  }
	  //시작 페이지 지정 메서드
	  public void setPerPageNum(int perPageNum){
	    if(perPageNum <= 0 || perPageNum > 100){
	      this.perPageNum = 10;
	      return;
	    }
	    this.perPageNum = perPageNum;
	  }
	  public int getPage(){
	    return page;
	  }
	  //실저 데이터를 몇개 부터 가져올지 가져오는 메서드
	  public int getPageStart(){
	    return (this.page - 1) * perPageNum;
	  }
	  
	  public int getPerPageNum(){
	    return this.perPageNum;
	  }
	  @Override
	  public String toString(){
	    return "Criteria [page=" + page + ", " + "perPageNum=" + perPageNum + "]";
	  }
	}

 

 

PageMaker.java

:페이징클래스

//페이지 번호 클래스
package com.example.domain;
public class PageMaker{
	  private int totalCount;
	  
	  private int startPage;
	  private int endPage;
	  
	  //true,false 값으로 리턴
	  private boolean prev;
	  //이전 버튼이 보여지는지
	  private boolean next;
	  //다음 버튼이 보여지는지
	  
	  private int displayPageNum = 10;
	  //한페이지당 보여지는 데이터 개수
	  
	  private Criteria cri;
	  
	  public void setCri(Criteria cri){
	    this.cri = cri;
	  }
	  public void setTotalCount(int totalCount){
	    this.totalCount = totalCount;
	    calcData();
	  }
	  private void calcData(){
	    endPage = (int) (Math.ceil(cri.getPage() / (double) displayPageNum) * displayPageNum);
	    startPage = (endPage - displayPageNum) + 1;
	    int tempEndPage = (int) (Math.ceil(totalCount / (double) cri.getPerPageNum()));
	    if(endPage > tempEndPage){
	      endPage = tempEndPage;
	    }
	    prev = startPage == 1 ? false : true;
	    next = endPage * cri.getPerPageNum() >= totalCount ? false : true;
	  }
	public int getStartPage() {
		return startPage;
	}
	public void setStartPage(int startPage) {
		this.startPage = startPage;
	}
	public int getEndPage() {
		return endPage;
	}
	public void setEndPage(int endPage) {
		this.endPage = endPage;
	}
	public boolean isPrev() {
		return prev;
	}
	public void setPrev(boolean prev) {
		this.prev = prev;
	}
	public boolean isNext() {
		return next;
	}
	public void setNext(boolean next) {
		this.next = next;
	}
	public int getDisplayPageNum() {
		return displayPageNum;
	}
	public void setDisplayPageNum(int displayPageNum) {
		this.displayPageNum = displayPageNum;
	}
	public int getTotalCount() {
		return totalCount;
	}
	public Criteria getCri() {
		return cri;
	}
}

LocalVO.java 

Local table 클래스 

package com.example.domain;

public class LocalVO {
	private int id;
	private String place;
	private String address;
	private String tel;
	
	
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getPlace() {
		return place;
	}
	public void setPlace(String place) {
		this.place = place;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public String getTel() {
		return tel;
	}
	public void setTel(String tel) {
		this.tel = tel;
	}
	
	
	@Override
	public String toString() {
		return "LocalVO [id=" + id + ", place=" + place + ", address=" + address + ", tel=" + tel + "]";
	}
	
	
	
}

LocalDAO.Interface

package com.example.persistence;

import java.util.*;

import com.example.domain.*;

public interface LocalDAO {
	public List list(Criteria cri)throws Exception;
}

LocalDAOImpl.java

package com.example.persistence;

import java.util.List;

import javax.inject.Inject;

import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Repository;

import com.example.domain.Criteria;
import com.example.domain.LocalVO;

@Repository
public class LocalDAOImp implements LocalDAO{
	@Inject
	SqlSession session;
	private static final String namespace="LocalMapper";
	@Override
	public List list(Criteria cri) throws Exception {
		// TODO Auto-generated method stub
		return session.selectList(namespace +".list",cri);
	}

}

LocalController.java

package com.example.web;

import java.util.HashMap;
import java.util.List;

import javax.inject.Inject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.example.domain.Criteria;
import com.example.domain.LocalVO;
import com.example.domain.PageMaker;
import com.example.persistence.LocalDAO;

@Controller
public class LocalController {
	@Inject
	LocalDAO dao;
	
	@ResponseBody
	@RequestMapping("local.json")
	public HashMap<String, Object> list(Criteria cri) throws Exception{
		cri.setPerPageNum(10);
		
		PageMaker pm=new PageMaker();
		pm.setCri(cri);
		pm.setTotalCount(60);
		
		HashMap<String, Object> map=new HashMap<String, Object>();
		map.put("list", dao.list(cri));
		map.put("pm",pm);
		return map;
	}
}

LocalMapper.xml

1
2
3
4
5
6
7
8
9
10
11
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
<mapper  namespace="LocalMapper">
    <select id="list" resultType="com.example.domain.LocalVO">
        select * from local 
        order by id desc
        limit #{pageStart}, #{perPageNum}
    </select>
</mapper>
 
 
 

local.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>


	카카오 지역 검색
		#divmap{
         width:700px;
         height:530px;
         background:gray;
         position:absolute;
         top:20%;
         left:20%;
         margin-top:-50px;
         margin-left:-150px;
         padding:10px;
         z-index:1000;
         display:none;
      }
	[카카오 지역 검색] 선택저장 검색:    건
	{{#each documents}}
	<tr class="row">
		<td><input type="checkbox"></td>
		<td>{{place_name}}</td>
		<td>{{address_name}}</td>
		<td>{{phone}}</td>
		<td><button class="mapView" x="{{x}}" y="{{y}}" place="{{place_name}}" tel="{{phone}}">지도보기</button></td>
	</tr>
	{{/each}}
	더보기

닫기
	{{#each list}}
	<tr>
		<td>{{id}}</td>
		<td>{{place}}</td>
		<td>{{address}}</td>
		<td>{{tel}}</td> 
	</tr>
	{{/each}}
	

	var page=1;
	var page1=1;
	
	var query=$("#query").val();
	var is_end=false;
	
	getList();
	
	getLocal();
	function getLocal(){
		$.ajax({
			type:"get",
			url:"local.json",
			data:{"page":page1},
			success:function(data){
				var temp=Handlebars.compile($("#temp1").html());
				$("#tbl1").html(temp(data));
				
				var str="";
				
				if(data.pm.prev){
					str +="<a href='"+ (data.pm.startPage-1) +"'>"+"◀</a>";
				}
				for(var i=data.pm.startPage; i<=data.pm.endPage; i++){
					str +="<a href='" + i + "'>" + i + "</a>";
				}
				if(data.pm.next){
					str +="<a href='"+(data.pm.endPage+1) +"'>"+"◀</a>";
				}
				$("#pagination").html(str);
			}
		});
	}
	$("#pagination").on("click","a", function(e){
		e.preventDefault();
		page1=$(this).attr("href");
		getLocal();
	});
	
	
	//chkAll 버튼을 누르면 테이블에 모든 버튼을 체크됨 
	$("#chkAll").on("click",function(){
		if($(this).is(":checked")){
			$("#tbl .row input:checkbox").each(function(){
				$(this).prop("checked", true);
			});
		}else{
			$("#tbl tr input:checkbox").each(function(){
				$(this).prop("checked", false);
			});
		}
	});
	
	$("#tbl").on("click","tr .mapView", function(){
		
		
	
		$("#divmap").show();
		var lat=$(this).attr("y");
		//위도
		var lng=$(this).attr("x");
		//경도
		//alert(lat +"-"+ lng);
		var place=$(this).attr("place");
		var tel=$(this).attr("tel");
		
		var container = document.getElementById('map'); //지도를 담을 영역의 DOM 레퍼런스
		var options = { //지도를 생성할 때 필요한 기본 옵션
			center: new kakao.maps.LatLng(lat, lng), //지도의 중심좌표.
			level: 3 //지도의 레벨(확대, 축소 정도)
	};
		var map = new kakao.maps.Map(container, options); //지도 생성 및 객체 리턴	
		var marker=new kakao.maps.Marker({
			position:new kakao.maps.LatLng(lat, lng)
		});
		marker.setMap(map);
		
			var str="<div>" + place + "</div>";
				str +="<div>" + tel + "</div>";
			//출력할 impormation 생성
			var info=new kakao.maps.InfoWindow({
				content:str
			})
		kakao.maps.event.addListener(marker, "mouseover",function(){
			info.open(map, marker);
		});
		kakao.maps.event.addListener(marker, "mouseout",function(){
			info.close(map, marker);
		});

	});
	
	$("#btnClose").on("click", function(){
		$("#divmap").hide();
	});
	$("#btnMore").on("click",function(){
		if(!is_end){
			page += 1;
			getList();
		}
	});
	$("#btnSearch").on("click", function(){
		$("#tbl").html("");
		page=1;
		query=$("#query").val();
		getList();
	});
	$("#query").keydown(function(key){
		if(key.keyCode==13){
			$("#tbl").html("");
			page=1;
			query=$("#query").val();
			getList();
		}
	});
	
	function getList(){
		$.ajax({
			type:"get",
			url:"https://dapi.kakao.com/v2/local/search/keyword.json",
			headers:{"Authorization":"KakaoAK 6baa3500ff42695b48d705aa87132cb3"},
			dataType:"json",
			data:{"query":query,"page":page,"size":"10"},
			success:function(data){
				var temp=Handlebars.compile($("#temp").html());
				$("#tbl").append(temp(data));
				$("#total").html(data.meta.total_count);
				//$("#container").html(temp(data));내용이 refresh
				//$("#container").appned(temp(data));내용이 추가
				is_end=data.meta.is_end;
			}
		});
	}