본문 바로가기
멀티캠퍼스 풀스택 과정/프론트엔드

프론트엔드4-5. google map api 사용-2(geocoding)

by 이쟝 2022. 2. 15.
지오코딩(geocoding)  역지오코딩(Reverse geocoding)
- 사람이 읽을 수 있는 주소를
지리적 좌표(경도, 위도)로 변환하는 것
- 지리적 좌표(경도, 위도)를
사람이 읽을 수 있는 주소로 변환하는 것

1. HTML 파일

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>google map</title>
    <style>
        #gmap{
            width:100%; 
            height:700px;
            outline:1px solid gray;
            }
    </style>
    <script async defer src="https://maps.googleapis.com/maps/api/js?key=키값입력&callback=initMap&region=kr">
    </script>
</head>
<body>
    <div id="gmap"></div>
    <script src = "googleMap1.js"></script>
</body>
</html>

2.  JS파일(googleMap1.js)

1. 지도의 표시 초기값을 넣을 함수 생성

let latitude;   // 위도
let longitude;  // 경도
  
let addr;       // 찾으려는 곳의 이름
let homePage;   // 찾으려는 곳의 웹사이트
let popImg;     // 찾으려는 곳의 이미지

function mapInitial() {
	// 초기값 넣기
	latitude = 37.5729503;
	longitude = 126.9793578;

	addr = ['서울 선유도', '서울 뚝섬', '서울 시청', '서울 잠실종합운동장']; // 주소
	homePage = ["http://parks.seoul.go.kr/", "https://www.naver.com", "https://www.seoul.go.kr", "https://stadium.seoul.go.kr/reserve/jamsil"];
	popImg = ['img1.jpg', 'img2.jpg', 'img3.jpg', 'img4.jpg'];
}

2. initMap 함수 생성

function initMap() {
		
		mapInitial();
		
        // 지도의 기본 데이터
		let mapProperties = {
			center : new google.maps.LatLng(latitude, longitude), // 기준위치
			zoom : 12,                                            // 줌의 정도
			mapTypeId : google.maps.MapTypeId.ROADMAP             // 맵의 유형
		}
		
        // 구글 맵 객체 생성
		map = new google.maps.Map(document.getElementById("gmap"),mapProperties);
		
        // 지오코더 객체 생성
		geoCoder = new google.maps.Geocoder();
			
		for(var i=0; i<addr.length; i++) {
			// 			    지명,     홈페이지 주소,   해당 이미지
			setMapPosition(addr[i], homePage[i], popImg[i]);
		}
			
} // initMap()
더보기
더보기
  • Geocoder( ) : 지명과 건물들의 명칭을 이용해 지도의 위도 경도를 구할 수 있다. 

3. setMapPosition 함수 생성(임의로 생성)

  • 기본 주소를 세팅
  • 지오코딩 서비스에 콜백 메서드가 있어야 지오코더 결과 검색 시 실행된다. 
// setMapPosition 함수
function setMapPosition(addr2, home2, img2) {
			//   마커를 표시할 주소(addr2), 주소의 정보, 처리 결과("OK"-> 주소존재)
	geoCoder.geocode({ 'address': addr2 }, function(results, status) {
		if (status == 'OK') { // 주소가 존재할 때
			console.log(results);

			// 지도의 가운데 위치를 새로 셋팅
			map.setCenter(results[0].geometry.location);
			// map.setCenter(results[0]['geometry']['location'];

		} else { // 주소가 존재하지 않을 때
			console.log("주소가 존재하지 않습니다.");
		}// if
	});//geoCoder.geocode
}//setMapPosition
더보기
더보기
  • addr2의 값을 geocode의 address에 받아서 주소를 이용한 정보들을 results에 저장하고 처리결과는 status에 저장해서 status가 OK인 경우에만 results를 대화상자에 띄워준다. 
  • 받은 주소가 addr2에 없으면 status에 OK가 아닌 값을 반환하고, addr2안에 있으면 OK를 반환한다.
  • address 파라미터: 검색할 주소의 문자열(필수로 전달해야 한다.)
  • 두번째 파라미터: 요청의 결과를 처리할 callback 함수
  • Status 객체 : 서버 API 호출 결과의 상태를 나타냄 이 값으로 요청 결과의 성공 및 실패 여부를 확인할 수 있다. 
    • OK : 요청이 성공한 상태 / ERROR : 요청이 실패한 상태
    • 요청이 성공하면 callback 함수의 첫 번째 파라미터로 json 객체가 만들어진다. 
  • setCenter( ): 지정한 좌표로 지도의 중심점을 설정한다. 
  • geometry.location : geometry라이브러리 안에 location은 위도값과 경도값을 포함하고 있다. 
  • 마커 표시
// setMapPosition 함수
function setMapPosition(addr2, home2, img2) {
		
	geoCoder.geocode({ 'address': addr2 }, function(results, status) {
		if (status == 'OK') { // 주소가 존재할 때
			console.log(results);

			// 지도의 가운데 위치를 새로 셋팅
			map.setCenter(results[0].geometry.location);
			// map.setCenter(results[0]['geometry']['location'];
			
			// 마커표시
			let marker = new google.mapsMarker({
				map : map,
				icon : 'gmap_pin.png',
				title : results[0].formatted_address,    // 주소 
				position : results[0].geometry.location  // 마커를 표시할 위치
			});

		} else { // 주소가 존재하지 않을 때
			console.log("주소가 존재하지 않습니다.");
		}// if
	});//geoCoder.geocode
}//setMapPosition
더보기
더보기
  • formatted_address 위치에 대한 읽을 수 있는 주소를 포함하는 문자열
  • 위도, 경도, 주소, 이미지, 이미지링크 걸기
