Map API polyline 관련한 문제

polyline을 적용했는데 배열 순서대로 그려지질 않고 랜덤으로 그려져서 새로고침을 할 때마다 순서가 바뀝니다 도저히 이유를 찾지 못하겠어서 혹시 답을 얻을 수 있을까 싶어 문의 남깁니다…

var arr = new Array();
<c:forEach items="${list}" var=“list”>
arr.push({
title: “${list.spot_title}”,
address: “${list.spot_address}”
});
</c:forEach>
var positions = arr;


	positions.forEach(function(pos, index){
		geocoder.addressSearch(positions[index].address, function(result, status) {
		
			 if (status === kakao.maps.services.Status.OK) {
				 
			        var coords = new kakao.maps.LatLng(result[0].y, result[0].x);
				       
				        var marker = new kakao.maps.Marker({
				            map: map,
				            position: coords,
				            image: markerImage
				        });
				       
				       marker.setMap(map);
					
			        var infowindow = new kakao.maps.InfoWindow({
			            content: '<div style="width:150px;text-align:center;padding:6px 0;">' + positions[index].title + '</div>'
			        });
			        
			        kakao.maps.event.addListener(marker, 'mouseover', makeOverListener(map, marker, infowindow));
				    kakao.maps.event.addListener(marker, 'mouseout', makeOutListener(infowindow));
			    	
			    	bounds.extend(new kakao.maps.LatLng(coords.Ma, coords.La));
			    	map.setBounds(bounds);
			    	
					linePath.push(new kakao.maps.LatLng(coords.Ma, coords.La)); 
					console.log(linePath);
					
					var polyline = new kakao.maps.Polyline({
								path: linePath, 
								strokeWeight: 3,
								strokeOpacity: 1,
								strokeColor: 'red',
								strokeStyle: 'solid'
					});
					
					polyline.setMap(map);

			 }
			 
			 });
		});

유사 게시글 답변 참고해주세요.

참고해 봐도 잘 모르겠습니다… 제 코드의 어디가 잘못된 걸까요

제가 답변을 잘못드렸네요.

비동기 로직으로 배열 순서와 관계없이
응답 결과가 먼저 온 데이터로 콜백 함수가 실행되기 때문에
path 값이 달라지게 됩니다.

비동기 로직을 순차 처리하는 방법은 아래 코드 참고해주세요.

var linePath = [];

var polyline = new kakao.maps.Polyline({
    path: linePath,
    strokeWeight: 3,
    strokeOpacity: 1,
    strokeColor: 'red',
    strokeStyle: 'solid'
});

const addressSearch = address => {
    return new Promise((resolve, reject) => {
        geocoder.addressSearch(address, function(result, status) {
            if (status === kakao.maps.services.Status.OK) {
                resolve(result);
            } else {
                reject(status);
            }
        });
    });
};

(async () => {
    try {
        for(let address of addressArray) {
            const result = await addressSearch(address);
            setPolyLine(result);
        }
    } catch (e) {
        console.log(e);
    }
})();

function setPolyLine(result) {
    const coords = new kakao.maps.LatLng(result[0].y, result[0].x);
    linePath.push(coords);
    polyline.setPath(linePath);

    if(!polyline.getMap()) {
        polyline.setMap(map);
    }
}

감사합니다 덕분에 해결했습니다 정말 감사합니다…ㅠㅠ 적게 일하고 많이 버세요…ㅠㅠ

1개의 좋아요