[Google Map] Places search box 구글 자동완성을 이용한 위경도 값 가져오기

Open API/Google|2018. 7. 4. 15:28
반응형

구글맵 위치정보를 활용한 

자동완성 기능을 적용시키는 샘플



구글의 정보는 정말 말로 할수없을 만큼 방대합니다.


그 중에서 맵데이터는 정말 놀라운데요.


기존에 장소(정확히는 도시별)별 위경도 값을 직접 데이터관리하던 부분을


구글 장소 검색 ( Places Search Box ) 기능으로 대체하게 되었습니다.


잘 구축된 API를 잘 가져다 쓰면 되기 때문에 참 편하죠.


자동완성의 반응속도도 빠르고 나름 직접 관리하는 것보다 정확하기 때문에 


여러모로 유용할것같습니다.


실제로 구현 하는 경우에는 가장 하단에 Js 참조할때 key 값을 입력해야합니다.


https://maps.googleapis.com/maps/api/js?key=여기에키값입력&libraries=places&callback=initAutocomplete

가져온 데이터에서 위경도 값을 읽어오는 부분은 
 

// place 에서 위경도 값을 읽어올 수 있음. 


▲  이라고 주석이 달린 부분을 참고하시면 될것같습니다.








◎ 실제로 구글 API의 Response값을 체크해서 데이터를 확인해보겠습니다. ( 크롬기준 )




1. 샘플 페이지를 열어서 F12를 눌러 개발자 도구를 실행하고 Network 탭으로 이동

그리고 키워드 검색을 통해 자동완성목록이 보여지는것을 확인.

그와 동시에 AutocompletionService.GetQueryPredictions 페이지를 호출하여 값을 가져옴.


(아래 이미지는 클릭하면 커집니다)




2. 목록 중 하나를 선택 했을 때 PlaceService.GetPlaceDetails 페이지를 호출하여 상세 정보를 가져옴.


(아래 이미지는 클릭하면 커집니다)



3. 해당 호출에 대한 Request


(아래 이미지는 클릭하면 커집니다)



4. 해당 호출에 대한 Response 데이터 , 이렇게 확인이 가능합니다.

실제로 Respons되는 데이터의 항목이 다양한데 이 또한 필요에 따라 활용이 가능할것같습니다.


(아래 이미지는 클릭하면 커집니다)





아래 코드의 99%는 


https://developers.google.com/maps/documentation/javascript/examples/places-searchbox


에서도 확인 하실 수 있습니다.



<!DOCTYPE html>
<html>

<head>
	<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
	<meta charset="utf-8">
	<title>Places Searchbox</title>
	<style>
		/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */

		#map {
			height: 100%;
		}

		/* Optional: Makes the sample page fill the window. */

		html,
		body {
			height: 100%;
			margin: 0;
			padding: 0;
		}

		#description {
			font-family: Roboto;
			font-size: 15px;
			font-weight: 300;
		}

		#infowindow-content .title {
			font-weight: bold;
		}

		#infowindow-content {
			display: none;
		}

		#map #infowindow-content {
			display: inline;
		}

		.pac-card {
			margin: 10px 10px 0 0;
			border-radius: 2px 0 0 2px;
			box-sizing: border-box;
			-moz-box-sizing: border-box;
			outline: none;
			box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
			background-color: #fff;
			font-family: Roboto;
		}

		#pac-container {
			padding-bottom: 12px;
			margin-right: 12px;
		}

		.pac-controls {
			display: inline-block;
			padding: 5px 11px;
		}

		.pac-controls label {
			font-family: Roboto;
			font-size: 13px;
			font-weight: 300;
		}

		#pac-input {
			background-color: #fff;
			font-family: Roboto;
			font-size: 15px;
			font-weight: 300;
			margin-left: 12px;
			padding: 0 11px 0 13px;
			text-overflow: ellipsis;
			width: 400px;
		}

		#pac-input:focus {
			border-color: #4d90fe;
		}

		#title {
			color: #fff;
			background-color: #4d90fe;
			font-size: 25px;
			font-weight: 500;
			padding: 6px 12px;
		}

		#target {
			width: 345px;
		}
	</style>
</head>

