moonStory
카카오 장소 검색 API 사용하기 (React) 본문
반응형
네이버 맵을 사용하려다가 네이버는 이제 장소 검색 API를 제공하지 않아서 카카오 맵으로 변경했다.
카카오 API를 사용하기 위해서는 먼저 kakao Devalopers에서 앱 키를 발급받아야 한다. 앱 키 발급 방법은 아래 링크에 정리해 두었다.
카카오 디벨로퍼(kakao developer) API key 발급받기
https://developers.kakao.com/ Kakao Developers 카카오 API를 활용하여 다양한 어플리케이션을 개발해보세요. 카카오 로그인, 메시지 보내기, 친구 API, 인공지능 API 등을 제공합니다. developers.kakao.com 카카오 d
ans3094.tistory.com
장소 검색 API를 사용하려면 우리가 사용할 앱 키는 REST API 키다.
const RestaurantInput: React.FC = () => {
const KAKAO_API_KEY = '{발급받은 REST API}'; // 발급받은 REST API 키로 변경
const [query, setQuery] = useState('');
const [places, setPlaces] = useState([]);
const [currentLocation, setCurrentLocation] = useState({ latitude: 0, longitude: 0 });
useEffect(() => {
if ('geolocation' in navigator) {
navigator.geolocation.getCurrentPosition(position => {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
setCurrentLocation({ latitude, longitude });
});
}
}, []);
const searchPlaces = () => {
if (!currentLocation.latitude || !currentLocation.longitude) {
alert('현재 위치를 가져오지 못했습니다.');
return;
}
const { latitude, longitude } = currentLocation;
// 현재 위치를 기반으로 2km 이내의 장소 검색
const apiUrl = `/v2/local/search/keyword.json?query=${query}&y=${latitude}&x=${longitude}&radius=2000`;
console.log('apiUrl', apiUrl);
fetch(apiUrl, {
headers: {
Authorization: `KakaoAK ${KAKAO_API_KEY}`,
},
})
.then(response => response.json())
.then(data => {
setPlaces(data.documents);
})
.catch(error => {
console.error('Error searching places:', error);
});
};
return (
<div>
<input type="text" placeholder="장소 검색" value={query} onChange={e => setQuery(e.target.value)} />
<button onClick={searchPlaces}>검색</button>
<div>
{places.map((place: any) => (
<div key={place.place_name}>{place.place_name}</div>
))}
</div>
</div>
);
};
export default RestaurantInput;
내 위치의 lat, lng 값을 받아와 radius를 사용하여 내 위치를 기반으로 검색 반경 거리를 제한할수도 있다.
참고
https://developers.kakao.com/docs/latest/ko/local/dev-guide#search-by-keyword
Kakao Developers
카카오 API를 활용하여 다양한 어플리케이션을 개발해보세요. 카카오 로그인, 메시지 보내기, 친구 API, 인공지능 API 등을 제공합니다.
developers.kakao.com
반응형
'REST API' 카테고리의 다른 글
카카오 디벨로퍼(kakao developer) API key 발급받기 (0) | 2023.09.07 |
---|