728x90
https://choi-hee-yeon.tistory.com/172
위의 글을 통해 다음의 우편번호 API 서비스를 이용해봤습니다.
https://choi-hee-yeon.tistory.com/173
위의 글을 통해 카카오맵 API를 사용하여 맵을 불러오는 것을 알아봤습니다.
그렇다면, 원하는 위치에 마커(marker)을 찍는건 어떨까요?
그것도 카카오맵 API 를 사용하여 개발할 수 있습니다.
1. 생성한 지도에서 geocoder.addressSearch()를 통해 주소로 좌표를 검색하기
initMap() {
if(this.isScriptLoaded){
window.kakao.maps.load(() => {
// eslint-disable-next-line no-undef
kakao.maps.load(() => {
console.log(`
initMap
`)
let mapContainer = document.getElementById('map'), // 지도를 표시할 div
mapOption = {
// eslint-disable-next-line no-undef
center: new kakao.maps.LatLng(33.450701, 126.570667), // 지도의 중심좌표
level: 3 // 지도의 확대 레벨
};
// eslint-disable-next-line no-undef
let map = new kakao.maps.Map(mapContainer, mapOption); // 지도를 생성합니다
console.log(map)
// // 주소-좌표 변환 객체를 생성합니다
// eslint-disable-next-line no-undef
const geocoder = new kakao.maps.services.Geocoder();
console.log(`${this.roadAddress} ${this.detailAddress}`);
// 주소로 좌표를 검색합니다
geocoder.addressSearch(`${this.roadAddress} ${this.detailAddress}`, function(result, status) {
// 정상적으로 검색이 완료됐으면
// eslint-disable-next-line no-undef
if (status === kakao.maps.services.Status.OK) {
// eslint-disable-next-line no-undef
const coords = new kakao.maps.LatLng(result[0].y, result[0].x);
// 결과값으로 받은 위치를 마커로 표시합니다
// eslint-disable-next-line no-undef
const marker = new kakao.maps.Marker({
map: map,
position: coords
});
// 지도의 중심을 결과값으로 받은 위치로 이동시킵니다
map.setCenter(coords);
console.log(marker);
}
});
})
})
}
},
- 앞서 initMap() 메서드를 통해 map을 만들었었는데, 해당 메서드에서 geocoder.addressSearch()를 통해 주소로 좌표를 검색합니다.
2. 검색이 완료된 위치를 마커로 표시하기
// eslint-disable-next-line no-undef
const coords = new kakao.maps.LatLng(result[0].y, result[0].x);
// 결과값으로 받은 위치를 마커로 표시합니다
// eslint-disable-next-line no-undef
const marker = new kakao.maps.Marker({
map: map,
position: coords
});
// 지도의 중심을 결과값으로 받은 위치로 이동시킵니다
map.setCenter(coords);
console.log(marker);
- // eslint-disable-next-line no-undef 는 api를 불러오기전, maps가 없다는 eslint 오류를 처리하기 위해 해당 코드의 바로 위에 작성해준 것입니다.
3. 결과
728x90