컨트롤 개요
Google Maps JavaScript API를 통해 표시되는 지도는 사용자가 지도와 상호작용이 가능한 UI 요소를 포함합니다. 이러한 요소를 컨트롤이라고 하며, 자신의 애플리케이션에 이러한 컨트롤의 변형을 포함할 수 있습니다. 또는, 아무것도 하지 않고 Google Maps JavaScript API가 모든 제어 동작을 처리하게 할 수 있습니다.
다음 지도는 Google Maps JavaScript API에 의해 표시되는 기본 컨트롤 세트를 보여줍니다.
아래는 지도에 사용할 수 있는 컨트롤 세트의 전체 목록입니다.
- Zoom control은 지도의 확대/축소 수준을 변경하는 데 사용되는 "+"와 "-" 버튼을 표시합니다. 기본적으로 이 컨트롤은 지도의 오른쪽 아래 모서리에 나타납니다.
- 지도 유형 컨트롤은 드롭다운이나 가로 버튼 막대 스타일로 제공되며, 사용자가 지도 유형(
ROADMAP
,SATELLITE
,HYBRID
또는TERRAIN
)을 선택할 수 있습니다. 이 컨트롤은 기본적으로 지도의 왼쪽 위 모서리에 나타납니다. - 스트리트 뷰 컨트롤에는 지도로 드래그해서 스트리트 뷰를 활성화할 수 있는 펙맨 아이콘이 있습니다. 기본적으로 이 컨트롤은 지도의 오른쪽 아래 근처에 나타납니다.
- 회전 컨트롤은 경사진 이미지가 포함된 지도에 틸트와 회전 옵션 조합을 제공합니다. 기본적으로 이 컨트롤은 지도의 오른쪽 아래 근처에 나타납니다. 자세한 내용은 45° 이미지를 참조하세요.
- 배율 컨트롤은 지도 배율 요소를 표시합니다. 이 컨트롤은 기본적으로 비활성화되어 있습니다.
- 전체 화면 컨트롤은 지도를 전체 화면 모드에서 여는 옵션을 제공합니다. 이 컨트롤은 모바일 기기에서 기본적으로 활성화되고 데스크톱에서 기본적으로 비활성화됩니다. 참고: iOS는 전체 화면 기능을 지원하지 않습니다. 따라서 전체 화면 컨트롤은 iOS 기기에서 보이지 않습니다.
이러한 지도 컨트롤에 직접 액세스하거나 수정할 수 없습니다. 대신, 컨트롤의 가시성과 표현에 영향을 미치는 지도의 MapOptions
필드를 수정합니다. 지도를 인스턴스화하여(적절한 MapOptions
사용) 컨트롤 프레젠테이션을 조정하거나 setOptions()
을 호출하여 지도 옵션을 변경하는 방식으로 지도를 동적으로 수정할 수 있습니다.
이러한 컨트롤이 모두 기본적으로 활성화되는 것은 아닙니다. 기본 UI 동작(및 이러한 동작의 수정 방법)에 대해 알아보려면 아래 기본 UI를 참조하세요.
기본 UI
기본적으로, 지도가 너무 작으면(200x200px) 모든 컨트롤이 사라집니다. 컨트롤이 보이도록 명시적으로 설정함으로써 이 동작을 재정의할 수 있습니다. 지도에 컨트롤 추가를 참조하세요.
컨트롤의 동작과 모양은 모바일과 데스크톱 기기에서 동일하며, 전체 화면 컨트롤만 예외입니다(컨트롤 목록에 설명된 동작 참조).
또한, 키보드 처리는 기본적으로 모든 기기에서 켜져 있습니다.
기본 UI 비활성화
API의 기본 UI 설정을 완전히 비활성할 수도 있습니다. 이렇게 하려면 지도의 disableDefaultUI
속성(MapOptions
객체 내부)을 true
로 설정합니다. 이 속성은 Google Maps JavaScript API에서 모든 자동 UI 동작을 비활성화합니다.
다음 코드는 기본 UI를 완전히 비활성화합니다.
function initMap() { var map = new google.maps.Map(document.getElementById('map'), { zoom: 4, center: {lat: -33, lng: 151}, disableDefaultUI: true }); }
<div id="map"></div>
/* 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; }
<!-- Replace the value of the key parameter with your own API key. --> <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"> </script>
function initMap() { var map = new google.maps.Map(document.getElementById('map'), { zoom: 4, center: {lat: -33, lng: 151}, disableDefaultUI: true }); }
예시 보기(control-disableUI.html).
지도에 컨트롤 추가
UI 동작이나 컨트롤을 제거, 추가, 수정하는 방식으로 인터페이스를 사용자 지정하고, 향후 업데이트에서 이 동작을 변경하지 않도록 할 수도 있습니다. 기존 동작만 추가하거나 수정하고자 한다면 컨트롤이 애플리케이션에 명시적으로 추가되도록 해야 합니다.
지도에 기본적으로 나타나는 컨트롤도 있지만, 특별히 요청하지 않으면 나타나지 않는 컨트롤도 있습니다. 지도에서 컨트롤을 추가/삭제하는 작업은 다음 MapOptions
객체 필드에서 지정됩니다. 이 필드를 true
로 설정하면 컨트롤이 보이고, false
로 설정하면 숨겨집니다.
{ zoomControl: boolean, mapTypeControl: boolean, scaleControl: boolean, streetViewControl: boolean, rotateControl: boolean, fullscreenControl: boolean }
기본적으로, 지도가 200x200px보다 작으면 모든 컨트롤이 사라집니다. 컨트롤이 보이도록 명시적으로 설정함으로써 이 동작을 재정의할 수 있습니다. 예를 들어, 다음 표는 지도 크기와 zoomControl
필드의 설정에 따라 확대/축소 컨트롤이 표시되는지 여부를 보여줍니다.
지도 크기 | zoomControl |
표시 여부 |
---|---|---|
모두 | false |
아니요 |
모두 | true |
예 |
>= 200x200px | undefined |
예 |
< 200x200px | undefined |
아니요 |
다음 예시는 확대/축소 컨트롤을 숨기고 배율 컨트롤을 표시하도록 지도를 설정합니다. 기본 UI를 명시적으로 비활성화하지 않았으므로 이 수정 사항을 기본 UI 동작에 추가할 수 있습니다.
function initMap() { var map = new google.maps.Map(document.getElementById('map'), { zoom: 4, center: {lat: -33, lng: 151}, zoomControl: false, scaleControl: true }); }
<div id="map"></div>
/* 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; }
<!-- Replace the value of the key parameter with your own API key. --> <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"> </script>
function initMap() { var map = new google.maps.Map(document.getElementById('map'), { zoom: 4, center: {lat: -33, lng: 151}, zoomControl: false, scaleControl: true }); }
컨트롤 옵션
여러 컨트롤이 구성 가능하며, 컨트롤의 동작이나 모양을 변경할 수 있습니다. 예를 들어, 지도 유형 컨트롤은 가로 막대나 드롭다운 메뉴로 나타납니다.
이러한 컨트롤은 지도 생성 시 MapOptions
객체 내에서 적절한 컨트롤 옵션을 변경하는 방식으로 수정됩니다.
예를 들어, 지도 유형 컨트롤을 변경하는 옵션은 mapTypeControlOptions
필드에 나타납니다. 지도 유형 컨트롤은 다음 style
옵션 중 하나로 나타날 수 있습니다.
google.maps.MapTypeControlStyle.HORIZONTAL_BAR
는 Google 지도에 나오는 것처럼 수평 막대에 버튼으로 컨트롤 배열을 표시합니다.google.maps.MapTypeControlStyle.DROPDOWN_MENU
는 드롭다운 메뉴를 통해 지도 유형을 선택할 수 있는 단일 버튼 컨트롤을 표시합니다.google.maps.MapTypeControlStyle.DEFAULT
는 기본 동작을 표시합니다. 이는 화면 크기에 따라 달라지고 차기 API 버전에서 변경될 수 있습니다.
컨트롤 옵션을 수정하는 경우, 적절한 MapOptions
값을 true
로 설정하여 컨트롤을 명시적으로 활성화해야 합니다. 예를 들어, 지도 유형 컨트롤을 DROPDOWN_MENU
스타일을 표시하도록 설정하려면 MapOptions
객체 내에 다음 코드를 사용합니다.
... mapTypeControl: true, mapTypeControlOptions: { style: google.maps.MapTypeControlStyle.DROPDOWN_MENU } ...
다음 예시는 기본 위치와 컨트롤의 스타일을 변경하는 방법을 보여줍니다.
// You can set control options to change the default position or style of many // of the map controls. function initMap() { var map = new google.maps.Map(document.getElementById('map'), { zoom: 4, center: {lat: -33, lng: 151}, mapTypeControl: true, mapTypeControlOptions: { style: google.maps.MapTypeControlStyle.DROPDOWN_MENU, mapTypeIds: ['roadmap', 'terrain'] } }); }
<div id="map"></div>
/* 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; }
<!-- Replace the value of the key parameter with your own API key. --> <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"> </script>
// You can set control options to change the default position or style of many // of the map controls. function initMap() { var map = new google.maps.Map(document.getElementById('map'), { zoom: 4, center: {lat: -33, lng: 151}, mapTypeControl: true, mapTypeControlOptions: { style: google.maps.MapTypeControlStyle.DROPDOWN_MENU, mapTypeIds: ['roadmap', 'terrain'] } }); }
일반적으로 컨트롤은 지도 생성 시 구성됩니다. 그러나 Map
의 setOptions()
메서드를 호출하고 새로운 컨트롤 옵션에 전달함으로써 컨트롤 표현을 동적으로 변경할 수 있습니다.
컨트롤 수정
지도의 MapOptions
객체 내에서 필드를 통해 지도를 생성할 때 컨트롤의 표현 방식을 지정합니다. 이러한 필드의 의미는 다음과 같습니다.
zoomControl
은 확대/축소 컨트롤을 활성화/비활성화합니다. 기본적으로 이 컨트롤은 표시되고 지도의 오른쪽 아래 근처에 나타납니다.zoomControlOptions
필드는 이 컨트롤에 사용할ZoomControlOptions
를 추가로 지정합니다.mapTypeControl
은 사용자가 지도 유형 간에(지도나 위성 등) 전환할 수 있는 지도 유형 컨트롤을 활성화/비활성화합니다. 기본적으로, 이 컨트롤은 표시되고 지도의 왼쪽 위 모서리에 나타납니다.mapTypeControlOptions
필드는 이 컨트롤에 사용할MapTypeControlOptions
를 추가로 지정합니다.streetViewControl
은 사용자가 스트리트 뷰 파노라마를 활성화할 수 있는 펙맨 컨트롤을 활성화/비활성화합니다. 기본적으로 이 컨트롤은 표시되고 지도의 오른쪽 아래 근처에 나타납니다.streetViewControlOptions
필드는 이 컨트롤에 사용할StreetViewControlOptions
를 추가로 지정합니다.rotateControl
은 45° 이미지의 방향을 제어하는 회전 컨트롤의 표시를 활성화/비활성화합니다. 기본적으로, 이 컨트롤의 표시 여부는 현재 확대/축소와 위치에서 특정 지도 유형에 45° 이미지가 있는지 여부로 결정됩니다. 지도의rotateControlOptions
를 설정하여 사용할RotateControlOptions
를 지정하는 방식으로 컨트롤의 동작을 변경할 수 있습니다. 현재 이용 가능한 45° 이미지가 없으면 컨트롤을 나타낼 수 없습니다.scaleControl
은 간단한 지도 배율을 제공하는 배율 컨트롤을 활성화/비활성화합니다. 기본적으로, 이 컨트롤은 표시되지 않습니다. 이 컨트롤이 활성화된 경우 항상 지도의 오른쪽 아래 모서리에 나타납니다.scaleControlOptions
는 이 컨트롤에 사용할ScaleControlOptions
를 추가로 지정합니다.fullscreenControl
은 지도를 전체 화면 모드에서 여는 컨트롤을 활성화/비활성화합니다. 기본적으로, 이 컨트롤은 모바일 기기에서 보이고 데스크톱에서는 보이지 않습니다. 활성화된 경우, 이 컨트롤이 지도의 오른쪽 위에 나타납니다.fullscreenControlOptions
는 이 컨트롤에 사용할FullscreenControlControlOptions
를 추가적으로 지정합니다.
처음에 비활성화한 컨트롤의 옵션을 지정할 수도 있습니다.
컨트롤 위치 지정
대부분의 컨트롤 옵션에는 지도에서 컨트롤을 배치할 위치를 나타내는 position
속성(ControlPosition
유형)이 포함됩니다. 이러한 컨트롤의 위치 지정은 절대값이 아닙니다. 대신 API는 주어진 제약 조건(지도 크기 등) 내에서 기존 지도 요소 또는 다른 컨트롤 주변에 유동적으로 배치하는 방식으로 지능적으로 컨트롤의 레이아웃을 설정합니다.
참고: API가 컨트롤을 지능적으로 배치하려고 시도하겠지만 주어진 복잡한 레이아웃에 컨트롤이 중첩되지 않는다는 보장은 없습니다.
다음과 같은 컨트롤 위치가 지원됩니다.
TOP_CENTER
는 컨트롤이 지도의 위쪽 가운데 배치되어야 함을 나타냅니다.TOP_LEFT
는 컨트롤이 지도의 왼쪽 위에 배치되어야 함을 나타냅니다. 컨트롤의 하위 요소는 위쪽 가운데 방향으로 "유동적으로 배치"되어야 합니다.TOP_RIGHT
는 컨틀롤이 지도의 오른쪽 위에 배치되어야 함을 나타냅니다. 컨트롤의 하위 요소는 위쪽 가운데 방향으로 "유동적으로 배치"되어야 합니다.LEFT_TOP
은 컨트롤이 지도의 왼쪽 위,TOP_LEFT
요소 아래 배치되어야 함을 나타냅니다.RIGHT_TOP
는 컨트롤이 지도의 오른쪽 위,TOP_RIGHT
요소 아래 배치되어야 함을 나타냅니다.LEFT_CENTER
는 컨트롤이 지도의 왼쪽 측면,TOP_LEFT
와BOTTOM_LEFT
위치 사이의 가운데 배치되어야 함을 나타냅니다.RIGHT_CENTER
는 컨트롤이 지도의 오른쪽 측면,TOP_RIGHT
와BOTTOM_RIGHT
위치 사이의 가운데 배치되어야 함을 나타냅니다.LEFT_BOTTOM
은 컨트롤이 지도의 왼쪽 아래,BOTTOM_LEFT
요소 위에 배치되어야 함을 나타냅니다.RIGHT_BOTTOM
는 컨트롤이 지도의 오른쪽 아래BOTTOM_RIGHT
요소 위에 배치되어야 한다는 것을 나타냅니다.BOTTOM_CENTER
는 컨트롤이 지도의 아래쪽 중앙에 배치되어야 함을 나타냅니다.BOTTOM_LEFT
는 컨트롤이 지도의 왼쪽 아래 배치되고, 컨트롤의 하위 요소는 아래쪽 가운데 방향으로 "유동적으로 배치"되어야 함을 나타냅니다.BOTTOM_RIGHT
는 컨트롤이 지도의 오른쪽 아래 배치되고, 컨트롤의 하위 요소는 아래쪽 가운데 방향으로 "유동적으로 배치"되어야 함을 나타냅니다.
예시 보기(control-positioning-labels.html).
이 위치는 위치를 수정할 수 없는 UI 요소(예: 저작권 및 Google 로고)의 위치와 겹칠 수 있습니다. 이 경우, 컨트롤은 각 위치에 적용된 로직에 따라 유동적으로 배치되고 최대한 표시된 위치에 가깝게 나타납니다.
다음 예시는 모든 컨트롤이 다른 위치에 활성화된 간단한 지도를 보여줍니다.
function initMap() { var map = new google.maps.Map(document.getElementById('map'), { zoom: 12, center: {lat: -28.643387, lng: 153.612224}, mapTypeControl: true, mapTypeControlOptions: { style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR, position: google.maps.ControlPosition.TOP_CENTER }, zoomControl: true, zoomControlOptions: { position: google.maps.ControlPosition.LEFT_CENTER }, scaleControl: true, streetViewControl: true, streetViewControlOptions: { position: google.maps.ControlPosition.LEFT_TOP }, fullscreenControl: true }); }
<div id="map"></div>
/* 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; }
<!-- Replace the value of the key parameter with your own API key. --> <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"> </script>
function initMap() { var map = new google.maps.Map(document.getElementById('map'), { zoom: 12, center: {lat: -28.643387, lng: 153.612224}, mapTypeControl: true, mapTypeControlOptions: { style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR, position: google.maps.ControlPosition.TOP_CENTER }, zoomControl: true, zoomControlOptions: { position: google.maps.ControlPosition.LEFT_CENTER }, scaleControl: true, streetViewControl: true, streetViewControlOptions: { position: google.maps.ControlPosition.LEFT_TOP }, fullscreenControl: true }); }
예시 보기(control-positioning.html).
사용자 지정 컨트롤
기존 API 컨트롤의 스타일과 위치를 수정하는 것은 물론, 사용자와의 상호작용을 처리하는 컨트롤을 생성할 수 있습니다. 밑에 있는 지도와 함께 움직이는 오버레이와 반대로 컨트롤은 지도 위의 절대 위치 위에 떠 있는 정적인 위젯입니다. 기본적으로 컨트롤은 단순히 <div>
요소로, 지도에 절대 위치를 갖고 있고, 사용자에게 일부 UI를 표시하고, 이벤트 핸들러를 통해 사용자 또는 지도와의 상호작용을 처리합니다.
자체 사용자 지정 컨트롤을 생성할 때는 규칙이 거의 필요 없습니다. 그러나 다음 지침이 모범 사례 역할을 할 수 있습니다.
- 표시할 컨트롤 요소에 적절한 CSS를 정의합니다.
- 지도 속성 변경이나 사용자 이벤트(예:
'click'
이벤트)가 발생할 경우, 이벤트 핸들러를 통해 사용자 또는 지도와의 상호작용을 처리합니다. <div>
요소를 생성하여 컨트롤을 유지하고, 이 요소를Map
의controls
속성에 추가합니다.
각각에 대한 내용은 아래에서 설명됩니다.
사용자 지정 컨트롤 그리기
컨트롤을 그리는 방식은 여러분에게 달려 있습니다. 일반적으로 컨트롤을 하나의 단위로 조작할 수 있도록 모든 컨트롤 프레젠테이션을 단일 <div>
요소 안에 배치하는 것이 좋습니다. 아래 샘플에서 이 디자인 패턴을 사용할 것입니다.
매력적인 컨트롤을 디자인하려면 CSS와 DOM 구조를 어느 정도 이해해야 합니다. 다음 코드는 포함된 <div>
에서 간단한 컨트롤을 생성하는 방법을 보여줍니다. 한 <div>
는 버튼 윤곽선을 고정하고 다른 <div>
는 버튼 내부를 고정합니다.
// Create a div to hold the control. var controlDiv = document.createElement('div'); // Set CSS for the control border var controlUI = document.createElement('div'); controlUI.style.backgroundColor = '#fff'; controlUI.style.border = '2px solid #fff'; controlUI.style.cursor = 'pointer'; controlUI.style.marginBottom = '22px'; controlUI.style.textAlign = 'center'; controlUI.title = 'Click to recenter the map'; controlDiv.appendChild(controlUI); // Set CSS for the control interior var controlText = document.createElement('div'); controlText.style.color = 'rgb(25,25,25)'; controlText.style.fontFamily = 'Roboto,Arial,sans-serif'; controlText.style.fontSize = '16px'; controlText.style.lineHeight = '38px'; controlText.style.paddingLeft = '5px'; controlText.style.paddingRight = '5px'; controlText.innerHTML = 'Center Map'; controlUI.appendChild(controlText);
사용자 지정 컨트롤에서 이벤트 처리
컨트롤이 유용하려면 실제로 어떤 동작을 해야 합니다. 컨트롤의 동작은 여러분이 결정합니다. 컨트롤은 사용자 입력에 응답하거나 Map
의 상태 변경에 응답할 수 있습니다.
사용자 입력에 응답할 경우, Google Maps JavaScript API는 브라우저 간 이벤트 처리 메서드 addDomListener()
를 제공합니다. 이는 대부분 브라우저의 지원되는 DOM 이벤트를 처리합니다. 다음 코드 스니펫은 브라우저의 'click'
이벤트에 대한 리스너를 추가합니다. 이 이벤트는 지도가 아니라 DOM에서 수신된다는 점에 유의하세요.
// Setup the click event listener: simply set the map to center on Chicago var chicago = {lat: 41.850, lng: -87.650}; google.maps.event.addDomListener(outer, 'click', function() { map.setCenter(chicago) });
사용자 지정 컨트롤 위치 지정
사용자 지정 컨트롤은 Map
객체의 controls
속성 내에서 적절한 위치에 배치하는 방식으로 지도에 배치됩니다. 이 속성은 google.maps.ControlPosition
의 배열을 포함합니다. Node
(일반적으로 <div>
)를 적절한 ControlPosition
에 추가하는 방식으로 지도에 사용자 지정 컨트롤을 추가합니다. (이 위치에 관한 내용은 위의 컨트롤 위치 지정을 참조하세요.)
각 ControlPosition
은 해당 위치에 표시된 컨트롤의 MVCArray
를 저장합니다. 따라서 해당 위치에서 컨트롤이 추가/삭제될 경우, API가 그에 따라 컨트롤을 업데이트합니다.
API는 index
속성의 순서에 따라 각 위치에 컨트롤을 배치합니다. 인덱스가 낮은 컨트롤이 먼저 배치됩니다. 예를 들어, BOTTOM_RIGHT
위치에 있는 2개의 사용자 지정 컨트롤은 낮은 인덱스 값을 우선순위로 인덱스 순서에 따라 배치됩니다. 기본적으로, 모든 사용자 지정 컨트롤은 API 기본 컨트롤이 배치된 후에 배치됩니다. 컨트롤의 index
속성을 음수 값으로 설정하여 이 동작을 재정의할 수 있습니다. 사용자 지정 컨트롤은 로고의 왼쪽이나 저작권 고지의 오른쪽에 배치될 수 없습니다.
다음 코드는 새 사용자 지정 컨트롤을 생성하고(생성자는 표시되지 않음) 지도의 TOP_RIGHT
위치에 추가합니다.
var map = new google.maps.Map(document.getElementById('map'), mapOptions); // Construct your control in whatever manner is appropriate. // Generally, your constructor will want access to the // DIV on which you'll attach the control UI to the Map. var controlDiv = document.createElement('div'); var myControl = new MyControl(controlDiv); // We don't really need to set an index value here, but // this would be how you do it. Note that we set this // value as a property of the DIV itself. controlDiv.index = 1; // Add the control to the map at a designated control position // by pushing it on the position's array. This code will // implicitly add the control to the DOM, through the Map // object. You should not attach the control manually. map.controls[google.maps.ControlPosition.TOP_RIGHT].push(controlDiv);
사용자 지정 컨트롤 예시
다음 컨트롤은 (특별히 유용하지는 않지만) 간단하고 위에서 보여준 패턴을 결합합니다. 이 컨트롤은 지도의 중심을 특정 기본 위치에 두는 방식으로 DOM 'click'
이벤트에 응답합니다.
var map; var chicago = {lat: 41.85, lng: -87.65}; /** * The CenterControl adds a control to the map that recenters the map on * Chicago. * This constructor takes the control DIV as an argument. * @constructor */ function CenterControl(controlDiv, map) { // Set CSS for the control border. var controlUI = document.createElement('div'); controlUI.style.backgroundColor = '#fff'; controlUI.style.border = '2px solid #fff'; controlUI.style.borderRadius = '3px'; controlUI.style.boxShadow = '0 2px 6px rgba(0,0,0,.3)'; controlUI.style.cursor = 'pointer'; controlUI.style.marginBottom = '22px'; controlUI.style.textAlign = 'center'; controlUI.title = 'Click to recenter the map'; controlDiv.appendChild(controlUI); // Set CSS for the control interior. var controlText = document.createElement('div'); controlText.style.color = 'rgb(25,25,25)'; controlText.style.fontFamily = 'Roboto,Arial,sans-serif'; controlText.style.fontSize = '16px'; controlText.style.lineHeight = '38px'; controlText.style.paddingLeft = '5px'; controlText.style.paddingRight = '5px'; controlText.innerHTML = 'Center Map'; controlUI.appendChild(controlText); // Setup the click event listeners: simply set the map to Chicago. controlUI.addEventListener('click', function() { map.setCenter(chicago); }); } function initMap() { map = new google.maps.Map(document.getElementById('map'), { zoom: 12, center: chicago }); // Create the DIV to hold the control and call the CenterControl() // constructor passing in this DIV. var centerControlDiv = document.createElement('div'); var centerControl = new CenterControl(centerControlDiv, map); centerControlDiv.index = 1; map.controls[google.maps.ControlPosition.TOP_CENTER].push(centerControlDiv); }
<div id="map"></div>
/* 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; }
<!-- Replace the value of the key parameter with your own API key. --> <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"> </script>
var map; var chicago = {lat: 41.85, lng: -87.65}; /** * The CenterControl adds a control to the map that recenters the map on * Chicago. * This constructor takes the control DIV as an argument. * @constructor */ function CenterControl(controlDiv, map) { // Set CSS for the control border. var controlUI = document.createElement('div'); controlUI.style.backgroundColor = '#fff'; controlUI.style.border = '2px solid #fff'; controlUI.style.borderRadius = '3px'; controlUI.style.boxShadow = '0 2px 6px rgba(0,0,0,.3)'; controlUI.style.cursor = 'pointer'; controlUI.style.marginBottom = '22px'; controlUI.style.textAlign = 'center'; controlUI.title = 'Click to recenter the map'; controlDiv.appendChild(controlUI); // Set CSS for the control interior. var controlText = document.createElement('div'); controlText.style.color = 'rgb(25,25,25)'; controlText.style.fontFamily = 'Roboto,Arial,sans-serif'; controlText.style.fontSize = '16px'; controlText.style.lineHeight = '38px'; controlText.style.paddingLeft = '5px'; controlText.style.paddingRight = '5px'; controlText.innerHTML = 'Center Map'; controlUI.appendChild(controlText); // Setup the click event listeners: simply set the map to Chicago. controlUI.addEventListener('click', function() { map.setCenter(chicago); }); } function initMap() { map = new google.maps.Map(document.getElementById('map'), { zoom: 12, center: chicago }); // Create the DIV to hold the control and call the CenterControl() // constructor passing in this DIV. var centerControlDiv = document.createElement('div'); var centerControl = new CenterControl(centerControlDiv, map); centerControlDiv.index = 1; map.controls[google.maps.ControlPosition.TOP_CENTER].push(centerControlDiv); }
컨트롤에 상태 추가
컨트롤은 상태를 저장할 수도 있습니다. 다음 예시는 전에 보여준 것과 비슷하지만 컨트롤에 새로운 홈 위치를 표시하도록 컨트롤을 설정하는 "Set Home" 버튼이 추가로 포함됩니다. 컨트롤 내에서 home_
속성을 생성하여 이 상태를 저장하고 해당 상태의 getter와 setter를 제공하는 방식으로 진행합니다.
var map; var chicago = {lat: 41.85, lng: -87.65}; /** * The CenterControl adds a control to the map that recenters the map on * Chicago. * @constructor * @param {!Element} controlDiv * @param {!google.maps.Map} map * @param {?google.maps.LatLng} center */ function CenterControl(controlDiv, map, center) { // We set up a variable for this since we're adding event listeners // later. var control = this; // Set the center property upon construction control.center_ = center; controlDiv.style.clear = 'both'; // Set CSS for the control border var goCenterUI = document.createElement('div'); goCenterUI.id = 'goCenterUI'; goCenterUI.title = 'Click to recenter the map'; controlDiv.appendChild(goCenterUI); // Set CSS for the control interior var goCenterText = document.createElement('div'); goCenterText.id = 'goCenterText'; goCenterText.innerHTML = 'Center Map'; goCenterUI.appendChild(goCenterText); // Set CSS for the setCenter control border var setCenterUI = document.createElement('div'); setCenterUI.id = 'setCenterUI'; setCenterUI.title = 'Click to change the center of the map'; controlDiv.appendChild(setCenterUI); // Set CSS for the control interior var setCenterText = document.createElement('div'); setCenterText.id = 'setCenterText'; setCenterText.innerHTML = 'Set Center'; setCenterUI.appendChild(setCenterText); // Set up the click event listener for 'Center Map': Set the center of // the map // to the current center of the control. goCenterUI.addEventListener('click', function() { var currentCenter = control.getCenter(); map.setCenter(currentCenter); }); // Set up the click event listener for 'Set Center': Set the center of // the control to the current center of the map. setCenterUI.addEventListener('click', function() { var newCenter = map.getCenter(); control.setCenter(newCenter); }); } /** * Define a property to hold the center state. * @private */ CenterControl.prototype.center_ = null; /** * Gets the map center. * @return {?google.maps.LatLng} */ CenterControl.prototype.getCenter = function() { return this.center_; }; /** * Sets the map center. * @param {?google.maps.LatLng} center */ CenterControl.prototype.setCenter = function(center) { this.center_ = center; }; function initMap() { map = new google.maps.Map(document.getElementById('map'), { zoom: 12, center: chicago }); // Create the DIV to hold the control and call the CenterControl() // constructor // passing in this DIV. var centerControlDiv = document.createElement('div'); var centerControl = new CenterControl(centerControlDiv, map, chicago); centerControlDiv.index = 1; centerControlDiv.style['padding-top'] = '10px'; map.controls[google.maps.ControlPosition.TOP_CENTER].push(centerControlDiv); }
<div id="map"></div>
/* 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; }
#goCenterUI, #setCenterUI { background-color: #fff; border: 2px solid #fff; border-radius: 3px; box-shadow: 0 2px 6px rgba(0,0,0,.3); cursor: pointer; float: left; margin-bottom: 22px; text-align: center; } #goCenterText, #setCenterText { color: rgb(25,25,25); font-family: Roboto,Arial,sans-serif; font-size: 15px; line-height: 25px; padding-left: 5px; padding-right: 5px; } #setCenterUI { margin-left: 12px; }
<!-- Replace the value of the key parameter with your own API key. --> <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"> </script>
var map; var chicago = {lat: 41.85, lng: -87.65}; /** * The CenterControl adds a control to the map that recenters the map on * Chicago. * @constructor * @param {!Element} controlDiv * @param {!google.maps.Map} map * @param {?google.maps.LatLng} center */ function CenterControl(controlDiv, map, center) { // We set up a variable for this since we're adding event listeners // later. var control = this; // Set the center property upon construction control.center_ = center; controlDiv.style.clear = 'both'; // Set CSS for the control border var goCenterUI = document.createElement('div'); goCenterUI.id = 'goCenterUI'; goCenterUI.title = 'Click to recenter the map'; controlDiv.appendChild(goCenterUI); // Set CSS for the control interior var goCenterText = document.createElement('div'); goCenterText.id = 'goCenterText'; goCenterText.innerHTML = 'Center Map'; goCenterUI.appendChild(goCenterText); // Set CSS for the setCenter control border var setCenterUI = document.createElement('div'); setCenterUI.id = 'setCenterUI'; setCenterUI.title = 'Click to change the center of the map'; controlDiv.appendChild(setCenterUI); // Set CSS for the control interior var setCenterText = document.createElement('div'); setCenterText.id = 'setCenterText'; setCenterText.innerHTML = 'Set Center'; setCenterUI.appendChild(setCenterText); // Set up the click event listener for 'Center Map': Set the center of // the map // to the current center of the control. goCenterUI.addEventListener('click', function() { var currentCenter = control.getCenter(); map.setCenter(currentCenter); }); // Set up the click event listener for 'Set Center': Set the center of // the control to the current center of the map. setCenterUI.addEventListener('click', function() { var newCenter = map.getCenter(); control.setCenter(newCenter); }); } /** * Define a property to hold the center state. * @private */ CenterControl.prototype.center_ = null; /** * Gets the map center. * @return {?google.maps.LatLng} */ CenterControl.prototype.getCenter = function() { return this.center_; }; /** * Sets the map center. * @param {?google.maps.LatLng} center */ CenterControl.prototype.setCenter = function(center) { this.center_ = center; }; function initMap() { map = new google.maps.Map(document.getElementById('map'), { zoom: 12, center: chicago }); // Create the DIV to hold the control and call the CenterControl() // constructor // passing in this DIV. var centerControlDiv = document.createElement('div'); var centerControl = new CenterControl(centerControlDiv, map, chicago); centerControlDiv.index = 1; centerControlDiv.style['padding-top'] = '10px'; map.controls[google.maps.ControlPosition.TOP_CENTER].push(centerControlDiv); }