⭐핵심 포인트!

1.new google.maps.Map 를 통해 맵 객체를 생성

  • 파라미터에 첫 번째 인수는 어디 맵 위치
  • 두 번째 인수는 option으로 json형태로 center, zoom, mapTypedId를 넣어준다.

2. var myCenter = new google.maps.LatLng(위도, 경도)

  • 현재의 위치를 중심으로 잡는다.
  • initMap() 콜백함수를 만들어줘야 한다. 그 이유는 아래의 script 태그 때문이다.

3. 마커 표시하기

  • var marker = new google.maps.Marker({
    map: 맵 인스턴스,
    icon:"사진 위치",
    title:,
    position: results[0].geometry.location
    })

  • map인스턴스.setCenter(results[0].geometry.location);

              

4. geocoder = new google.maps.Geocoder()

  • geocoder.geocode({'address': 주소}, (results, status) => {
    console.log(results, status)
    })

results의 결과

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<!-- googleMap 라이브러리 -->
	<script async defer src = "https://maps.googleapis.com/maps/api/js?key=AIzaSyAKbXq2Sq9eQDArGeJDTQRGxdm8Nbd9I2c&callback=initMap"></script>
</head>
<style>
	body{margin:0}
	#search{position:absolute;left:1px; top:20px;text-align:center;width:100%;}
	#searchList{
		position:absolute; left:20px; top:50px; border:1px solid #ddd; background:#eee;
		width: 400px; height:700px; opacity:0.6;
		 
	}
	.addrList{
		background: #fff;
		margin:10px;
		padding: 10px; 
	}
</style>
<body>
<!-- 지도표시  -->
<div id="gMap"></div>
<!-- 검색  -->
<div id="search">
	<input type="text" id="searchWord" onkeyup="geocodeSearchKey()" />
	<input type="button" id="geoSubmit" value="geoCode" onclick= "geocodeSearch()"  />
</div>
<!-- 검색결과표시 -->
<div id="searchList"></div>

<script>
	//지도표시할 영역의 높이를 창의 크기를 기준으로 설정하기
	window.innerHeight
	document.getElementById("gMap").style.height = window.innerHeight + "px";
	//현재 위치를 이용하여 위도, 경도 구하기
	var latitude;
	var longitude;
	var map;
	var geocoder;
	
	
	var showPosition = (position) =>{
		latitude = position.coords.latitude;  //위도
		longitude = position.coords.longitude;//경도
	}
	
	var geoLocation = () =>{
		if(navigator.geolocation){
			//**콜백함수: 파라미터로 함수를 전달받아, 함수의 내부에서 실행하는 함수
			navigator.geolocation.getCurrentPosition(showPosition);
	
		}else{}
	}
	geoLocation(); 
	// 
	function initMap(){
		var myCenter = new google.maps.LatLng(latitude, longitude);
		var option = {
				center: myCenter,
				zoom: 16,
				mapTypeId: google.maps.MapTypeId.ROADMAP
		} 
		map = new google.maps.Map(document.getElementById("gMap"), option)
		//지명, 건물명을 검색을 위해 지오코드 객체를 만든다.
		geocoder = new google.maps.Geocoder()
	}
	//건물명, 지명을 입력한 후 검색
	//버튼 : click이벤트, text 박스: 
   function geocodeSearch(){
		//검색어 입력이 되지 않은 경우
		if(document.getElementById("searchWord").value==""){
			alert("데이터를 입력하세요");
			return false;
		} else{//검색어가 입력된 경우
			geoAddress(document.getElementById("searchWord").value);
		}
		document.getElementById("searchWord").value = "";
	}
	//키 이벤트
	function geocodeSearchKey(){
		//키보드에서 enter입력되면 검색을 해야 된다.
		//event 내장객체를 이용한 현재 입력한 키보드 값(아스키 코드 13) 
		if(event.keyCode == 13){
			geocodeSearch();
		} 
	}
	// ***geocode객체를 이용한 지도 검색***
	function geoAddress(addrName){
		//			 검색주소, 콜백함수(검색결과 처리를 할)
		geocoder.geocode({'address': addrName}, function(results, status){
			//results: 찾은 지도 정보
			//status:찾기 성공(OK), ZERO_RESULTS
			console.log(results);
			console.log(status)
			//결과값이 있을 때
			if(status == 'OK'){
				//위도
				var lat = results[0]['geometry']['location']['lat']();
				//경도
				var lng = results[0].geometry.location.lng();
				//주소
				var addr = results[0].formatted_address;
				//대한민국 제거
				if(addr.indexOf("대한민국")==0){
					addr.substring(5);
				}
                //** 검색 리스트 만들기 ** 
				var tag = "<div class='addrList'>";
				tag += "위도" + lat +"<br />";
				tag += "경도" + lng +"<br />";
				tag += "주소" + addr;
				tag += "</div>";
				
				var dom = document.getElementById("searchList");
				dom.innerHTML = dom.innerHTML + tag;
				
				//중심위치 이동하기
				map.setCenter(results[0].geometry.location);
				var marker = new google.maps.Marker({
					map: map,
					icon:"../img/gmap_pin.png",
					title:addr,
					position: results[0].geometry.location
				})
				marker.setMap(map);
				//마우스 오버시 대화상자 표시
				var infor = new google.maps.InfoWindow({content:tag});
				//팝업대화상자 처리를 위한 이벤트
				google.maps.event.addListener(marker, 'mouseover', function(){ return infor.open(map, marker)})
				google.maps.event.addListener(marker, 'mouseout', function(){return infor.close(map, marker)})
				
			}else{
				alert("검색 결과가 존재하지 않습니다.")
			}
		});
	}
</script>
</body>
</html>

profile
풀스택eDot

0개의 댓글