// location은 함수가 아닌데 lat은 함수
let lati = results[0]['geometry']['location']['lat']();  // 위도
let longi = results[0]['geometry']['location']['lng'](); // 경도
				
let popMsg = "위도 : " + lati;
	popMsg += "<br/>경도 : " + longi;
	popMsg += "<br/>주소 : " + results[0].formatted_address;
	popMsg += "<br/><a href='"+home2+"'><img src ='../../img/"+img2+"' width='100' height='50'/></a>";
				
	let info = new google.maps.InfoWindow({content:popMsg});
				
// 이벤트에 의해서 대화상자 보여지도록 (설정 대상, 종류, 이벤트가 발생하면 실행할 함수)
google.maps.event.addListener(marker, 'click', function() {
	info.open(map, marker);
});

[전체코드]

let latitude;
let longitude;

let addr;
let homePage;
let popImg;

function mapInitial() {
	// 초기값 넣기
	latitude = 37.5729503;
	longitude = 126.9793578;

	addr = ['서울 선유도', '서울 뚝섬', '서울 시청', '서울 잠실종합운동장']; // 주소
	homePage = ["http://parks.seoul.go.kr/", "https://www.naver.com", "https://www.seoul.go.kr", "https://stadium.seoul.go.kr/reserve/jamsil"];
	popImg = ['img1.jpg', 'img2.jpg', 'img3.jpg', 'img4.jpg'];
}

let map;       // map 객체
let geoCoder;  // Geocoder 객체

function initMap() {

	mapInitial();

	// 지도의 기본 데이터
	let mapProperties = {
		center: new google.maps.LatLng(latitude, longitude),
		zoom: 12,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	}

	// 구글맵 객체 생성
	map = new google.maps.Map(document.getElementById("gmap"), mapProperties);

	// 지오코더 객체 생성
	geoCoder = new google.maps.Geocoder();

	for (var i = 0; i < addr.length; i++) {
		// setMapPosition은 만든 임의의 함수(지명, 홈페이지주소, 해당 이미지)
		setMapPosition(addr[i], homePage[i], popImg[i]);
	}
}
// setMapPosition 함수
function setMapPosition(addr2, home2, img2) {
			//   마커를 표시할 주소(addr2), 주소의 정보, 처리 결과("OK"-> 주소존재)
	geoCoder.geocode({ 'address': addr2 }, function(results, status) {
		if (status == 'OK') { // 주소가 존재할 때
			console.log(results);

			// 지도의 가운데 위치를 새로 셋팅
			map.setCenter(results[0].geometry.location);
			// map.setCenter(results[0]['geometry']['location'];
			
			// 마커표시
			let marker = new google.maps.Marker({
				map : map,
				icon : 'gmap_pin.png',
				title : results[0].formatted_address,    // 주소 
				position : results[0].geometry.location  // 마커를 표시할 위치
			});
			
			// 위도, 경도, 주소, 이미지, 이미지링크걸기
			// location은 함수가 아닌데 lat은 함수
			let lati = results[0]['geometry']['location']['lat']();  // 위도
			let longi = (results[0].geometry.location.lng()); // 경도
				
			let popMsg = "위도 : " + lati;
				popMsg += "<br/>경도 : " + longi;
				popMsg += "<br/>주소 : " + results[0].formatted_address;
				popMsg += "<br/><a href='"+home2+"'><img src ='../../img/"+img2+"' width='100' height='50'/></a>";
				
			let info = new google.maps.InfoWindow({content:popMsg});
				
			// 이벤트에 의해서 대화상자 보여지도록 (설정 대상, 종류, 이벤트가 발생하면 실행할 함수)
			google.maps.event.addListener(marker, 'click', function() {
				info.open(map, marker);
			});
		
		} else { // 주소가 존재하지 않을 때
			console.log("주소가 존재하지 않습니다.");
		}// if
	});//geoCoder.geocode
}//setMapPosition

[ 검색하는 창 만들기 ]

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>google map</title>
<style>
	#gmap{
		width:100%; 
		height:700px;
		outline:1px solid gray;
		}
	#mapSearch{
		position:absolute; 
		outline:1px solid gray;
		z-index:100;
		left:300px; 
		top:50px;
		margin:0 auto;
	}
</style>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBMbY6yhHlEq6hIqakrD9npCuKZ_z39IPA&callback=initMap&region=kr">
</script>
<script>
	function geocodeAddress() {
		let address = document.querySelector("#address");
		if(address.value==""){
			alert("검색할 지명 또는 빌딩명을 입력하세요.");
			address.value="";
			address.focus();
			return false;
		}
		setMapPosition(address.value, "http://www.naver.com", "nature.jpg");
	}
</script>
</head>
<body>
<div id="mapSearch">
	<input type="text" id="address"/>
	<input type="button" id="geoSearch" value="search" onclick="geocodeAddress()"/>
</div>
<div id="gmap"></div>
<script src = "googleMap1.js"></script>
</body>
</html>


https://l2j.co.kr/2646