<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>주변 주류 매장 찾기</title>
<script type="text/javascript"
src="//dapi.kakao.com/v2/maps/sdk.js?appkey=my_api_key&libraries=services"></script>
</head>
<body>
<div id="map" style="width:100%;height:400px;"></div>
<div id="result"></div>
<script>
fetch('http://localhost:8000/api/v1/subcontents/map/', {
method: 'GET',
headers: {
'Authorization': 'Bearer ' + localStorage.getItem('access_token')
}
})
.then(response => response.json())
.then(data => {
if (data.address) {
var geocoder = new kakao.maps.services.Geocoder();
// 주소를 좌표로 변환
geocoder.addressSearch(data.address, function (result, status) {
if (status === kakao.maps.services.Status.OK) {
var userLatitude = result[0].y;
var userLongitude = result[0].x;
var mapContainer = document.getElementById('map');
var mapOption = {
center: new kakao.maps.LatLng(userLatitude, userLongitude),
level: 3
};
// 지도 생성
var map = new kakao.maps.Map(mapContainer, mapOption);
// marker 이미지
var MarkerImage = new kakao.maps.MarkerImage(
'/src/images/user_marker.png',
new kakao.maps.Size(36, 35), // 마커 크기
{
offset: new kakao.maps.Point(18, 35) // 마커의 위치를 중앙 하단으로 설정
}
);
// 현재 유저의 위치에 마커 생성
var userMarker = new kakao.maps.Marker({
map: map,
position: new kakao.maps.LatLng(userLatitude, userLongitude),
title: "현재 위치", // 마커 위에 표시될 툴팁
zIndex: 2, // 다른 마커보다 위에 표시되도록 설정
image: MarkerImage
});
// 장소 검색 객체 생성
var places = new kakao.maps.services.Places();
var infowindow = new kakao.maps.InfoWindow(); // 인포윈도우를 외부에서 정의
// 주류 매장을 검색하는 함수 호출
places.keywordSearch('주류', function (result, status) {
if (status === kakao.maps.services.Status.OK) {
var resultDiv = document.getElementById('result');
resultDiv.innerHTML = ''; // 이전 결과를 초기화
// 검색 결과 출력 및 마커 생성
for (var i = 0; i < result.length; i++) {
(function (place) {
resultDiv.innerHTML += '<p>' + place.place_name + ' - ' + place.road_address_name + '</p>';
var marker = new kakao.maps.Marker({
map: map,
position: new kakao.maps.LatLng(place.y, place.x)
});
// 마커 클릭 시 인포윈도우 생성
kakao.maps.event.addListener(marker, 'click', function () {
// 인포윈도우를 닫고 새로운 내용으로 업데이트
infowindow.close();
infowindow.setContent('<div style="padding:5px;">' + place.place_name + '<br>' + place.road_address_name + '</div>');
infowindow.open(map, marker);
});
})(result[i]); // 클로저를 사용하여 각 마커에 대한 place 정보를 유지
}
} else {
alert("주변 주류 매장을 찾을 수 없습니다.");
}
}, {
location: new kakao.maps.LatLng(userLatitude, userLongitude),
radius: 2000
});
} else {
alert("주소를 찾을 수 없습니다.");
}
});
} else {
alert(data.message);
}
})
.catch(error => {
console.error('Error fetching user address:', error);
});
</script>
</body>
</html>
저번에 문제에 대한 이야기를 먼저 해보면 lib를 추가하지 않았다.
이거 안넣어서 안된다고 이야기 하고 있으니 문제가 해결이 될리가 있나.
API 주소에 보내는 요청은 로그인한 유저의 address를 받기만 하는 간단한 view이다.
class UserAddressAPIView(APIView):
permission_classes = [IsAuthenticated]
def get(self, request):
user = request.user
if user.address:
return Response({"address": user.address})
else:
return Response({
"message": "주소가 등록되어 있지 않습니다."
}, status=status.HTTP_400_BAD_REQUEST)
유저의 주소를 바탕으로 geocoder를 이용해서 유저가 있는 좌표값을 구한다.
그리고 주변 주류 매장에 대한 정보를 불러오는 식으로 먼저 구현을 하고 성공했다.
후에 문제점들을 살펴보니 아래와 같은 문제가 있었다.
- 가게에 대한 마커가 지도에 표시되지 않음
- 유저의 위치도 마커로 표시되지 않음
- 가게에 대한 마커를 구현했을 때 마커가 어디 가게를 가리키는지 모름
위의 문제점들에 대한 코드를 수정하고 나니 그래도 얼추 바라던 페이지가 나왔다.
조금의 수정과 css를 적용시켜서 레이아웃을 배치해야 하는 수정사항들이 남아있지만 바라던 방향으로 구현은 완료한 것 같다.
'웹 개발' 카테고리의 다른 글
[프로젝트] 커서 페이지네이션 (0) | 2024.10.11 |
---|---|
[프로젝트] API key를 숨기기 위한 처리 (2) | 2024.10.09 |
[프로젝트] 카카오 지도 api 구현 중 (1) | 2024.10.07 |
[프로젝트] 트러블 슈팅(프로필 조회) (0) | 2024.10.04 |
[프로젝트] django-cors-headers (0) | 2024.10.01 |