<body> <input id="pac-input" class="controls" type="text" placeholder="Search Box">
	<div id="map"></div>
	<script>
		// This example adds a search box to a map, using the Google Place Autocomplete
		// feature. People can enter geographical searches. The search box will return a
		// pick list containing a mix of places and predicted search terms.
		// This example requires the Places library. Include the libraries=places
		// parameter when you first load the API. For example:
		// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
		function initAutocomplete() {
			var map = new google.maps.Map(document.getElementById('map'), {
				center: {
					lat: -33.8688,
					lng: 151.2195
				},
				zoom: 13,
				mapTypeId: 'roadmap'
			});
			// Create the search box and link it to the UI element.
			var input = document.getElementById('pac-input');
			var searchBox = new google.maps.places.SearchBox(input);
			map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
			// Bias the SearchBox results towards current map's viewport.
			map.addListener('bounds_changed', function() {
				searchBox.setBounds(map.getBounds());
			});
			var markers = [];
			// Listen for the event fired when the user selects a prediction and retrieve
			// more details for that place.
			searchBox.addListener('places_changed', function() {
				var places = searchBox.getPlaces();
				if (places.length == 0) {
					return;
				}
				// Clear out the old markers.
				markers.forEach(function(marker) {
					marker.setMap(null);
				});
				markers = [];
				// For each place, get the icon, name and location.
				var bounds = new google.maps.LatLngBounds();
				places.forEach(function(place) {
					if (!place.geometry) {
						console.log("Returned place contains no geometry");
						return;
					}

                                        // place 에서 위경도 값을 읽어올 수 있음. 
					console.log(place.geometry.location.lat());
					console.log(place.geometry.location.lng());

					var icon = {
						url: place.icon,
						size: new google.maps.Size(71, 71),
						origin: new google.maps.Point(0, 0),
						anchor: new google.maps.Point(17, 34),
						scaledSize: new google.maps.Size(25, 25)
					};
					// Create a marker for each place.
					markers.push(new google.maps.Marker({
						map: map,
						icon: icon,
						title: place.name,
						position: place.geometry.location
					}));
					if (place.geometry.viewport) {
						// Only geocodes have viewport.
						bounds.union(place.geometry.viewport);
					} else {
						bounds.extend(place.geometry.location);
					}
				});
				map.fitBounds(bounds);
			});
		}
	</script>
	<script src="https://maps.googleapis.com/maps/api/js?key=&libraries=places&callback=initAutocomplete" async defer></script>
</body>

</html>


댓글()

구글맵 마커 + 말풍선 - v3

Open API/Google|2016. 12. 12. 18:30
반응형

구글맵 V3 + 마커 샘플입니다.


일반적으로 기본 구글맵에서 가장 많이쓰는것이기도 한데요..


Test Url : http://www.uhoon.co.kr/test/4338/4338.html



<!DOCTYPE html>
<html>

<head>
	<meta charset="utf-8">
	<title>Info windows</title>
	<style>
		html,
		body,
		#map-canvas {
			height: 400px;
			width:600px;
			margin: 0px;
			padding: 0px
		}
	</style>
	<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
	<script>
		function initialize() {
			var myLatlng = new google.maps.LatLng(37.55544,127.07590);		// 위경도 수정
			var mapOptions = {
				zoom: 17,
				center: myLatlng
			};

			var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

                        // 말풍선 내용 수정
			var contentString = '<div style="width:100px;height:50px;">군자동 주민센터</div>';		

			var infowindow = new google.maps.InfoWindow({
				content: contentString,
				size: new google.maps.Size(200,100)
			});

			var marker = new google.maps.Marker({
				position: myLatlng,
				map: map
			});
			google.maps.event.addListener(marker, 'click', function() {
				infowindow.open(map, marker);
			});
		}

		google.maps.event.addDomListener(window, 'load', initialize);
	</script>
</head>

<body>
	<div id="map-canvas"></div>
</body>

</html>

* Info Window :  https://developers.google.com/maps/documentation/javascript/examples/infowindow-simple?hl=ko* Info Window Options : https://developers.google.com/maps/documentation/javascript/reference?hl=ko#InfoWindowOptions

댓글()