Kakao is also using the API. Now I keep getting an error saying that onSelectLocation is not a function, but I really don't know. Pass the onSelectLocation function from the parent component to the map component. The map component renders addresses and coordinates.
I don't understand why onSelectLocation is not a function. I asked gpt as well, but I couldn't find the answer I wanted. Even when outputting through console.log, I confirmed that props were delivered properly, not unfind.
Error Text
ERROR onSelectLocation is not a function TypeError: onSelectLocation is not a function at http://localhost:3000/static/js/bundle.js:2926:11 at http://t1.daumcdn.net/mapjsapi/js/libs/services/1.0.2/services.js:6:1700 at Object.oncomplete (http://t1.daumcdn.net/mapjsapi/js/libs/services/1.0.2/services.js:6:194)
/* eslint-disable no-unused-vars */
/* global kakao */
import { useEffect, useState } from 'react';
import PropTypes from 'prop-types'; // prop-types 라이브러리를 import
// import InviteWritePage from '../pages/InviteWritePage';
const { kakao } = window;
function MapKakao({ onSelectLocation }) {
const [map, setMap] = useState(null);
useEffect(() => {
// 카카오 지도 초기화
const container = document.getElementById('map');
const options = { center: new kakao.maps.LatLng(33.450701, 126.570667) };
const map = new kakao.maps.Map(container, options);
setMap(map);
// 장소 검색 객체 생성
const geocoder = new kakao.maps.services.Geocoder();
// 검색 버튼 클릭 이벤트 핸들러
const searchButton = document.getElementById('search-button');
searchButton.addEventListener('click', () => {
// 입력된 주소 가져오기
const input = document.getElementById('address-input');
const address = input.value;
// 주소를 검색하여 좌표를 얻어옴
geocoder.addressSearch(address, (result, status) => {
if (status === window.kakao.maps.services.Status.OK) {
const latlng = new window.kakao.maps.LatLng(result[0].y, result[0].x);
// 이전 마커가 있으면 제거
if (map.marker) {
map.marker.setMap(null);
}
// 새로운 마커 추가 및 지도 중심 이동
const newMarker = new window.kakao.maps.Marker({
position: latlng,
});
newMarker.setMap(map);
map.panTo(latlng);
// 위도, 경도, 주소 정보를 상위 컴포넌트로 전달
onSelectLocation(latlng.getLat(), latlng.getLng(), address);
} else {
alert('주소를 찾을 수 없습니다.');
}
});
});
}, [onSelectLocation]);
return (
<div>
<input
type="text"
id="address-input"
placeholder="주소를 입력하세요"
style={{ marginRight: '10px' }}
/>
<button id="search-button">검색</button>
<div id="map" style={{ height: '307px' }}></div>
</div>
);
}
MapKakao.propTypes = {
onSelectLocation: PropTypes.func.isRequired, // onSelectLocation 프로퍼티를 정의하고 함수 형태로 검사합니다.
};
export default MapKakao;
import { useState } from 'react';
import axios from 'axios';
import MapKakao from '../services/MapKakao';
function InviteWritePage() {
const [selectedLocation, setSelectedLocation] = useState({
latitude: 0, // 초기값 설정
longitude: 0, // 초기값 설정
address: '', // 초기값 설정
});
// 사용자입력값 상태변수
const [formData, setFormData] = useState({
title: '',
date: '',
body: '',
category: '',
totalNum: 0,
money: 0,
latitude: '',
longitude: '',
address: '',
});
const handleSubmit = (event) => {
event.preventDefault();
// 서버로 보낼 데이터 생성
// const requestData = {
// title: formData.title,
// date: formData.date,
// body: formData.body,
// category: formData.category,
// totalNum: formData.totalNum,
// money: formData.money,
// latitude: formData.latitude,
// longitude: formData.longitude,
// address: formData.address,
// };
const token =
// 서버로 POST 요청 보내기
axios
.post('http://3.39.76.109:8080/boards/new-boards', formData, {
headers: {
Authorization: token,
},
})
.then((response) => {
// 성공적으로 생성되었을 때 처리할 로직
console.log('Card created successfully:/', response.data);
})
.catch((error) => {
console.error('Error creating card:', error);
});
};
const handleInputChange = (event) => {
const { name, value } = event.target;
setFormData((prevData) => ({
...prevData,
[name]: value,
}));
};
// 사용자가 지도에서 선택한 장소 정보를 업데이트하는 함수
const handleLocationSelect = (latitude, longitude, address) => {
// console.log(latitude, longitude, address);
setSelectedLocation({
latitude,
longitude,
address,
});
};
// console.log(handleLocationSelect);
return (
<div>
<h2>Create a New Card</h2>
<form onSubmit={handleSubmit}>
<label>
Title:
<input
type="text"
name="title"
value={formData.title}
onChange={handleInputChange}
/>
</label>
<label>
Date:
<input
type="date"
name="date"
value={formData.date}
onChange={handleInputChange}
/>
</label>
<label>
Body:
<textarea
name="body"
value={formData.body}
onChange={handleInputChange}
/>
</label>
<label>
Category:
<input
type="text"
name="category"
value={formData.category}
onChange={handleInputChange}
/>
</label>
<label>
Person:
<input
type="number"
name="totalNum"
value={formData.totalNum}
onChange={handleInputChange}
/>
</label>
<label>
Money:
<input
type="number"
name="money"
value={formData.money}
onChange={handleInputChange}
/>
</label>
{/* <label>
address:
<input
type="text"
name="address"
// value={formData.address}
onChange={handleInputChange}
/>
</label> */}
</form>
<MapKakao onSelectLocation={handleLocationSelect} />
<p>선택한 주소: {selectedLocation.address}</p>
<p>위도: {selectedLocation.latitude}</p>
<p>경도: {selectedLocation.longitude}</p>
<button type="submit">Create Card</button>
</div>
);
}
export default InviteWritePage;