본문 바로가기
웹 개발

[네이버 지도 api (4)] 주소를 검색해서 지도 이동하기 Geocoding 좌표변환

by 배추잠자리 2022. 4. 27.
반응형

 

[네이버 지도 api (1)] 지도 생성 후 마커 이미지 넣기 - 스프링 + 자바스크립트 (tistory.com)

[네이버 지도 api (2)] 마커 클릭시 정보창 띄우기 - 스프링 + 자바스크립트 (tistory.com)

[네이버 지도 api (3)] 다중마커, 다중 정보창 - 스프링 + 자바스크립트 (tistory.com)

 

 

주소를 검색해서 지도를 이동하는 소스코드 입니다.

글의 하단부에는 복사할 수 있는 전체 소스코드가 있습니다.

 

■ 네이버지도 API 설정하기

Geocoding 설정

허용 URL은  http://localhost:8000 으로 추가해서 저장해준다.

 

 

■ 신청된 API 인증정보 확인

 

Client ID를 이용할거니깐 확인해두기 !

 

 

■ <head> 작성   제이쿼리, 네이버api 등록

위의 사진에서 빨간 부분으로 작성된 클라이언트 ID 부분에 인증정보를 등록해줍니다.

 

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
    <script type="text/javascript" src="https://openapi.map.naver.com/openapi/v3/maps.js?ncpClientId=클라이언트아이디&submodules=geocoder"></script>
	<script  src="http://code.jquery.com/jquery-latest.min.js"></script>
	<script type="text/javascript" src="http://code.jquery.com/jquery-2.2.4.min.js"></script>
</head>

 

 

 

■ <body> 작성   지도 표출 및 좌표를 보여주는 페이지 작성

 

<body>
<div class="search">
	<input id="address" type="text" placeholder="검색할 주소">
	<input id="submit" type="button" value="주소검색">
</div>
<div id="map" style="width:1000px;height:500px;"></div>

<div>
<table>
    <thead>
        <tr>
            <th>주소</th>
            <th>위도</th>
            <th>경도</th>
        </tr>	
    </thead>
    <tbody id="mapList"></tbody>
</table>
</div>
</body>

 

검색기능을 구현하고,

검색한 주소로 지도가 이동되며 마커를 찍어주고,

하단의 테이블에는 주소, 위도, 경도를 작성해줄겁니다.

 

 

 

■ <script>부분 작성

 

 # 지도를 그려주는 부분

function selectMapList() {
	
	var map = new naver.maps.Map('map', {
	    center: new naver.maps.LatLng(37.3595704, 127.105399),
	    zoom: 10
	});
}

 

 

 # 지도를 움직이게 해주는 함수

function moveMap(len, lat) {
	var mapOptions = {
		    center: new naver.maps.LatLng(len, lat),
		    zoom: 15,
		    mapTypeControl: true
		};
		var map = new naver.maps.Map('map', mapOptions);
		var marker = new naver.maps.Marker({
		    position: new naver.maps.LatLng(len, lat),
		    map: map
		});
}

 

 

 

# 주소를 검색하는 부분 ( 클릭이벤트 )

    $('#address').on('keydown', function(e) {
        var keyCode = e.which;
        if (keyCode === 13) { // Enter Key
            searchAddressToCoordinate($('#address').val());
        }
    });
    $('#submit').on('click', function(e) {
        e.preventDefault();
        searchAddressToCoordinate($('#address').val());
    });
    naver.maps.Event.once(map, 'init_stylemap', initGeocoder);

 

 

# 주소를 검색하는 부분 ( 실질적인 로직 )

function searchAddressToCoordinate(address) {
    naver.maps.Service.geocode({
        query: address
    }, function(status, response) {
        if (status === naver.maps.Service.Status.ERROR) {
            return alert('Something Wrong!');
        }
        if (response.v2.meta.totalCount === 0) {
            return alert('올바른 주소를 입력해주세요.');
        }
        var htmlAddresses = [],
            item = response.v2.addresses[0],
            point = new naver.maps.Point(item.x, item.y);
        if (item.roadAddress) {
            htmlAddresses.push('[도로명 주소] ' + item.roadAddress);
        }
        if (item.jibunAddress) {
            htmlAddresses.push('[지번 주소] ' + item.jibunAddress);
        }
        if (item.englishAddress) {
            htmlAddresses.push('[영문명 주소] ' + item.englishAddress);
        }

        insertAddress(item.roadAddress, item.x, item.y);
        
    });
}

 

 

# 입력된 주소의 정보를 테이블로 작성해주는 부분

function insertAddress(address, latitude, longitude) {
	var mapList = "";
	mapList += "<tr>"
	mapList += "	<td>" + address + "</td>"
	mapList += "	<td>" + latitude + "</td>"
	mapList += "	<td>" + longitude + "</td>"
	mapList += "</tr>"

	$('#mapList').append(mapList);	

	var map = new naver.maps.Map('map', {
	    center: new naver.maps.LatLng(longitude, latitude),
	    zoom: 14
	});
    var marker = new naver.maps.Marker({
        map: map,
        position: new naver.maps.LatLng(longitude, latitude),
    });
}

 

 

