지도가 뜨질 않습니다

아래 코드에서 94번째줄에서 map이 생성자가 아니라고 뜨고, 주석처리하면
97번째줄에서 똑같은 증상이 일어나고, 또 주석처리하면
100번째줄에서 똑같은 증상이 일어납니다.

그니깐 카카오 API에서 뭔가 받아오는 걸 아예 못하는 것 같습니다.

autoload=false도 설정해줬고,
사이트 도메인도 잘 설정해줬고,
구글링해서 할 수 있는 건 다해본 것 같습니다. (useEffect 등등)

제발 해결해주세요.

<template>
  <div class="divPadding">
    <div class="form-container">
      <h2>다이어리 등록</h2>
      <form @submit.prevent="submitForm">
        <div class="form-group">
          <label for="title">제목</label>
          <input type="text" id="title" v-model="postDiary.title" required />
        </div>

        <div class="form-group">
          <label for="content">내용</label>
          <input type="text" id="content" v-model="postDiary.content" required style="width: 100%;" />
        </div>

        <div>
          <!-- Include the Kakao Maps HTML code here -->
          <div id="map" style="width: 40vw; height: 40vh;"></div>
          <div id="clickLatlng">지도에서 위치를 클릭해서 오늘의 장소를 등록해보세요!</div>
          <input id="keywordInput" type="text" placeholder="검색 할 위치">
          <button @click="searchByKeyword">검색</button>
        </div>

        <button type="button" class="btn btn-primary" @click="registDiary">
          등록
        </button>
      </form>
    </div>
  </div>
</template>

<script setup>
import { useDiaryStore } from "@/stores/diaryStore";
import { ref, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";

const route = useRoute();
const router = useRouter();
const diaryStore = useDiaryStore();

const postDiary = ref({
  userId: null,
  title: null,
  content: null,
  diaryDate: null,
  diaryPicture: null,
  location: null,
});

onMounted(() => {
  const script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = '//dapi.kakao.com/v2/maps/sdk.js?appkey={제 Javascript KEY 몇번이고 확인하고 복붙해서 넣었습니다.}&libraries=services,clusterer,drawing&autoload=false';

  script.addEventListener('load', initKakaoMap);
  script.addEventListener('error', handleScriptError);

  document.head.appendChild(script);
});

function initKakaoMap() {
  function dateFormat(date) {
    let month = date.getMonth() + 1;
    let day = date.getDate();
    let hour = date.getHours();
    let minute = date.getMinutes();
    let second = date.getSeconds();

    month = month >= 10 ? month : '0' + month;
    day = day >= 10 ? day : '0' + day;
    hour = hour >= 10 ? hour : '0' + hour;
    minute = minute >= 10 ? minute : '0' + minute;
    second = second >= 10 ? second : '0' + second;

    return date.getFullYear() + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
  }

  function successCallback({ coords, timestamp }) {
    latitude = coords.latitude;
    longitude = coords.longitude;
    alert(`위도: ${latitude},\n경도: ${longitude},\n\n현재 시간: ${dateFormat(new Date(timestamp))}`);
  }

  const errorCallback = (error) => {
    console.log(error);
  }

  const position = navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
  let latitude;
  let longitude;

  var container = document.getElementById('map');
  var options = {
    // center: new kakao.maps.LatLng(36.35512, 127.2983),
    level: 5
  };
  // var map = new kakao.maps.Map(container, options);

  var markerImageSrc = "https://t1.daumcdn.net/localimg/localimages/07/mapapidoc/markerStar.png";
  // var markerImageSize = new kakao.maps.Size(22, 35);
  var markerImage = new kakao.maps.MarkerImage(markerImageSrc, markerImageSize);

  var marker = new kakao.maps.Marker({
    position: map.getCenter(),
    image: markerImage
  });
  marker.setMap(map);

  kakao.maps.event.addListener(map, 'click', function (mouseEvent) {
    var latlng = mouseEvent.latLng;
    marker.setPosition(latlng);
    var message = '클릭한 위치의 위도는 ' + latlng.getLat() + ' 이고, ';
    message += '경도는 ' + latlng.getLng() + ' 입니다';
    var resultDiv = document.getElementById('clickLatlng');
    resultDiv.innerHTML = message;
  });

  var iwContent = '<div style="padding:15px;">제목</div>';
  var iwContentOnlyDate = '<div style="padding:15px;">다이어리 날짜</div>';
  var iwPosition = map.getCenter();
  var iwRemoveable = true;

  var infowindow = new kakao.maps.InfoWindow({
    map: map,
    position: iwPosition,
    content: iwContent,
    removable: iwRemoveable
  });

  var infowindowOnlyDate = new kakao.maps.InfoWindow({
    map: map,
    position: iwPosition,
    content: iwContentOnlyDate,
    removable: iwRemoveable,
  });

  infowindow.open(map, marker);

  kakao.maps.event.addListener(marker, 'click', function () {
    infowindow.open(map, marker);
  });

  kakao.maps.event.addListener(marker, 'mouseover', function () {
    infowindowOnlyDate.open(map, marker);
  });

  kakao.maps.event.addListener(marker, 'mouseout', function () {
    infowindowOnlyDate.close();
  });

  var ps = new kakao.maps.services.Places();
  var markers = [];

  function removeMarker() {
    for (var i = 0; i < markers.length; i++) {
      markers[i].setMap(null);
    }
    markers = [];
  }

  function placesSearchCB(data, status, pagination) {
    if (status === kakao.maps.services.Status.OK) {
      var bounds = new kakao.maps.LatLngBounds();
      removeMarker();

      for (var i = 0; i < data.length; i++) {
        displayMarker(data[i]);
        bounds.extend(new kakao.maps.LatLng(data[i].y, data[i].x));
      }

      map.setBounds(bounds);
    } else if (status === kakao.maps.services.Status.ZERO_RESULT) {
      alert('검색 결과가 존재하지 않습니다.');
      return;
    } else if (status === kakao.maps.services.Status.ERROR) {
      alert('검색 결과 중 오류가 발생했습니다.');
      return;
    }
  }

  function displayMarker(place) {
    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.setContent('<div style="padding:5px;font-size:12px;">' + place.place_name + '</div>');
      infowindow.open(map, marker);
    });

    markers.push(marker);
  }

  function searchByKeyword() {
    const keyword = document.getElementById('keywordInput').value;
    console.log(keyword + '로 검색한 결과');
    ps.keywordSearch(keyword, placesSearchCB);
  }
}

