API (Application Programing Interface)
JavaScript | 네이버 지도 연동하기, NAVER MAP API
Valar
2021. 5. 21. 11:37
반응형
▶ 네이버 지도 연동하기, NAVER MAP API
1. 네이버 클라우드(https://console.ncloud.com) 가입 → AI NAVER API → Application 등록
*해당 영역이 안 보일 경우 이용 신청을 한 뒤에 진행한다.
https://www.ncloud.com/product/applicationService/maps
2. 약관 동의 후 확인
3. 사용할 Maps API 체크 후 사용될 URL을 추가 후 저장한다.
4. Application 생성 완료 후 인증정보 팝업에서 Client ID 확인이 가능하다.
5. Application이 생성되었으니, 가이드대로 자바스크립트 코드를 작성한다.
HTML DIV (id="map")
<div id="map" style="width:100%;height:500px;"></div>
script (ncpClientId=Client ID)
발급받은 Client ID를 입력한다.
<script type="text/javascript" src="https://openapi.map.naver.com/openapi/v3/maps.js?ncpClientId=클라이언트ID&submodules=geocoder"></script>
JAVASCRIPT (현재 위치, 서울시청 위치, 내 위치로 이동 이미지 필요)
<script type="text/javascript">
// 현재 위치로 이동 이미지
var curtBtn = '<img src="/common/img/curt-loca-icon.png" alt="현재위치로 이동">';
// 현재 위치 위도, 경도 좌표 객체를 담을 변수
var curtLoca = "";
// 서울 시청 위/경도 좌표 객체
var sCityHallLoca = new naver.maps.LatLng(37.5666805, 126.9784147);
// Map 초기화
var map = new naver.maps.Map('map', {
center: sCityHallLoca, // X, Y 값 설정
scaleControl: false, // 우측 하단 scale 표시
mapDataControl: false, // 좌측 하단 @ NAVER Corp 표시
zoom: 17 // 지도 줌 레벨
});
// 서울 시청 마커 설정
var marker = new naver.maps.Marker({
position: sCityHallLoca,
map: map,
icon: { url: "/common/img/marker-target.png" }
});
// 마커 클릭 이벤트 핸들러 함수
var makerClickHandler = function() {
return function(e) { alert("Marker Seoul City Hall"); }
}
// 마커 클릭 이벤트 리스너 추가
naver.maps.Event.addListener(marker, 'click', makerClickHandler());
// Map 사용자 정의 컨트롤 이벤트 추가 (현재위치로 이동 버튼을 추가)
naver.maps.Event.once(map, 'init_stylemap', function() {
/*
현재 위치로 이동 img tag 변수를 CustomControl에 설정
표시될 위치는 맵의 우측 상단
*/
var cstmCtrl = new naver.maps.CustomControl(curtBtn, {
position: naver.maps.Position.RIGHT_TOP
});
// CustomControl를 Map에 설정
cstmCtrl.setMap(map);
// 클릭 이벤트 리스너 설정
naver.maps.Event.addDOMListener(cstmCtrl.getElement(), 'click', function() {
if (curtLoca) {
// 얻은 좌표를 지도의 중심으로 설정
map.setCenter(curtLoca);
// 지도의 줌 레벨을 변경
map.setZoom(17);
}
else {
alert("위치 액세스가 거부되었습니다.\n사용하시려면 위치 액세스를 허용해주세요.");
}
});
});
// getCurrentPosition 성공 콜백 함수
var onSuccessGeolocation = function (position) {
// 현재위치
curtLoca = new naver.maps.LatLng(position.coords.latitude, position.coords.longitude);
// 얻은 좌표를 지도의 중심으로 설정합니다.
map.setCenter(curtLoca);
// 지도의 줌 레벨을 변경합니다.
map.setZoom(17);
// 현재 위치에 마커 표시
new naver.maps.Marker({
position: curtLoca,
map: map,
icon: { url: "/common/img/marker-current.png" }
});
}
// getCurrentPosition 에러 콜백 함수
var onErrorGeolocation = function () {
var agent = navigator.userAgent.toLowerCase(), name = navigator.appName;
if (name === 'Microsoft Internet Explorer' || agent.indexOf('trident') > -1 || agent.indexOf('edge/') > -1) {
alert("지원하지 않는 브라우져입니다.");
}
else {
console.log("현재 위치를 가져오는데 에러가 발생하였습니다.");
}
}
// Geolocation HTML5 API를 통해 얻은 현재 위치 좌표로 지도를 이동합니다.
if (navigator.geolocation) {
/**
* navigator.geolocation 은 Chrome 50 버젼 이후로 HTTP 환경에서 사용이 Deprecate 되어 HTTPS 환경에서만 사용 가능 합니다.
* http://localhost 에서는 사용이 가능하며, 테스트 목적으로, Chrome 의 바로가기를 만들어서 아래와 같이 설정하면 접속은 가능합니다.
* chrome.exe --unsafely-treat-insecure-origin-as-secure="http://example.com"
*/
navigator.geolocation.getCurrentPosition(onSuccessGeolocation, onErrorGeolocation);
}
else {
console.log("Geolocation Not supported Required");
}
</script>
주소로 위/경도 조회 (위의 기능과는 무관 하나 필요시 사용을 위해)
// 주소 => 위/경도 조회
var searchAddressToCoordinate = function (address) {
naver.maps.Service.geocode({ query: address },
function(status, response) {
if (status === naver.maps.Service.Status.ERROR) {
if (!address) {
return alert('Geocode Error, Please check address');
}
return alert('Geocode Error, address:' + address);
}
if (response.v2.meta.totalCount === 0) {
return alert('Geocode No result.');
}
var item = response.v2.addresses[0];
var lat = item.y;
var lng = item.x;
console.log(item);
});
}
6. 네이버 지도 API 결과
네이버 클라우드
https://console.ncloud.com
네이버 MAP API V3
https://navermaps.github.io/maps.js.ncp/docs/tutorial-digest.example.html
반응형