카카오맵 overay에 onclick event 생성하기

Mingtorr·2021년 4월 13일
1

오버레이의 온클릭 이벤트구현에 필요한 구체적인 코드는 마커를 사용할 때와는 다릅니다. 따라서 커스텀 오버레이로 생성한 마커는 일반 마커처럼 addListener 함수로 onclick 이벤트를 생성할 수 없습니다. 필요한 이벤트들은 content 내부에 넣을 HTML Element(EventTarget)들에게 각각 Native DOM 이벤트를 걸어주셔야 합니다.

먼저 제가 생성했던 문제의 overay onclick fucntion 입니다.

kakao.maps.event.addListener(marker, 'click', function() {
	console.log("click!!!");
});

위와 같이 입력하게 되면 클릭이벤트가 발생하지 않습니다. 클릭이벤트를 발생시키기 위해선 content 내부에 넣을 HTML Element(EventTarget)들에게 이벤트를 걸어야 합니다.

먼저, overay content 내부에 다음과 같이 함수를 생성할 수 있습니다.

var marker = new kakao.maps.CustomOverlay({
         map: map,
         position: position,
         content: markerreturn(key, positions, avg, zoom, housenum),<-함수생성 
         xAnchor: 0.5,
         yAnchor: 0.5,
         zIndex: 4,
       });
       markers.push(marker);

함수의 내용은 다음과 같습니다.
해당 코드는 elastic search에서 가져온 데이터들을 zoom 수준에 따라 다른 overay 디자인을 출력하는 코드입니다. 여기서 onclick 함수를 입력할 수 있습니다!!
파라미터 부분을 유의해서 봐주세요

function markerreturn(key, positions, avg, zoom, housenum) {
   const box = {
     data: positions[key].key,
     x: positions[key].location.hits.hits[0]._source.location.lat,
     y: positions[key].location.hits.hits[0]._source.location.lon,
   };

   const string = "asdasd";
   if (zoom <= 4) {
     const level = '<a href="#" class="level_box"  onclick="myFunction(\'' + positions[key].key + "," + 
positions[key].location.hits.hits[0]._source.location.lat + "," +
positions[key].location.hits.hits[0]._source.location.lon + "')\"}>"
+ '<div id="box_avg">' + '<p id="box_avg_p">' + avg + "</p>" + "</div>" +
'<div id="box_img">' + "</div>" + "</a>";

     return level;}
     .
     .
     .
     }
     

이때 클릭이벤트는 window.functioname으로 입력해야 합니다. 코드는 다음과 같습니다.

window.myFunction = (box) => {
   ///클릭 이벤트
   
   var splitstring = box.split(",");
   console.log(splitstring[0]);
   console.log(splitstring[1]);
   console.log(splitstring[2]);

위처럼 window.function 으로 입력하게 되면 정상적으로 overay에 onclick 이벤트를 생성할 수 있습니다.

profile
츄르 값 벌기 위해 코딩하는 아키텍쳐

0개의 댓글