여기에는 스프링 프레임워크를 사용하여 웹 애플리케이션을 위한 MVC 컨트롤러 EgovHbzScrapController가 정의되어 있습니다. 이 컨트롤러는 여러 웹 페이지 경로와 관련된 HTTP 요청을 처리하고, 데이터 스크랩 서비스를 이용하여 결과를 뷰에 제공합니다. 코드를 설명하면 다음과 같습니다.
패키지 선언: 이 클래스는 egovframework.hbz.web 패키지에 속해있습니다.
임포트: 필요한 Java 클래스와 인터페이스 라이브러리를 임포트합니다.
Logger 설정: EgovHbzScrapController 클래스의 로거를 설정하여 로그 메시지를 기록할 수 있습니다.
Service 주입: EgovHbzScrapServiceImpl 서비스를 자동으로 주입합니다(@Autowired 애너테이션 사용).
@Controller 애너테이션: 이 클래스가 컨트롤러로 작동한다는 것을 나타냅니다.
스케줄러 대기 코드: 주석 처리된 코드로, 현재 사용되지 않지만 주기적인 작업을 위해 사용될 수 있습니다.
User
Assistant
이 코드는 EgovHbzScrapServiceImpl이라는 클래스로 되어 있으며, 데이터 스크래핑과 관련된 여러 가지 서비스를 제공할 목적으로 작성되었습니다. 클래스는 EgovHbzScrapService 인터페이스를 구현합니다.
다음은 주요 내용입니다:
필요한 라이브러리와 클래스를 임포트합니다. 예를 들어 Jsoup을 사용하여 HTML을 파싱하고, JSON을 처리하기 위한 json-simple 라이브러리 등이 있습니다.
클래스 정의와 @Service 어노테이션으로 이 클래스가 서비스 계층의 컴포넌트임을 명시합니다.
멤버 변수 egovHbzScrpDao는 @Autowired를 통해 자동 주입되어, DAO(Data Access Object) 계층에 접근할 수 있게 합니다.
API와 관련된 상수(ENCODING_KEY, DECODING_KEY, KEY, DEC_KEY, base_url)를 정의합니다.
여러 개의 메소드들이 있으며, 각각 스크래핑 로직이 포함되어 있습니다. 예를 들어 hospitalInfo 메소드는 지정된 주소를 사용하여 공공데이터포털에서 병원 기본 정보를 스크래핑합니다.
HospitalPage 메소드는 요양기호(ykiho)를 사용해서 병원 상세 정보를 조회합니다.
newsRank 메소드는 네이버 뉴스 랭킹을 스크래핑합니다.
webtoonScrap 메소드는 지정된 웹툰 상세 페이지를 스크래핑합니다.
getVilageFcst 메소드는 지역과 시간에 따른 기상청 단기예보를 조회합니다.
User
Assistant
완료 버튼을 클릭했을 때 병원 위치 마커들을 표시하는 로직을 고치기 위해, 현재의 이벤트 핸들러에서 카카오 맵 API를 호출하는 부분을 별도의 함수로 분리해야 합니다. 그런 다음 완료 버튼의 클릭 이벤트에서 해당 함수를 호출하도록 만들면 됩니다.
다음은 수정할 수 있는 코드 예시입니다:
병원 위치 마커를 표시하는 기능을 함수로 만듭니다.
완료 버튼 클릭 시 위에서 만든 함수를 호출해서 카카오 맵에 마커를 표시하게 합니다.
먼저 병원 위치 마커 표시 기능을 함수로 분리합니다.
javascript
function displayHospitalMarkers() {
// 이 부분에 기존에 사용했던 병원 마커를 표시하는 코드를 넣습니다.
var positions = [
<c:forEach var="hospital" items="${hospitalList}" varStatus="status">
{
title: '${hospital.yadmNm}',
ykiho: '${hospital.ykiho}',
latlng: new kakao.maps.LatLng(${hospital.YPos}, ${hospital.XPos})
},
<c:if test="${!status.last}"></c:if>
</c:forEach>
];
// positions 배열을 이용한 마커 로직은 그대로...
}
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
@Service
public class EgovHbzScrapServiceImpl implements EgovHbzScrapService{
@Autowired
EgovHbzScrpDao egovHbzScrpDao;
final String ENCODING_KEY = "9toq77DZvOo2Wo4a9jGNKUlG%2BogjcApjs3texQK9Xj0brXm1Qs2l3mt0pSzBkYyoaKhO6izphKkgGxT9w7SRHQ%3D%3D";
final String DECODING_KEY = "9toq77DZvOo2Wo4a9jGNKUlG+ogjcApjs3texQK9Xj0brXm1Qs2l3mt0pSzBkYyoaKhO6izphKkgGxT9w7SRHQ==";
final String KEY = "9toq77DZvOo2Wo4a9jGNKUlG%2BogjcApjs3texQK9Xj0brXm1Qs2l3mt0pSzBkYyoaKhO6izphKkgGxT9w7SRHQ%3D%3D";
final String DEC_KEY = "9toq77DZvOo2Wo4a9jGNKUlG+ogjcApjs3texQK9Xj0brXm1Qs2l3mt0pSzBkYyoaKhO6izphKkgGxT9w7SRHQ==";
<div id="wrap">
<!-- container 시작 -->
<div id="main_container">
<!-- hospital 섹션 -->
<section class="page-section hospital" id="hospital">
<div class="container">
<br>
<div class="row justify-content-center">
<div class="col-md-6 col-lg-4 mb-5"
style="position: relative; display: flex; justify-content: center; align-items: center; height: 100%; transform: translateY(-25px);">
<!-- 인체 모양-->
<c:url value='/images/human.png' var="imgSrc" />
<img src="${imgSrc}" alt="Alternative Text"
style="width: 90%; height: 90%;" />
<!-- 전면 버튼 시작-->
<!-- 머리 버튼 -->
<div id="head-btn" class="position-absolute translate-middle"
style="top: 7%; left: 49.9%;">
<button class="btn btn-primary btn-opacity"
style="width: 70px; height: 90px; border-radius: 50%;"
data-bs-toggle="modal" data-bs-target="#hospitalModal1"></button>
</div>
</div>
</div>
</div>
</section>
<!-- 병원 위치 지도 섹션-->
<section class="page-section hospital"
style="height: 1000px;">
<div class="row justify-content-center" style="width: 99%;">
<div class="col-md-6 col-lg-4 mb-5"
style="position: relative; display: flex; justify-content: center; align-items: center;">
<h1>지도가 나오는 부분</h1>
</div>
</div>
<div style= "position: relative; display: flex; justify-content: center; align-items: center;" >
<div style="width:1000px; height:500px;" id="map"></div>
</div>
</section>
<!-- 모달창 구간 -->
<!-- 머리 -->
<div class="hospital-modal modal fade" id="hospitalModal1"
tabindex="-1" aria-labelledby="hospitalModal1" aria-hidden="true">
<div class="modal-dialog modal-xl">
<div class="modal-content">
<div style="position: relative;">
<button class="btn-close" type="button" data-bs-dismiss="modal"
aria-label="Close" style="position: absolute; right: 0;"></button>
</div>
<div class="modal-body text-center pb-5">
<div class="container">
<div class="row justify-content-center">
<div class="col-lg-8">
<h2
class="hospital-modal-title text-secondary text-uppercase mb-0">머리</h2>
<div class="divider-custom">
<div class="divider-custom-line"></div>
<div class="divider-custom-icon">
<i class="fas fa-star"></i>
</div>
<div class="divider-custom-line"></div>
</div>
<button class="btn btn-primary"
onclick="closeModalAndScrollToSection(); getUserLocation();">
<i class="fas fa-xmark fa-fw"></i> 완료
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Bootstrap core JS-->
<script
src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
<!-- Core theme JS-->
<script src="js/scripts.js"></script>
<!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *-->
<!-- * * SB Forms JS * *-->
<!-- * * Activate your form at https://startbootstrap.com/solution/contact-forms * *-->
<!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *-->
<script src="https://cdn.startbootstrap.com/sb-forms-latest.js"></script>
<!-- 스크립트 부분 -->
<script type="text/javascript"
src="//dapi.kakao.com/v2/maps/sdk.js?appkey=5aedc9bc48ee8cf5b21c312d3905ad16&libraries=services"></script>
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
<!--자바 스크립트 -->
<script>
var geocoder = new kakao.maps.services.Geocoder();
// 지도 표시
var mapContainer = document.getElementById('map'); // 지도를 표시할 div
var mapOption = {
center : new kakao.maps.LatLng(33.450701, 126.570667), // 지도의 중심좌표
level : 7 // 지도의 확대 레벨
};
// 지도를 표시할 div와 지도 옵션으로 지도를 생성합니다
var map = new kakao.maps.Map(mapContainer, mapOption);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var lat = position.coords.latitude; // 위도
var lon = position.coords.longitude; // 경도
var locPosition = new kakao.maps.LatLng(lat, lon); // 마커가 표시될 위치를 geolocation으로 얻어온 좌표로 생성합니다
var message = '<div style="padding:5px;">여기에 계신가요?!</div>'; // 인포윈도우에 표시될 내용입니다
// 마커와 인포윈도우를 표시합니다
displayMarker(locPosition, message);
});
}
// 병원 위치 정보 확인
function getUserLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var lat = position.coords.latitude; // 위도
var lon = position.coords.longitude; // 경도
var locPosition = new kakao.maps.LatLng(lat, lon); // 마커가 표시될 위치를 geolocation으로 얻어온 좌표로 생성합니다
var message = '<div style="padding:5px;">여기에 계신가요?!</div>'; // 인포윈도우에 표시될 내용입니다
// 마커와 인포윈도우를 표시합니다
displayMarker(locPosition, message);
// 이제 lat과 lon을 사용할 수 있으므로 geocoder.coord2RegionCode와 console.log에서 사용할 수 있습니다
geocoder.coord2RegionCode(lon, lat, function(result, status) {
if (status === kakao.maps.services.Status.OK) {
var fullAddress = result[0].address_name;
console.log('전체 주소: ' + fullAddress);
// 여기에서 슬라이싱을 통해 원하는 부분의 주소를 얻어냅니다.
var slicedAddress = fullAddress.slice(0, 12); // 예: 주소의 처음 12글자 ex(경산북도 경산시 하양읍)
console.log('슬라이싱된 주소: ' + slicedAddress);
// 그리고 나서 이 주소를 API에 전달합니다.
$.ajax({
url: '/hbz/Hospital.do', // 요청을 보낼 API의 URL을 적어주세요.
type: 'GET',
data: {address: slicedAddress},
dataType: 'html', // 서버로 보내는 데이터의 타입을 'json'으로 지정합니다
success: function(response) {
// 서버로부터 응답이 올 경우 실행할 함수
// 'response' 변수에는 서버로부터 받은 응답이 들어있습니다.
console.log(response);
$('body').html(response);
// 사용자 위치를 사용하는 코드를 여기에 위치시킵니다.
// 예: 위치에 따른 마커 표시 등
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("AJAX 요청 실패: " + textStatus);
console.log("에러 내용: " + errorThrown);
}
});
}
});
});
} else {
// HTML5의 GeoLocation을 사용할 수 없을 때 처리
console.log('Geolocation을 지원하지 않는 브라우저입니다.');
}
}
// 현재위치 마커 및 정보
function displayMarker(locPosition, message) {
var marker = new kakao.maps.Marker({
map : map,
position : locPosition
});
var iwContent = message;
var iwRemoveable = true;
var infowindow = new kakao.maps.InfoWindow({
content : iwContent,
removable : iwRemoveable
});
infowindow.open(map, marker);
map.setCenter(locPosition);
}
// 위치 지역 마킹 찍는 함수
var positions = [
<c:forEach var="hospital" items="${hospitalList}" varStatus="status">
{
title: '${hospital.yadmNm}',
ykiho: '${hospital.ykiho}',
latlng: new kakao.maps.LatLng(${hospital.YPos}, ${hospital.XPos})
},
<c:if test="${!status.last}"></c:if>
</c:forEach>
];
for (var i = 0; i < positions.length; i ++) {
// 마커 이미지의 이미지 크기 입니다
var imageSize = new kakao.maps.Size(24, 35);
var imageSrc = "https://t1.daumcdn.net/localimg/localimages/07/mapapidoc/markerStar.png";
// 마커 이미지를 생성합니다
var markerImage = new kakao.maps.MarkerImage(imageSrc, imageSize);
// 마커를 생성합니다
var marker = new kakao.maps.Marker({
map: map, // 마커를 표시할 지도
position: positions[i].latlng, // 마커를 표시할 위치
title : positions[i].title, // 마커의 타이틀, 마커에 마우스를 올리면 타이틀이 표시됩니다
image : markerImage // 마커 이미지
});
// 마커를 클릭했을 때 마커 위에 표시할 인포윈도우를 생성합니다
var iwContent = positions[i].title;
var iwRemoveable = true; // removeable 속성을 ture 로 설정하면 인포윈도우를 닫을 수 있는 x버튼이 표시됩니다
// 인포윈도우를 생성합니다
var infowindow = new kakao.maps.InfoWindow({
content : iwContent,
removable : iwRemoveable
});
// 마커에 클릭이벤트를 등록합니다
kakao.maps.event.addListener(marker, 'click', (function(marker, infowindow, ykiho) {
return function() {
// 마커 위에 인포윈도우를 표시합니다
infowindow.open(map, marker);
console.log(ykiho);
$.ajax({
url: '/hbz/HospitalInfo.do', // API 경로
type: 'GET', // 요청 방식
data: {
ykiho: ykiho
},
success: function(data) {
console.log(data);
$('body').html(data);
},
error: function(error) {
console.log("실패");
}
});
};
})(marker, infowindow, positions[i].ykiho));
// 사용자의 위치를 API부분으로 옮긴다
var userPosition;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
userPosition = {
latitude: position.coords.latitude,
longitude: position.coords.longitude
};
});
}
}
</script>
<script type="text/javascript">
function closeModalAndScrollToSection() {
// 모달들을 선택
var modals = document.querySelectorAll(".hospital-modal");
modals.forEach(function (modal) {
// 모달 인스턴스 가져오기
var modalInstance = bootstrap.Modal.getInstance(modal);
// 모달을 닫음
if (modalInstance) {
modalInstance.hide();
}
// 모달이 완전히 닫힌 후에 실행될 이벤트 리스너
modal.addEventListener('hidden.bs.modal', function onModalHidden() {
// 이 이벤트 리스너를 제거함으로써 다시는 실행되지 않음
modal.removeEventListener('hidden.bs.modal', onModalHidden);
const mapElement = document.getElementById('map');
if (mapElement) {
// 'map' 섹션의 시작 부분으로 스크롤
mapElement.scrollIntoView({
behavior: 'smooth',
block: 'start'
});
}
});
});
}
</script>
여기서 jsp 파일의 아래 머리 버튼을 누르면 모달창이 뜨는데
모달창 아래의 완료 버튼을 누르면 카카오 맵에 관련 병원 위치 마커들이 표시가 돼.
완료
그리고 카카오맵의 해당 병원 위치 마커를 클릭하면 아래 ajax 코드가 실행되는데
.ajax({
url: '/hbz/HospitalInfo.do', // API 경로
type: 'GET', // 요청 방식
data: {
ykiho: ykiho
},
success: function(data) {
console.log(data);
('body').html(data);
},
error: function(error) {
console.log("실패");
}
});
이런 식으로 카카오맵의 마커를 누르는 게 아니라 완료 버튼을 누르면 ajax가 실행되도록 고치고 싶어. 해결해줘.
그리고 완료 버튼 클릭 시 displayHospitalMarkers 함수와 getUserLocation 함수를 호출하도록 수정합니다.
이 코드는 사용자가 머리 부분을 클릭할 때 나타나는 모달의 완료 버튼에 클릭 이벤트를 추가합니다. 클릭 시 모달을 닫고, 스크롤을 맵 섹션으로 이동시키며, 현재 사용자의 위치를 가져온 다음 해당 사용자의 위치 주변에 병원 위치 마커들을 표시합니다.
맵에 병원 마커들을 표시하는 로직이 많은 양의 데이터 렌더링 때문에 자칫 느려질 수도 있으니 성능을 확인하면서 조정하는 것이 좋습니다. 또한, 실제 백엔드 API에서는 hospitalList와 같이 병원 데이터 목록이 있다면, 이 데이터를 사용자에게 제공하기 전에 프론트엔드에 필요한 형식으로 가공하는 것이 좋습니다. 이는 불필요한 데이터 전송을 줄이고 프론트엔드의 성능을 향상시킬 수 있습니다.