# 페이지 로드와 동시에 지도를 그려주는 함수를 실행한다.

 

selectMapList();

 

 

 

■ 최종 소스코드

 

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
    <script type="text/javascript" src="https://openapi.map.naver.com/openapi/v3/maps.js?ncpClientId=ncpClientId&submodules=geocoder"></script>
	<script  src="http://code.jquery.com/jquery-latest.min.js"></script>
	<script type="text/javascript" src="http://code.jquery.com/jquery-2.2.4.min.js"></script>
</head>

<body>
<div class="search">
	<input id="address" type="text" placeholder="검색할 주소">
	<input id="submit" type="button" value="주소검색">
</div>
<div id="map" style="width:1000px;height:500px;"></div>
<div>
	<table>
		<thead>
			<tr>
				<th>주소</th>
				<th>위도</th>
				<th>경도</th>
			</tr>	
		</thead>
		<tbody id="mapList"></tbody>
	</table>
</div>
</body>
<script>
//지도를 그려주는 함수 실행
selectMapList();

//검색한 주소의 정보를 insertAddress 함수로 넘겨준다.
function searchAddressToCoordinate(address) {
    naver.maps.Service.geocode({
        query: address
    }, function(status, response) {
        if (status === naver.maps.Service.Status.ERROR) {
            return alert('Something Wrong!');
        }
        if (response.v2.meta.totalCount === 0) {
            return alert('올바른 주소를 입력해주세요.');
        }
        var htmlAddresses = [],
            item = response.v2.addresses[0],
            point = new naver.maps.Point(item.x, item.y);
        if (item.roadAddress) {
            htmlAddresses.push('[도로명 주소] ' + item.roadAddress);
        }
        if (item.jibunAddress) {
            htmlAddresses.push('[지번 주소] ' + item.jibunAddress);
        }
        if (item.englishAddress) {
            htmlAddresses.push('[영문명 주소] ' + item.englishAddress);
        }

        insertAddress(item.roadAddress, item.x, item.y);
        
    });
}

// 주소 검색의 이벤트
$('#address').on('keydown', function(e) {
    var keyCode = e.which;
    if (keyCode === 13) { // Enter Key
        searchAddressToCoordinate($('#address').val());
    }
});
$('#submit').on('click', function(e) {
    e.preventDefault();
    searchAddressToCoordinate($('#address').val());
});
naver.maps.Event.once(map, 'init_stylemap', initGeocoder);


    
//검색정보를 테이블로 작성해주고, 지도에 마커를 찍어준다.
function insertAddress(address, latitude, longitude) {
	var mapList = "";
	mapList += "<tr>"
	mapList += "	<td>" + address + "</td>"
	mapList += "	<td>" + latitude + "</td>"
	mapList += "	<td>" + longitude + "</td>"
	mapList += "</tr>"

	$('#mapList').append(mapList);	

	var map = new naver.maps.Map('map', {
	    center: new naver.maps.LatLng(longitude, latitude),
	    zoom: 14
	});
    var marker = new naver.maps.Marker({
        map: map,
        position: new naver.maps.LatLng(longitude, latitude),
    });
}

//지도를 그려주는 함수
function selectMapList() {
	
	var map = new naver.maps.Map('map', {
	    center: new naver.maps.LatLng(37.3595704, 127.105399),
	    zoom: 10
	});
}


// 지도를 이동하게 해주는 함수
function moveMap(len, lat) {
	var mapOptions = {
		    center: new naver.maps.LatLng(len, lat),
		    zoom: 15,
		    mapTypeControl: true
		};
    var map = new naver.maps.Map('map', mapOptions);
    var marker = new naver.maps.Marker({
        position: new naver.maps.LatLng(len, lat),
        map: map
    });
}
</script>
</html>

 

 

■ 최종 결과

 

 

검색 시 테이블에 작성이되고, 지도에 마커가 찍힙니다.

또한 알수 없는 주소일 경우 alert창을 확인할 수 있습니다 !

 

 

이해가 안되는 부분은 댓글 남겨주세요 ~~

 

 

[KeyWord]

네이버 지도 생성, 네이버 지도 api 연동, 네이버 지도 api, 네이버 지도 마커, 네이버 지도 api 마커, 네이버 지도 api 마커 이미지

네이버 지도 중복마커, 네이버 지도 주소검색, 네이버 지도 api geocoding, 네이버 지도 api 좌표 변환, 네이버 지도 정보창,

네이버 지도 api 다중 정보창, 네이버 지도 api infowindows, 네이버 지도 api 주소 검색

반응형

댓글