- 오늘은 네이버에 있는 영화검색 및 상품검색 데이터를 테이블로 가지고 오는 작업을 해보도록 하겠다.
https://developers.naver.com/main/
- ex12 프로젝트를 생성하고 이전에 ex10에서 사용했던 resources와 home.jsp를 넣는다.
- movie mapper를 만들어서 기존 db의 데이터를 가지고 와보도록 하겠다.
/ex12/src/main/resources/mapper/MovieMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.MovieMapper">
<select id="list" resultType="hashmap">
select * from tbl_movie
order by id desc
limit #{pageStart},#{perPageNum}
</select>
</mapper>
/ex12/src/main/java/com/example/mapper/MovieDAO.java
package com.example.mapper;
import java.util.HashMap;
import java.util.List;
import com.example.domain.Criteria;
public interface MovieDAO {
public List<HashMap<String, Object>> list(Criteria cri);
}
/ex12/src/main/java/com/example/mapper/MovieDAOImpl.java
package com.example.mapper;
import java.util.HashMap;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.example.domain.Criteria;
@Repository
public class MovieDAOImpl implements MovieDAO {
@Autowired
SqlSession session;
String namespace="com.example.mapper.MovieMapper";
@Override
public List<HashMap<String, Object>> list(Criteria cri) {
return session.selectList(namespace+".list",cri);
}
}
- TEST
/ex12/src/test/java/com/example/controller/MysqlTest.java
package com.example.controller;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.example.domain.Criteria;
import com.example.mapper.MovieDAO;
import com.example.mapper.MysqlMapper;
@RunWith(SpringJUnit4ClassRunner.class) //먼저 SpringJUnit4ClassRunner.class import한다.
@ContextConfiguration(locations={"file:src/main/webapp/WEB-INF/spring/**/*.xml"})
public class MysqlTest {
@Autowired
private MovieDAO mapper;
@Test
public void getTime() {
Criteria cri = new Criteria();
mapper.list(cri);
}
}
- 이제 컨트롤러를 만들어서 출력까지 해보도록 하겠다.
- about.jsp, mList.jsp를 홈에서 출력할 수 있도록 하겠다.
/ex12/src/main/java/com/example/controller/MovieContorller.java
package com.example.controller;
import java.util.HashMap;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.example.domain.Criteria;
@Controller
public class MovieContorller {
@RequestMapping("/movie/list")
public String movieList(Model model){
model.addAttribute("pageName","mList.jsp");
return "home";
}
}
/ex12/src/main/webapp/WEB-INF/views/mList.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<h1>[현재 상영작]</h1>
/ex12/src/main/java/com/example/controller/HomeController.java
package com.example.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class HomeController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Model model) {
model.addAttribute("pageName","about.jsp");
return "home";
}
}
/ex12/src/main/webapp/WEB-INF/views/about.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<h1>What is API?</h1>
<p>An application Programming Interface is a connection between
computers or between computer programs. It is a type of software
interface, offering a service to other pieces of software. A document
or standard that describes how to build or use such a connection or
interface is called an API specification.</p>
/ex12/src/main/webapp/WEB-INF/views/home.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<title>검색 API</title>
<link rel="stylesheet" href="/resources/home.css" />
<script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.1/handlebars.js"></script>
</head>
<body>
<div id="page">
<div id="header">
<a href="/" title="홈으로"><img src="/resources/back.png" width=920 /></a>
</div>
<div id="center">
<div id="menu">
<a href="/movie/list" title="영화목록으로">영화목록</a>
</div>
<div id="content">
<jsp:include page="${pageName}"></jsp:include>
</div>
</div>
<div id="footer">
<h3>Copyright API Practice. All rights Reserved.</h3>
</div>
</div>
</body>
</html>
- 이제 json을 이용해 출력해보도록 하겠다.
/ex12/src/main/java/com/example/controller/MovieContorller.java
...
@RequestMapping("/movie.json")
@ResponseBody
public HashMap<String, Object> movieJSON(Criteria cri){
HashMap<String, Object> map = new HashMap<String,Object>();
map.put("list", mdao.list(cri));
map.put("cri", cri);
// 하단 페이징
PageMaker pm = new PageMaker();
pm.setCri(cri);
// select하여 구한 총갯수
pm.setTotalCount(80);
map.put("pm", pm);
return map;
}
}
- 데이터에 있는 총 데이터 갯수를 출력하여 paging까지 할 수 있도록 하겠다.
/ex12/src/main/resources/mapper/MovieMapper.xml
...
<select resultType="int" id="totalCount">
select count(*) from tbl_movie
</select>
</mapper>
/ex12/src/main/java/com/example/mapper/MovieDAO.java
public int totalCount();
}
/ex12/src/main/java/com/example/mapper/MovieDAOImpl.java
@Override
public int totalCount() {
return session.selectOne(namespace+".totalCount");
}
}
/ex12/src/main/java/com/example/controller/MovieContorller.java
@RequestMapping("/movie.json")
@ResponseBody
public HashMap<String, Object> movieJSON(Criteria cri){
HashMap<String, Object> map = new HashMap<String,Object>();
map.put("list", mdao.list(cri));
// 하단 페이징
PageMaker pm = new PageMaker();
pm.setCri(cri);
// select하여 구한 총갯수
pm.setTotalCount(mdao.totalCount());
map.put("cri", cri);
map.put("pm", pm);
return map;
}
}
/ex12/src/main/webapp/WEB-INF/views/mList.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<h1>[현재 상영작]</h1>
<style>
#movies {
overflow: hidden;
text-align: center;
}
.box {
float: left;
width: 150px;
height: 250px;
margin: 12px;
background :rgb(253, 252, 240);
padding: 5px;
}
</style>
<h3 id="total"></h3>
<hr />
<div id="movies"></div>
<script id="temp" type="text/x-handlebars-template">
{{#each list}}
<div class="box">
<div class="image">
<img src="/display?file={{image}}" width=150 />
</div>
<div class="title">{{title}}</div>
</div>
{{/each}}
</script>
<div id="pagination" class="pagination"></div>
<script src="/resources/pagination.js"></script>
<script>
var page = 1;
getList();
function getList() {
$.ajax({
type : 'get',
url : '/movie.json',
data : {
page : page
},
dataType : 'json',
success : function(data) {
var temp = Handlebars.compile($('#temp').html());
$('#movies').html(temp(data));
$('#pagination').html(getPagination(data));
$('#total').html("현재 상영작 : " + data.pm.totalCount + "개");
}
})
}
$("#pagination").on('click', 'a', function(e) {
e.preventDefault();
page = $(this).attr("href");
getList();
})
</script>
- 이제 영화 검색 페이지를 만들도록 하겟다.
/ex12/src/main/java/com/example/controller/MovieContorller.java
@RequestMapping("/movie/search")
public String movieSearch(Model model){
model.addAttribute("pageName","mSearch.jsp");
return "home";
}
/ex12/src/main/webapp/WEB-INF/views/mSearch.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<h1>네이버 영화 검색</h1>
- 네이버 검색 API를 이용하겠다. java
https://developers.naver.com/docs/serviceapi/search/blog/blog.md#%EB%B8%94%EB%A1%9C%EA%B7%B8
/ex12/src/main/java/com/example/domain/NaverAPI.java
//애플리케이션 클라이언트 아이디값"
//애플리케이션 클라이언트 시크릿값"
확인해서 넣는다.
package com.example.domain;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class NaverAPI {
public static void search(String url, String query) {
String clientId = "DSISkunI4gxjpwj6Yl6J"; // 애플리케이션 클라이언트 아이디값"
String clientSecret = "CxLnF9_VmQ"; // 애플리케이션 클라이언트 시크릿값"
String text = null;
try {
text = URLEncoder.encode(query, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("검색어 인코딩 실패", e);
}
String apiURL = url + "?query=" + text; // json
// 결과
// String apiURL =
// "https://openapi.naver.com/v1/search/blog.xml?query="+ text; // xml
// 결과
Map<String, String> requestHeaders = new HashMap<>();
requestHeaders.put("X-Naver-Client-Id", clientId);
requestHeaders.put("X-Naver-Client-Secret", clientSecret);
String responseBody = get(apiURL, requestHeaders);
System.out.println(responseBody);
}
private static String get(String apiUrl, Map<String, String> requestHeaders) {
HttpURLConnection con = connect(apiUrl);
try {
con.setRequestMethod("GET");
for (Map.Entry<String, String> header : requestHeaders.entrySet()) {
con.setRequestProperty(header.getKey(), header.getValue());
}
int responseCode = con.getResponseCode();
if (responseCode == 200) { // 정상 호출
return readBody(con.getInputStream());
} else { // 에러 발생
return readBody(con.getErrorStream());
}
} catch (IOException e) {
throw new RuntimeException("API 요청과 응답 실패", e);
} finally {
con.disconnect();
}
}
private static HttpURLConnection connect(String apiUrl) {
try {
URL url = new URL(apiUrl);
return (HttpURLConnection) url.openConnection();
} catch (MalformedURLException e) {
throw new RuntimeException("API URL이 잘못되었습니다. : " + apiUrl, e);
} catch (IOException e) {
throw new RuntimeException("연결이 실패했습니다. : " + apiUrl, e);
}
}
private static String readBody(InputStream body) {
// 한글 깨짐 해결 한글 깨짐 해결 한글 깨짐 해결 한글 깨짐 해결
InputStreamReader streamReader = null;
try {
streamReader = new InputStreamReader(body,"UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try (BufferedReader lineReader = new BufferedReader(streamReader)) {
StringBuilder responseBody = new StringBuilder();
String line;
while ((line = lineReader.readLine()) != null) {
responseBody.append(line);
}
return responseBody.toString();
} catch (IOException e) {
throw new RuntimeException("API 응답을 읽는데 실패했습니다.", e);
}
}
}
- 웹에 출력해보도록 하겠다.
/ex12/src/main/java/com/example/domain/NaverAPI.java
public class NaverAPI {
public static String search(String url, String query, int page) {
String clientId = "DSISkunI4gxjpwj6Yl6J"; // 애플리케이션 클라이언트 아이디값"
String clientSecret = "CxLnF9_VmQ"; // 애플리케이션 클라이언트 시크릿값"
int start = (page - 1) * 10 + 1;
String text = null;
try {
text = URLEncoder.encode(query, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("검색어 인코딩 실패", e);
}
String apiURL = url + "?query=" + text + "&start" + start;
// String apiURL =
// "https://openapi.naver.com/v1/search/blog.xml?query="+ text; // xml
// 결과
Map<String, String> requestHeaders = new HashMap<>();
requestHeaders.put("X-Naver-Client-Id", clientId);
requestHeaders.put("X-Naver-Client-Secret", clientSecret);
String responseBody = get(apiURL, requestHeaders);
//System.out.println(responseBody);
return responseBody;
}
/ex12/src/main/java/com/example/controller/MovieContorller.java
@RequestMapping("/movie/search.json")
@ResponseBody
public String movieSearchJSON(Model model, String query, int page){
//page=1;
//query="터미네이터";
String url="https://openapi.naver.com/v1/search/movie.json";
return NaverAPI.search(url,query,page);
}
- jsp에 출력해보도록 하겠다.
/ex12/src/main/webapp/WEB-INF/views/mSearch.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<h1>[영화 검색]</h1>
<style>
#movies {
overflow: hidden;
text-align: center;
}
.box {
float: left;
width: 150px;
height: 250px;
margin: 12px;
background :rgb(253, 252, 240);
padding: 5px;
}
</style>
<div>
<h3 id="total"></h3>
<input type="text" id="query" placeholder="검색"/>
</div>
<hr />
<div id="movies"></div>
<script id="temp" type="text/x-handlebars-template">
{{#each items}}
<div class="box">
<div class="image">
<img src="{{image}}" width=150 />
</div>
<div class="title">{{{title}}}</div>
</div>
{{/each}}
</script>
<div id="pagination" class="pagination"></div>
<script src="/resources/pagination.js"></script>
<script>
var page = 1;
getList();
$("#query").on('keypress',function(e){
if(e.keyCode==13){
page=1;
getList();
}
});
function getList() {
var query=$("#query").val();
$.ajax({
type : 'get',
url : '/movie/search.json',
data : {
page : page,
query : query
},
dataType : 'json',
success : function(data) {
var temp = Handlebars.compile($('#temp').html());
$('#movies').html(temp(data));
//$('#pagination').html(getPagination(data));
$('#total').html("현재 상영작 : " + data.pm.totalCount + "개");
}
})
}
$("#pagination").on('click', 'a', function(e) {
e.preventDefault();
page = $(this).attr("href");
getList();
})
</script>
- 네이버에서 검색한 영화 목록을 데이터베이스에 insert하겠다.
/ex12/src/main/resources/mapper/MovieMapper.xml
<insert id="insert">
insert into tbl_movie(title,image)
values(#{title},#{image})
</insert>
</mapper>
/ex12/src/main/java/com/example/mapper/MovieDAO.java
public void insert(String title, String image);
}
/ex12/src/main/java/com/example/mapper/MovieDAOImpl.java
@Override
public void insert(String title, String image) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("title", title);
map.put("image", image);
session.insert(namespace+".insert", map);
}
}
/ex12/src/main/java/com/example/controller/MovieContorller.java
@ResponseBody
@RequestMapping(value="/movie/insert",method=RequestMethod.POST)
public void insert(String title, String image){
// 이미지 복사
try {
if(image!=null && !image.equals("")){
URL url = new URL(image);
InputStream in = url.openStream();
String path="c:/data/upload";
String file ="/movie/"+System.currentTimeMillis()+".jpg";
OutputStream out = new FileOutputStream(path+file);
FileCopyUtils.copy(in, out);
mdao.insert(title, file);
}
} catch (Exception e) {
System.out.println("insert error : "+e.toString());
}
}
/ex12/src/main/webapp/WEB-INF/views/mSearch.jsp
...
<div>
<h3 id="total"></h3>
<button id="btnInsert">데이터 저장</button>
<input type="text" id="query" placeholder="검색" />
</div>
<hr />
<div id="movies"></div>
<script id="temp" type="text/x-handlebars-template">
{{#each items}}
<div class="box">
<div class="image">
<img src="{{image}}" width=150 />
</div>
<div class="title">{{{title}}}</div>
</div>
{{/each}}
</script>
<div id="pagination" class="pagination"></div>
<script src="/resources/pagination.js"></script>
<script>
var page = 1;
getList();
$("#btnInsert").on("click", function() {
if (!confirm("해당 데이터를 저장하시겠습니까?"))
return;
$("#movies .box").each(function() {
var image = $(this).find("img").attr("src");
var title = $(this).find(".title").text();
$.ajax({
type : 'post',
url : '/movie/insert',
data : {
image : image,
title : title
},
success : function() {
}
})
alert("저장되었습니다.");
});
});
...
- 영화 검색을 통해서 총 검색 갯수를 출력해보도록 하겠다.
- 우선 json-simple 라이브러리를 추가한다.
/ex12/pom.xml
...
<dependencies>
<!-- 새로운 라이브러리 추가 시작 -->
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
...
/ex12/src/main/java/com/example/controller/MovieContorller.java
...
@RequestMapping("/movie/search.json")
@ResponseBody
public JSONObject movieSearchJSON(Model model, String query, int page) {
String url = "https://openapi.naver.com/v1/search/movie.json";
String result = NaverAPI.search(url, query, page);
JSONParser parser = new JSONParser();
JSONObject object = null;
try {
object = (JSONObject) parser.parse(result);
Criteria cri = new Criteria();
cri.setPage(page);
object.put("cri", cri);
PageMaker pm = new PageMaker();
pm.setCri(cri);
String total = object.get("total").toString();
pm.setTotalCount(Integer.parseInt(total));
object.put("pm", pm);
} catch (Exception e) {
System.out.println("오류:" + e.toString());
}
return object;
}
...
- 카카오 지도 API를 이용해 지역검색 페이지를 만들어보겠다.
https://developers.kakao.com/docs/latest/ko/local/dev-guide
/setup/src/main/java/com/example/domain/KakaoAPI.java
package com.example.domain;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class KakaoAPI {
public static String search(String apiURL) {
try {
URL url = new URL(apiURL);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Authorization", "KakaoAK 본인 REST API");
int responseCode = con.getResponseCode();
BufferedReader br;
// 정상 호출인 경우
if (responseCode == 200) {
br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
// 에러 발생가 발생한 경우
} else {
br = new BufferedReader(new InputStreamReader(con.getErrorStream()));
}
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = br.readLine()) != null) {
response.append(inputLine);
}
br.close();
System.out.println(response.toString());
return response.toString();
} catch (Exception e) {
return e.toString();
}
}
}
/ex12/src/main/java/com/example/controller/LocalController.java
package com.example.controller;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.example.domain.Criteria;
import com.example.domain.KakaoAPI;
import com.example.domain.PageMaker;
@Controller
public class LocalController {
@RequestMapping("/local.json")
@ResponseBody
public JSONObject localJSON(String query, int page) {
JSONObject object = new JSONObject();
String url = "https://dapi.kakao.com/v2/local/search/keyword.json?";
url+="?query="+ query + "&page=" + page;
String result = KakaoAPI.search(url);
try {
JSONParser parser = new JSONParser();
object = (JSONObject) parser.parse(result);
Criteria cri = new Criteria();
cri.setPage(page);
object.put("cri", cri);
PageMaker pm = new PageMaker();
pm.setCri(cri);
JSONObject obj = (JSONObject)object.get("meta");
String total = obj.get("total_count").toString();
pm.setTotalCount(Integer.parseInt(total));
object.put("pm", pm);
} catch (Exception e) {
System.out.println("result -> object error : " + e.toString());
}
return object;
}
}
- 지도 검색 페이지 생성
/ex12/src/main/java/com/example/controller/LocalController.java
@RequestMapping("/local/search")
public String localSearch(Model model){
model.addAttribute("pageName","lsearch.jsp");
return "home";
}
/ex12/src/main/webapp/WEB-INF/views/lSearch.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<h1>[지역 검색]</h1>
<style>
#movies {
overflow: hidden;
text-align: center;
}
.box {
float: left;
width: 150px;
height: 250px;
margin: 12px;
background: rgb(253, 252, 240);
padding: 5px;
}
</style>
<div>
<h3 id="total"></h3>
<button id="btnInsert">데이터 저장</button>
<input type="text" id="query" placeholder="검색" />
</div>
<hr />
<table id="locals"></table>
<script id="temp" type="text/x-handlebars-template">
{{#each documents}}
<tr class="row">
<td class="name" width=200>{{place_name}}</td>
<td class="address" width=300>{{address_name}}</td>
<td class="phone" width=200>{{{phone}}}</td>
<td><button>위치보기</button></td>
</tr>
{{/each}}
</script>
<div id="pagination" class="pagination"></div>
<script src="/resources/pagination.js"></script>
<script>
var page = 1;
var query = $("#query").val();
getList();
$("#query").on('keypress', function(e) {
if (e.keyCode == 13) {
page = 1;
getList();
}
});
function getList() {
var query = $("#query").val();
$.ajax({
type : 'get',
url : '/local.json',
data : {
page : page,
query : query
},
dataType : 'json',
success : function(data) {
var temp = Handlebars.compile($('#temp').html());
$('#locals').html(temp(data));
$('#pagination').html(getPagination(data));
$('#total').html("지역 검색 결과 : " + data.pm.totalCount + "개");
}
})
}
$("#pagination").on('click', 'a', function(e) {
e.preventDefault();
page = $(this).attr("href");
getList();
})
</script>
- 위치보기 버튼을 클릭하여 해당 위치의 지도를 보여주겠다.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<script type="text/javascript"
src="//dapi.kakao.com/v2/maps/sdk.js?appkey=437cd2932e9baa6f039994ed90c57549"></script>
<h1>[지역 검색]</h1>
<style>
table {
border-collapse: collapse;
background: white;
}
#map{
margin:0px auto;
margin-top:50px;
}
</style>
<div>
<h3 id="total"></h3>
<button id="btnInsert">데이터 저장</button>
<input type="text" id="query" placeholder="검색" />
</div>
<hr />
<table id="locals"></table>
<script id="temp" type="text/x-handlebars-template">
{{#each documents}}
<tr class="row">
<td class="name" width=200>{{place_name}}</td>
<td class="address" width=300>{{address_name}}</td>
<td class="phone" width=200>{{{phone}}}</td>
<td><button x="{{x}}" y="{{y}}" name="{{place_name}}" phone="{{phone}}">위치보기</button></td>
</tr>
{{/each}}
</script>
<!-- 페지이 출력부 -->
<div id="pagination" class="pagination"></div>
<!-- 지도 출력부 -->
<div id="map" style="width: 500px; height: 400px;"></div>
<script src="/resources/pagination.js"></script>
<script>
var page = 1;
var query = $("#query").val();
getList();
var x=126.570667;
var y=33.450701;
var phone="";
var name="";
printMap();
$('#locals').on('click','.row button',function(){
x=$(this).attr("x");
y=$(this).attr("y");
name=$(this).attr("name");
phone=$(this).attr("phone");
printMap();
});
// 지도 출력 함수
function printMap(){
var container = document.getElementById('map'); //지도를 담을 영역의 DOM 레퍼런스
var options = { //지도를 생성할 때 필요한 기본 옵션
center: new kakao.maps.LatLng(y, x), //지도의 중심좌표.
level: 3 //지도의 레벨(확대, 축소 정도)
};
var map = new kakao.maps.Map(container, options); //지도 생성 및 객체 리턴
// 마커가 표시될 위치입니다
var markerPosition = new kakao.maps.LatLng(y, x);
// 마커를 생성합니다
var marker = new kakao.maps.Marker({
position: markerPosition
});
// 마커가 지도 위에 표시되도록 설정합니다
marker.setMap(map);
// 마커를 클릭했을 때 마커 위에 표시할 인포윈도우를 생성합니다
var iwContent = '<div style="padding:5px;">'
iwContent+=name+ '<hr/>' +phone;
iwContent+='</div>'
iwRemoveable = true; // removeable 속성을 ture 로 설정하면 인포윈도우를 닫을 수 있는 x버튼이 표시됩니다
// 인포윈도우를 생성합니다
var infowindow = new kakao.maps.InfoWindow({
content : iwContent,
removable : iwRemoveable
});
// 마커에 클릭이벤트를 등록합니다
kakao.maps.event.addListener(marker, 'click', function() {
// 마커 위에 인포윈도우를 표시합니다
infowindow.open(map, marker);
});
}
$("#query").on('keypress', function(e) {
if (e.keyCode == 13) {
page = 1;
getList();
}
});
function getList() {
var query = $("#query").val();
$.ajax({
type : 'get',
url : '/local.json',
data : {
page : page,
query : query
},
dataType : 'json',
success : function(data) {
var temp = Handlebars.compile($('#temp').html());
$('#locals').html(temp(data));
$('#pagination').html(getPagination(data));
$('#total').html("지역 검색 결과 : " + data.pm.totalCount + "개");
}
})
}
$("#pagination").on('click', 'a', function(e) {
e.preventDefault();
page = $(this).attr("href");
getList();
})
</script>
- Github 연습
'ICIA 수업일지' 카테고리의 다른 글
2021.10.25 수업일지(Spring Framework, Web Socket) (0) | 2021.10.25 |
---|---|
2021.10.22 수업일지(Spring Framework, Web Socket) (3) | 2021.10.22 |
2021.10.20 수업일지(Spring Framework, Github, Git, Jsoup, Selenium) (0) | 2021.10.20 |
2021.10.19 수업일지(Spring Framework, Interceptor, Google API) (0) | 2021.10.19 |
2021.10.18 수업일지(Spring Framework, Interceptor) (0) | 2021.10.18 |