function handleScriptError(event) {
  console.error('Error loading Kakao Maps script:', event);
}

const registDiary = function () {
  postDiary.value.userId = route.params.user_id;
  postDiary.value.diaryDate = route.params.diary_date;
  console.log(postDiary.value.userId);
  console.log(postDiary.value.diaryDate);
  diaryStore.registDiary(postDiary.value);
  alert("일기가 작성되었습니다");
  console.log("등록되었습니다.");
  router.push({
    name: "Diary",
    params: { diary: JSON.stringify(postDiary.value) },
  });
};
</script>

<style scoped>
.divPadding {
  padding-top: 3.3vw;
}

.form-container {
  display: flex;
  flex-direction: column;
  max-width: 400px;
  margin: 0 auto;
}

.form-group {
  margin-bottom: 1.5rem;
}

label {
  display: block;
  margin-bottom: 0.5rem;
}

input {
  width: 100%;
  padding: 0.5rem;
  box-sizing: border-box;
  border: 1px solid #ccc;
  border-radius: 4px;
  outline: none;
}

.btn {
  padding: 0.75rem 1rem;
  background-color: #aad1f1;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.btn:hover {
  background-color: #fbff0c;
}
</style>

@yonggari0821

앱 등록정보 내 허용 사이트 도메인을 다시 확인해주세요.
localhost 와 127.0.0.1 은 다른 것으로 인식됩니다.

localhost로 했고 허용사이트 도메인에 localhost로 해뒀습니다.

@yonggari0821

실제 호출이 되는 레퍼러가 localhost 로 들어오지 않고 있어 안내드린 부분입니다.

  • localhost 또는 IP
  • http 또는 https
  • 호출 페이지의 port 값을 명시적으로 붙이는 경우

모두 다르게 취급됩니다.

localhost
IP 확인 후 해당 IP
각 방법들에 모두 2가지 http와 https 적용
url에 port 번호를 아예 명시해서

모두 해봤는데 안됩니다.

@yonggari0821

http://127.0.0.1:포트번호

추가로 등록해보세요.

그래도 안되네요…혹시 몰라서 https도 해봤습니다.

아니면 Vue 파일이라서 안 될수도 있나요?

스크립트를 동적 로드(autoload=false)할 경우 kakao.maps.load 콜백 함수 안에서 kakao.maps.* 객체 접근할 수 있습니다.
스크립트 로드 전에 kakao.maps.* 객체에 접근하려고 해서 오류가 생긴 것 같은데요.
load 콜백 함수에 지도를 생성해서 확인 부탁드립니다.

function initKakaoMap() {
    kakao.maps.load(() => {
        // 콜백함수 안에서 지도와 마커를 생성해주세요.
    });
}

https://apis.map.kakao.com/web/documentation/#load_load

감사합니다…이미 해결하긴 했는데
이런식으로 하니까 또 결국에는 콜백함수 내에서 함수를 선언해야되는데 그럼 활용할 수가 없네요…
예를 들면 vue파일에서 v-model로 연결된 값을 가지고 지도에서 키워드로 검색을 하고 싶은데 그러려면 검색하는 함수 등이
initKakaoMap밖에 있어야 하는데 그럼 또 kakao객체를 찾을 수 없다하네요…