마커는 생성되나 라벨이 생성이 안되는것은 왜그럴까여?

[FAQ] 지도/로컬 API 문의 전 꼭 읽어 주세요.

function updateMarkers() {
const bounds = new kakao.maps.LatLngBounds();

dataRows.forEach((row, index) => {
    const latitude = parseFloat(row[4]);
    const longitude = parseFloat(row[5]);

    if (isNaN(latitude) || isNaN(longitude)) {
        console.warn(`Invalid coordinates for row ${index}: [${latitude}, ${longitude}]`);
        return;
    }

    const label = `${row[0]} - ${row[1]}`;
    const markerPosition = new kakao.maps.LatLng(latitude, longitude);
    const key = `${latitude},${longitude}`;
    const isCompleted = row.includes("완료");

    if (markerDataMap[key]) {
        // Handle duplicate marker
        markerDataMap[key].rows.push({ index, row, completed: isCompleted });
        const duplicateCount = markerDataMap[key].rows.length;

        const markerImageSrc = "https://gobiztrip.synology.me/myproject/images/R_100.png";
        markerDataMap[key].marker.setImage(new kakao.maps.MarkerImage(markerImageSrc, getMarkerSize()));

        const duplicateLabel = `<div class="label" onclick="handleMarkerClick('${key}')">${label} 외 ${duplicateCount - 1}개</div>`;
        markerDataMap[key].overlay.setContent(duplicateLabel);
        markerDataMap[key].isDuplicate = true;

        if (markerDataMap[key].rows.every(item => item.completed)) {
            const completedMarkerImageSrc = "https://gobiztrip.synology.me/myproject/images/Gr_100.png";
            markerDataMap[key].marker.setImage(new kakao.maps.MarkerImage(completedMarkerImageSrc, getMarkerSize()));
            markerDataMap[key].overlay.setContent(`<div class="label completed">${label} 외 ${duplicateCount - 1}개 (완료)</div>`);
        }
    } else {
        const markerImageSrc = isCompleted
            ? "https://gobiztrip.synology.me/myproject/images/Gr_100.png"
            : "https://gobiztrip.synology.me/myproject/images/G100.png";
        const marker = new kakao.maps.Marker({
            position: markerPosition,
            image: new kakao.maps.MarkerImage(markerImageSrc, getMarkerSize())
        });
        marker.setMap(map);
        markers.push(marker);

        // Create label
        const labelContent = isCompleted 
            ? `<div class="label completed"><s>${label}</s></div>` 
            : `<div class="label">${label}</div>`;
        
        const customOverlay = new kakao.maps.CustomOverlay({
            content: labelContent,
            position: markerPosition,
            yAnchor: 2.1,
            zIndex: 3,
            clickable: true
        });
        customOverlay.setMap(map);

        markerDataMap[key] = { marker, overlay: customOverlay, rows: [{ index, row, completed: isCompleted }] };

        // Add click events to marker and overlay
        kakao.maps.event.addListener(marker, "click", () => handleMarkerClick(key));
        kakao.maps.event.addListener(customOverlay, "click", () => handleMarkerClick(key));

        // Zoom-level based visibility
        kakao.maps.event.addListener(map, 'zoom_changed', function() {        
            var level = map.getLevel();
            if (level <= 10) {
                customOverlay.setMap(map);
            } else {
                customOverlay.setMap(null);
            }
        });
    }

    bounds.extend(markerPosition);
});

if (dataRows.length > 0) {
    map.setBounds(bounds);
}

}

마커는 되는데 라벨을 못불러오는것은 왜그런가여 ?

First, let’s make sure that CSS styles are defined correctly in HTML

<style>
.label {
    display: block;
    padding: 5px 10px;
    background: #fff;
    border: 1px solid #ccc;
    border-radius: 3px;
    font-size: 12px;
    text-align: center;
    white-space: nowrap;
    pointer-events: auto;
    cursor: pointer;
}

.label.completed {
    color: #888;
    text-decoration: line-through;
}
</style>

Let’s update the CustomOverlay creation section as follows:

// Label creation function
function createCustomOverlay(position, content) {
    return new kakao.maps.CustomOverlay({
        position: position,
        content: content,
        yAnchor: 2.1,
        zIndex: 3,
        clickable: true,
        map: map // Doğrudan haritaya ekle
    });
}

// Usage
const labelContent = isCompleted 
    ? `<div class="label completed" onclick="handleMarkerClick('${key}')">${label}</div>` 
    : `<div class="label" onclick="handleMarkerClick('${key}')">${label}</div>`;

const customOverlay = createCustomOverlay(markerPosition, labelContent);

Let’s update the updateMarkers function:

function updateMarkers() {
    // Clear existing markers and labels
    markers.forEach(marker => marker.setMap(null));
    Object.values(markerDataMap).forEach(data => {
        if (data.overlay) data.overlay.setMap(null);
        if (data.marker) data.marker.setMap(null);
    });

    const bounds = new kakao.maps.LatLngBounds();
    markers = [];
    markerDataMap = {};

    dataRows.forEach((row, index) => {
         // Your current code...
        
        // Control label visibility
        const currentZoom = map.getLevel();
        if (currentZoom <= 10) {
            customOverlay.setMap(map);
        }
    });

    // Harita sınırlarını ayarla
    if (dataRows.length > 0) {
        map.setBounds(bounds);
    }
}

update the Zoom event:

kakao.maps.event.addListener(map, 'zoom_changed', function() {
    const currentZoom = map.getLevel();
    Object.values(markerDataMap).forEach(data => {
        if (currentZoom <= 10) {
            data.overlay.setMap(map);
        } else {
            data.overlay.setMap(null);
        }
    });
});

Let’s add checks for debugging:

function debugOverlays() {
    console.log('Marker Data Map:', markerDataMap);
    Object.entries(markerDataMap).forEach(([key, data]) => {
        console.log(`Overlay for ${key}:`, {
            position: data.overlay.getPosition(),
            map: data.overlay.getMap(),
            content: data.overlay.getContent()
        });
    });
}

Check the console (with the F12 key)
Make sure the map zoom level is 10 or lower
Check the data in the markerDataMap object

If you continue to have problems, please tag me and I will be happy to help.

1개의 좋아요

감사합니다 확인해 보겠습니다

1개의 좋아요

If the problem persists, please send me the source codes you used for the map. This will help me understand better and we can solve the problem faster.

You can come to open chat for quick communication KakaoTalk Open Chat