728x90
★ 프로젝트 생성
- Dynamic Web Project
- MapTest
- context : map
★ 카카오맵 API
- https://apis.map.kakao.com/
- https://apis.map.kakao.com/web/guide/
- https://www.flaticon.com/kr/free-icons/map-marker/2?k=1684393535380&log-in=google
- https://fonts.google.com/icons?selected=Material+Symbols+Outlined:liquor:FILL@0;wght@400;GRAD@0;opsz@48&icon.query=bar
■ 필요 파일
- "com.test.map"
- "Map.java"
- "MapDAO.java"
- "PlaceDTO.java"
- "CategoryDTO.java"
- webapp > WEB-INF > "views"
- "map.jsp"
■ 필요 라이브러리
jackson
json
jstl
lombok
myLibrary
Ojdbc
■ 데이터베이스
-- 카테고리
create table tblPlaceCategory (
seq number primary key,
name varchar2(100) not null,
marker varchar2(50) not null
);
-- 장소 등록
create table tblPlace (
seq number primary key, -- 번호(PK)
name varchar2(100) not null, -- 장소
lat number not null, -- 위도
lng number not null, -- 경도
cseq number not null references tblPlaceCategory(seq)
);
create sequence seqPlaceCategory;
create sequence seqPlace;
insert into tblPlaceCategory values (seqPlaceCategory.nextVal, '맛집', 'default');
insert into tblPlaceCategory values (seqPlaceCategory.nextVal, '카페', 'default');
insert into tblPlaceCategory values (seqPlaceCategory.nextVal, '운동', 'default');
insert into tblPlaceCategory values (seqPlaceCategory.nextVal, '빵집', 'default');
insert into tblPlaceCategory values (seqPlaceCategory.nextVal, '술집', 'default');
■ 소스 코드
- Map.java
package com.test.map;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/map.do")
public class Map extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//Map.java
MapDAO dao = new MapDAO();
List<PlaceDTO> mlist = dao.mlist(); //장소
List<CategoryDTO> clist = dao.clist(); //카테고리
setIcons(mlist);
req.setAttribute("mlist", mlist);
req.setAttribute("clist", clist);
RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/views/map.jsp");
dispatcher.forward(req, resp);
}
private void setIcons(List<PlaceDTO> mlist) {
for (PlaceDTO dto : mlist) {
if (dto.getCesq().equals("1")) {
dto.setCicon("restaurant_menu");
} else if (dto.getCesq().equals("2")) {
dto.setCicon("local_cafe");
} else if (dto.getCesq().equals("3")) {
dto.setCicon("fitness_center");
} else if (dto.getCesq().equals("4")) {
dto.setCicon("breakfast_dining");
} else if (dto.getCesq().equals("5")) {
dto.setCicon("liquor");
}
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
String name = req.getParameter("name");
String category = req.getParameter("category");
String lat = req.getParameter("lat");
String lng = req.getParameter("lng");
PlaceDTO dto = new PlaceDTO();
dto.setName(name);
dto.setCesq(category);
dto.setLat(lat);
dto.setLng(lng);
MapDAO dao = new MapDAO();
int result = dao.add(dto);
if (result == 1) {
resp.sendRedirect("/map/map.do");
} else {
PrintWriter writer = resp.getWriter();
writer.print("<script>alert('failed');history.back();</scirpt>");
writer.close();
}
}
}
- PlaceDTO.java
package com.test.map;
import lombok.Data;
@Data
public class PlaceDTO {
private String seq;
private String name;
private String lat;
private String lng;
private String cesq;
private String cicon;
}
- CategoryDTO.java
package com.test.map;
import lombok.Data;
@Data
public class CategoryDTO {
private String seq;
private String name;
private String marker;
}
- MapDAO.java
package com.test.map;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import com.test.my.DBUtil;
public class MapDAO {
private Connection conn;
private Statement stat;
private PreparedStatement pstat;
private ResultSet rs;
public MapDAO() {
this.conn = DBUtil.open();
}
public List<CategoryDTO> clist() {
try {
String sql = "select * from tblPlaceCategory order by name asc";
stat = conn.createStatement();
rs = stat.executeQuery(sql);
List<CategoryDTO> clist = new ArrayList<CategoryDTO>();
while (rs.next()) {
CategoryDTO dto = new CategoryDTO();
dto.setSeq(rs.getString("seq"));
dto.setName(rs.getString("name"));
dto.setMarker(rs.getString("marker"));
clist.add(dto);
}
return clist;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public int add(PlaceDTO dto) {
try {
String sql = "insert into tblPlace (seq, name, lat, lng, cseq) values (seqPlace.nextVal, ?, ?, ?, ?)";
pstat = conn.prepareStatement(sql);
pstat.setString(1, dto.getName());
pstat.setString(2, dto.getLat());
pstat.setString(3, dto.getLng());
pstat.setString(4, dto.getCesq());
return pstat.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
public List<PlaceDTO> mlist() {
try {
String sql = "select * from tblPlace order by name asc";
stat = conn.createStatement();
rs = stat.executeQuery(sql);
List<PlaceDTO> mlist = new ArrayList<PlaceDTO>();
while (rs.next()) {
PlaceDTO dto = new PlaceDTO();
dto.setSeq(rs.getString("seq"));
dto.setName(rs.getString("name"));
dto.setLat(rs.getString("lat"));
dto.setLng(rs.getString("lng"));
dto.setCesq(rs.getString("cseq"));
mlist.add(dto);
}
return mlist;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
- map.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://me2.do/5BvBFJ57">
<style>
#main {
display: flex;
align-items: flex-start;
}
#map {
border: 1px solid #CCC;
width: 550px;
height: 400px;
}
#list {
width: 200px;
margin-top: 0;
}
#add {
}
</style>
</head>
<body>
<h1>Map <small>Place</small></h1>
<div id="main">
<div id="map">지도</div>
<table id="list">
<c:forEach items="${mlist}" var="dto">
<tr>
<td style="display: flex; cursor:pointer;" data-lat="${dto.lat}" data-lng="${dto.lng}">
<span class="material-symbols-outlined">${dto.cicon}</span>
<div style="margin-top: 3px; margin-left:5px;">${dto.name}</div>
</td>
</tr>
</c:forEach>
</table>
</div>
<hr>
<form method="POST" action="/map/map.do">
<table id="add" class="vertical">
<tr>
<th>장소명</th>
<td><input type="text" name="name" id="name" class="long"></td>
</tr>
<tr>
<th>카테고리</th>
<td>
<select name="category" id="category">
<c:forEach items="${clist}" var="cdto">
<option value="${cdto.seq}">${cdto.name}</option>
</c:forEach>
</select>
</td>
</tr>
<tr>
<th>위치</th>
<td><div id="position"></div></td>
</tr>
</table>
<div>
<input type="submit" value="등록하기" id="btn">
</div>
<input type="hidden" name="lat" id="lat">
<input type="hidden" name="lng" id="lng">
</form>
<script type="text/javascript" src="//dapi.kakao.com/v2/maps/sdk.js?appkey=7b34a8317f5befe832f9eefe047ae818"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
var container = document.getElementById('map'); //지도를 담을 영역의 DOM 레퍼런스
var options = { //지도를 생성할 때 필요한 기본 옵션
center: new kakao.maps.LatLng(37.4993, 127.0331), //지도의 중심좌표.
level: 3 //지도의 레벨(확대, 축소 정도)
};
var map = new kakao.maps.Map(container, options); //지도 생성 및 객체 리턴
let m = null;
kakao.maps.event.addListener(map, 'click', function(event) {
if (m != null){
m.setMap(null);
}
$('#position').text(event.latLng);
$('#lat').val(event.latLng.getLat());
$('#lng').val(event.latLng.getLng());
m = new kakao.maps.Marker({
position: event.latLng
});
m.setMap(map);
});
$('#list td').click(function() {
//alert($(this).data('lat'));
if (m != null){
m.setMap(null);
}
let p = new kakao.maps.LatLng($(this).data('lat'), $(this).data('lng'));
m = new kakao.maps.Marker({
position: p
});
m.setMap(map);
map.panTo(p);
$('#list td').css('background-color', 'transparent');
$(this).css('background-color', 'gold');
});
</script>
</body>
</html>
■ 실행 결과
- 마커를 튜닝
- 모두 보기 기능 추가
- 카운트 하여, 마커가 찍히는 색상 표시
728x90
'Server' 카테고리의 다른 글
게시판 개발 STEP 2 - Board (0) | 2023.05.31 |
---|---|
게시판 개발 STEP 1 - Ajax, Json, Oracle, JDBC etc.. (0) | 2023.05.31 |
AJAX STEP 10 - 게시판 목록 보기 (0) | 2023.05.18 |
AJAX STEP 9 - 상품 목록 페이지 (0) | 2023.05.17 |
AJAX STEP 8 - 일기장 AJAX (0) | 2023.05.17 |