컨트롤

플랫폼 선택: Android iOS 자바스크립트

컨트롤 개요

Maps JavaScript API를 통해 표시되는 지도에는 사용자와 지도가 상호작용할 수 있는 UI 요소가 포함됩니다. 이러한 요소를 컨트롤이라고 하며 애플리케이션에 이러한 컨트롤의 변형을 포함할 수 있습니다. 또는 아무것도 하지 않고 Maps JavaScript API가 모든 컨트롤 동작을 처리하도록 할 수 있습니다.

다음 지도는 Maps JavaScript API에서 표시하는 기본 컨트롤 집합을 보여줍니다.

다음은 지도에 사용할 수 있는 컨트롤의 전체 목록입니다.

  • 확대/축소 컨트롤은 지도의 확대/축소 수준을 변경할 수 있는 '+' 및 '-' 버튼을 표시합니다. 이 컨트롤은 기본적으로 지도의 오른쪽 하단에 나타납니다.
  • 지도 유형 컨트롤은 드롭다운 또는 가로 버튼 바 스타일로 제공되며 사용자가 이 컨트롤을 사용하여 지도 유형(ROADMAP, SATELLITE, HYBRID 또는 TERRAIN)을 선택할 수 있습니다. 이 컨트롤은 기본적으로 지도의 왼쪽 상단에 표시됩니다.
  • 스트리트 뷰 컨트롤에는 지도에 드래그하여 스트리트 뷰를 사용 설정할 수 있는 페그맨 아이콘이 포함되어 있습니다. 이 컨트롤은 기본적으로 지도의 오른쪽 하단에 표시됩니다.
  • 회전 컨트롤은 비스듬한 이미지가 포함된 지도에 기울기 및 회전 옵션의 조합을 제공합니다. 이 컨트롤은 기본적으로 지도의 오른쪽 하단에 표시됩니다. 자세한 내용은 45° 이미지를 참고하세요.
  • 축척 컨트롤은 지도 축척 요소를 표시합니다. 이 컨트롤은 기본적으로 사용 중지되어 있습니다.
  • 전체 화면 컨트롤은 전체 화면 모드로 지도를 열기 위한 옵션을 제공합니다. 이 컨트롤은 데스크톱과 휴대기기에서 기본적으로 사용 설정되어 있습니다. 참고: iOS는 전체 화면 기능을 지원하지 않습니다. 따라서 iOS 기기에는 전체 화면 컨트롤이 표시되지 않습니다.
  • 단축키 컨트롤은 지도와 상호작용하기 위한 단축키 목록을 표시합니다.

지도 컨트롤에 직접 액세스하거나 컨트롤을 수정하지 마세요. 대신 컨트롤의 가시성과 표시 방식에 영향을 주는 지도의 MapOptions 필드를 수정하세요. (적절한 MapOptions를 사용하여) 지도를 인스턴스화할 때 컨트롤 표시 방식을 조정하거나 setOptions()를 호출하여 지도의 옵션을 변경함으로써 지도를 동적으로 수정할 수 있습니다.

일부 컨트롤은 기본적으로 사용 설정되지 않습니다. 기본 UI 동작 및 이러한 동작을 수정하는 방법에 대한 자세한 내용은 아래의 기본 UI를 참고하세요.

기본 UI

기본적으로, 지도가 너무 작으면(200x200픽셀) 모든 컨트롤이 사라집니다. 컨트롤이 표시되도록 명시적으로 설정하여 이 동작을 재정의할 수 있습니다. 지도에 컨트롤 추가를 참고하세요.

컨트롤의 동작과 모양은 전체 화면 컨트롤을 제외하고 휴대기기와 데스크톱 기기에서 동일합니다(컨트롤 목록에 설명된 동작 참고).

또한 키보드 처리는 기본적으로 모든 기기에서 사용 설정되어 있습니다.

기본 UI 사용 중지

API의 기본 UI 버튼을 전체적으로 사용 중지할 수도 있습니다. 이렇게 하려면 MapOptions 객체 내에서 지도의 disableDefaultUI 속성을 true로 설정하세요. 이 속성은 Maps JavaScript API에서 모든 UI 컨트롤 버튼을 사용 중지합니다. 하지만 각각 gestureHandlingkeyboardShortcuts 속성으로 제어되는 기본 지도의 마우스 동작이나 단축키에는 영향을 미치지 않습니다.

다음 코드는 UI 버튼을 사용 중지합니다.

TypeScript

function initMap(): void {
  const map = new google.maps.Map(
    document.getElementById("map") as HTMLElement,
    {
      zoom: 4,
      center: { lat: -33, lng: 151 },
      disableDefaultUI: true,
    }
  );
}

declare global {
  interface Window {
    initMap: () => void;
  }
}
window.initMap = initMap;

JavaScript

function initMap() {
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 4,
    center: { lat: -33, lng: 151 },
    disableDefaultUI: true,
  });
}

window.initMap = initMap;
예시 보기

샘플 사용해 보기

지도에 컨트롤 추가

UI 동작이나 컨트롤을 제거, 추가 또는 수정하여 인터페이스를 조정하고, 향후 업데이트로 인해 이 동작이 변경되지 않도록 할 수도 있습니다. 기존 동작만 추가하거나 수정하려면 컨트롤을 애플리케이션에 명시적으로 추가해야 합니다.

일부 컨트롤은 기본적으로 지도에 표시되지만 구체적으로 요청하지 않으면 표시되지 않는 컨트롤도 있습니다. 컨트롤 추가 또는 삭제는 다음 MapOptions 객체의 필드에서 지정합니다. 컨트롤을 표시하려면 true로 설정하고 숨기려면 false로 설정합니다.

{
  zoomControl: boolean,
  mapTypeControl: boolean,
  scaleControl: boolean,
  streetViewControl: boolean,
  rotateControl: boolean,
  fullscreenControl: boolean
}

기본적으로 지도가 200x200픽셀보다 작으면 모든 컨트롤이 사라집니다. 컨트롤이 표시되도록 명시적으로 설정하여 이 동작을 재정의할 수 있습니다. 예를 들어 다음 표에는 지도 크기 및 zoomControl 필드의 설정에 따른 확대/축소 컨트롤의 표시 여부가 나와 있습니다.

지도 크기 zoomControl 표시 여부
모두 false 아니요
모두 true
200x200픽셀 이상 undefined
200x200픽셀 미만 undefined 아니요

다음 예에서는 확대/축소 컨트롤을 숨기고 축척 컨트롤을 표시하도록 지도를 설정합니다. 기본 UI를 명시적으로 사용 중지하지 않으므로 이 수정 사항이 기본 UI 동작에 추가됩니다.

TypeScript

function initMap(): void {
  const map = new google.maps.Map(
    document.getElementById("map") as HTMLElement,
    {
      zoom: 4,
      center: { lat: -33, lng: 151 },
      zoomControl: false,
      scaleControl: true,
    }
  );
}

declare global {
  interface Window {
    initMap: () => void;
  }
}
window.initMap = initMap;

JavaScript

function initMap() {
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 4,
    center: { lat: -33, lng: 151 },
    zoomControl: false,
    scaleControl: true,
  });
}

window.initMap = initMap;
예시 보기

샘플 사용해 보기

컨트롤 옵션

몇몇 컨트롤의 경우 구성을 통해 동작이나 모양을 변경할 수 있습니다. 예를 들어 지도 유형 컨트롤은 가로 막대 또는 드롭다운 메뉴로 표시할 수 있습니다.

이러한 컨트롤은 지도를 만들 때 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
  }
  ...

다음 예에서는 컨트롤의 기본 위치와 스타일을 변경하는 방법을 보여줍니다.

TypeScript

// You can set control options to change the default position or style of many
// of the map controls.

function initMap(): void {
  const map = new google.maps.Map(
    document.getElementById("map") as HTMLElement,
    {
      zoom: 4,
      center: { lat: -33, lng: 151 },
      mapTypeControl: true,
      mapTypeControlOptions: {
        style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
        mapTypeIds: ["roadmap", "terrain"],
      },
    }
  );
}

declare global {
  interface Window {
    initMap: () => void;
  }
}
window.initMap = initMap;

JavaScript

// You can set control options to change the default position or style of many
// of the map controls.
function initMap() {
  const 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"],
    },
  });
}

window.initMap = initMap;
예시 보기

샘플 사용해 보기

컨트롤은 일반적으로 지도를 만들 때 구성됩니다. 하지만 MapsetOptions() 메서드를 호출하고 새 컨트롤 옵션을 전달하여 컨트롤의 표시 방식을 동적으로 변경할 수도 있습니다.

컨트롤 수정

지도의 MapOptions 객체 내의 필드를 통해 지도를 만들 때 컨트롤의 표시 방식을 지정합니다. 이러한 필드는 다음과 같습니다.

  • zoomControl은 확대/축소 컨트롤을 사용 설정/사용 중지합니다. 기본적으로 이 컨트롤은 지도의 오른쪽 하단에 표시됩니다. zoomControlOptions 필드는 이 컨트롤에 사용할 ZoomControlOptions를 추가로 지정합니다.
  • mapTypeControl은 사용자가 지도 유형(예: 지도 및 위성) 간에 전환할 수 있는 지도 요형 컨트롤을 사용 설정/사용 중지합니다. 기본적으로 이 컨트롤은 지도의 왼쪽 상단에 표시됩니다. mapTypeControlOptions 필드는 이 컨트롤에 사용할 MapTypeControlOptions를 추가로 지정합니다.
  • streetViewControl은 사용자가 스트리트 뷰 파노라마를 활성화할 수 있는 페그맨 컨트롤을 사용 설정/사용 중지합니다. 기본적으로 이 컨트롤은 지도의 오른쪽 하단에 표시됩니다. streetViewControlOptions 필드는 이 컨트롤에 사용할 StreetViewControlOptions를 추가로 지정합니다.
  • rotateControl은 45° 이미지의 방향을 조정하기 위한 회전 컨트롤의 표시 여부를 지정합니다. 기본적으로 이 컨트롤의 표시 여부는 현재 확대/축소 설정 및 위치에서 지정된 지도 유형의 45° 이미지가 있는지에 따라 결정됩니다. 지도의 rotateControlOptions를 설정하여 사용할 RotateControlOptions를 지정하여 컨트롤의 동작을 변경할 수도 있습니다. 현재 이용 가능한 45° 이미지가 없으면 컨트롤을 표시할 수 없습니다.
  • scaleControl - 간단한 지도 축척을 제공하는 축척 컨트롤을 사용 설정/사용 중지합니다. 기본적으로 이 컨트롤은 표시되지 않습니다. 이 컨트롤은 사용 설정되면 항상 지도의 오른쪽 하단에 표시됩니다. scaleControlOptions는 이 컨트롤에 사용할 ScaleControlOptions를 추가로 지정합니다.
  • fullscreenControl은 지도를 전체 화면 모드로 여는 컨트롤을 사용 설정/사용 중지합니다. 데스크톱 및 Android 기기에서 이 컨트롤은 기본적으로 사용 설정되어 있습니다. 이 컨트롤은 사용 설정되면 지도의 오른쪽 상단에 표시됩니다. fullscreenControlOptions는 이 컨트롤에 사용할 FullscreenControlOptions를 추가로 지정합니다.

초기에 사용 중지하는 컨트롤의 옵션을 지정할 수도 있습니다.

컨트롤 배치

대부분의 컨트롤 옵션에는 지도에서 컨트롤을 배치할 위치를 나타내는 position 속성(ControlPosition 유형)이 포함되어 있습니다. 이러한 컨트롤의 위치는 고정된 것이 아닙니다. 대신 API는 지정된 제약 조건(예: 지도 크기) 내에서 기존 지도 요소 또는 다른 컨트롤 주변에 유동적으로 배치하는 방식으로 컨트롤을 지능적으로 배치합니다.

참고: API에서 컨트롤을 지능적으로 배치하려고 시도하지만 컨트롤이 지정된 복잡한 레이아웃과 겹치지 않는다고 보장할 수는 없습니다.

다음과 같은 컨트롤 위치가 지원됩니다.

  • TOP_CENTER는 지도의 상단 중앙에 컨트롤을 배치해야 함을 나타냅니다.
  • TOP_LEFT는 지도의 왼쪽 상단에 컨트롤을 배치하고, 하위 요소가 있는 경우 상단 중앙을 향해 '유동적으로' 배치해야 함을 나타냅니다.
  • TOP_RIGHT는 지도의 오른쪽 상단에 컨트롤을 배치하고, 하위 요소가 있는 경우 상단 중앙을 향해 '유동적으로' 배치해야 함을 나타냅니다.
  • LEFT_TOP은 지도의 왼쪽 상단, 모든 TOP_LEFT 요소 아래 컨트롤을 배치해야 함을 나타냅니다.
  • RIGHT_TOP은 지도의 오른쪽 상단, 모든 TOP_RIGHT 요소 아래 컨트롤을 배치해야 함을 나타냅니다.
  • LEFT_CENTER는 지도의 왼쪽 TOP_LEFTBOTTOM_LEFT 위치 사이의 중앙에 컨트롤을 배치해야 함을 나타냅니다.
  • RIGHT_CENTER는 지도의 오른쪽 TOP_RIGHTBOTTOM_RIGHT 위치 사이의 중앙에 컨트롤을 배치해야 함을 나타냅니다.
  • LEFT_BOTTOM은 지도의 왼쪽 하단, 모든 BOTTOM_LEFT 요소 위에 컨트롤을 배치해야 함을 나타냅니다.
  • RIGHT_BOTTOM은 지도의 오른쪽 하단, 모든 BOTTOM_RIGHT 요소 위에 컨트롤을 배치해야 함을 나타냅니다.
  • BOTTOM_CENTER는 지도의 하단 중앙에 컨트롤을 배치해야 함을 나타냅니다.
  • BOTTOM_LEFT는 지도의 왼쪽 하단에 컨트롤을 배치하고, 하위 요소가 있는 경우 하단 중앙을 향해 '유동적으로' 배치해야 함을 나타냅니다.
  • BOTTOM_RIGHT는 지도의 오른쪽 하단에 컨트롤을 배치하고, 하위 요소가 있는 경우 하단 중앙을 향해 '유동적으로' 배치해야 함을 나타냅니다.

이 위치는 위치를 수정할 수 없는 UI 요소(예: 저작권 및 Google 로고)의 위치와 겹칠 수도 있습니다. 그러한 경우 컨트롤은 각 위치에 적용된 로직에 따라 유동적으로 배치되고 최대한 지정된 위치에 가깝게 표시됩니다.

다음 예는 모든 컨트롤이 서로 다른 위치에 사용 설정된 간단한 지도를 보여줍니다.

TypeScript

function initMap(): void {
  const map = new google.maps.Map(
    document.getElementById("map") as HTMLElement,
    {
      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,
    }
  );
}

declare global {
  interface Window {
    initMap: () => void;
  }
}
window.initMap = initMap;

JavaScript

function initMap() {
  const 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,
  });
}

window.initMap = initMap;
예시 보기

샘플 사용해 보기

맞춤 컨트롤

기존 API 컨트롤의 스타일과 위치를 수정하는 것은 물론 사용자와의 상호작용을 처리하는 자체 컨트롤을 만들 수 있습니다. 컨트롤은 기본 지도와 함께 움직이는 오버레이와 달리 지도상의 절대 위치에 떠 있는 정지된 위젯입니다. 기본적으로 컨트롤은 지도상의 절대 위치에 있는 <div> 요소로서, 사용자에게 UI를 표시하고 일반적으로 이벤트 핸들러를 통해 사용자 또는 지도와의 상호작용을 처리합니다.

자체 사용자설정 컨트롤을 만들 때는 규칙이 거의 필요하지 않습니다. 하지만 다음 가이드라인을 권장사항으로 참고할 수 있습니다.

  • 표시할 컨트롤 요소를 위한 적절한 CSS를 정의합니다.
  • 지도 속성 변경이나 사용자 이벤트(예: 'click' 이벤트)의 이벤트 핸들러를 통해 사용자 또는 지도와의 상호작용을 처리합니다.
  • <div> 요소를 만들어 컨트롤을 유지하고 이 요소를 Mapcontrols 속성에 추가합니다.

이러한 내용에 대해서는 아래에 설명되어 있습니다.

사용자설정 컨트롤 그리기

컨트롤을 그리는 방법은 여러분에게 달려 있습니다. 일반적으로 컨트롤을 하나의 단위로 다룰 수 있도록 단일 <div> 요소 내에 모든 컨트롤 표시를 배치하는 것이 좋습니다. 아래에 표시된 샘플에서는 이 디자인 패턴을 사용합니다.

매력적인 컨트롤을 디자인하려면 CSS와 DOM 구조에 관한 지식이 필요합니다. 다음 코드는 시카고를 중심으로 하는 지도에서 이동하는 버튼 요소를 만드는 함수를 보여줍니다.

function createCenterControl(map) {
  const controlButton = document.createElement("button");

  // Set CSS for the control.
  controlButton.style.backgroundColor = "#fff";
  controlButton.style.border = "2px solid #fff";
  controlButton.style.borderRadius = "3px";
  controlButton.style.boxShadow = "0 2px 6px rgba(0,0,0,.3)";
  controlButton.style.color = "rgb(25,25,25)";
  controlButton.style.cursor = "pointer";
  controlButton.style.fontFamily = "Roboto,Arial,sans-serif";
  controlButton.style.fontSize = "16px";
  controlButton.style.lineHeight = "38px";
  controlButton.style.margin = "8px 0 22px";
  controlButton.style.padding = "0 5px";
  controlButton.style.textAlign = "center";

  controlButton.textContent = "Center Map";
  controlButton.title = "Click to recenter the map";
  controlButton.type = "button";

  // Setup the click event listeners: simply set the map to Chicago.
  controlButton.addEventListener("click", () => {
    map.setCenter(chicago);
  });

  return controlButton;
}

사용자설정 컨트롤의 이벤트 처리

컨트롤은 실제로 기능이 있어야 유용합니다. 컨트롤의 동작은 여러분이 결정합니다. 컨트롤은 사용자 입력에 응답하거나 Map의 상태 변화에 응답할 수 있습니다.

사용자 입력에 응답하려면 지원되는 DOM 이벤트를 처리하는 addEventListener()를 사용합니다. 다음 코드 스니펫에서는 브라우저의 'click' 이벤트에 대한 리스너를 추가합니다. 이 이벤트는 지도가 아니라 DOM에서 수신됩니다.

// Setup the click event listener: set the map to center on Chicago
var chicago = {lat: 41.850, lng: -87.650};

controlButton.addEventListener('click', () => {
  map.setCenter(chicago);
});

사용자설정 컨트롤의 접근성 강화

컨트롤이 키보드 이벤트를 수신하고 스크린 리더에 올바르게 표시되도록 하려면 다음 안내를 따르세요.

  • 버튼, 양식 요소, 라벨에는 항상 기본 HTML 요소를 사용합니다. DIV 요소는 기본 컨트롤을 담는 컨테이너로만 사용하세요. DIV를 대화형 UI 요소로 재사용해서는 안 됩니다.
  • 필요한 경우 label 요소, title 속성 또는 aria-label 속성을 사용하여 UI 요소에 관한 정보를 제공합니다.

사용자설정 컨트롤 배치

사용자설정 컨트롤은 Map 객체의 controls 속성 내 적절한 위치에 배치하여 지도에 배치합니다. 이 속성에는 google.maps.ControlPosition의 배열이 포함됩니다. Node(일반적으로 <div>)를 적절한 ControlPosition에 추가하여 사용자설정 컨트롤을 지도에 추가합니다. 이러한 위치에 관한 자세한 내용은 위의 컨트롤 배치를 참고하세요.

ControlPosition은 해당 위치에 표시된 컨트롤의 MVCArray를 저장합니다. 따라서 위치에 컨트롤이 추가되거나 삭제되면 이에 따라 API가 컨트롤을 업데이트합니다.

API는 index 속성의 순서에 따라 각 위치에 컨트롤을 배치합니다. 더 낮은 색인의 컨트롤이 먼저 배치됩니다. 예를 들어 BOTTOM_RIGHT 위치의 두 사용자설정 컨트롤은 이 색인 순서에 따라 색인 값이 낮은 컨트롤부터 배치됩니다. 기본적으로 모든 사용자설정 컨트롤은 API 기본 컨트롤이 배치된 후에 배치됩니다. 컨트롤의 index 속성을 음수 값으로 설정하여 이 동작을 재정의할 수 있습니다. 사용자설정 컨트롤은 로고의 왼쪽이나 저작권의 오른쪽에 배치할 수 없습니다.

다음 코드는 새 사용자설정 컨트롤(생성자가 표시되지 않음)을 만들어 지도의 TOP_RIGHT 위치에 추가합니다.

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

// Create a DIV to attach the control UI to the Map.
const centerControlDiv = document.createElement("div");

// Create the control. This code calls a function that
// creates a new instance of a button control.
const centerControl = createCenterControl(map);

// Append the control to the DIV.
centerControlDiv.appendChild(centerControl);

// 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_CENTER].push(centerControlDiv);

사용자설정 컨트롤 예

다음 컨트롤은 (특별히 유용하지는 않지만) 간단하고 위에 표시된 패턴을 결합합니다. 이 컨트롤은 지도의 중심을 특정 기본 위치에 설정하여 DOM 'click' 이벤트에 응답합니다.

TypeScript

let map: google.maps.Map;

const chicago = { lat: 41.85, lng: -87.65 };

/**
 * Creates a control that recenters the map on Chicago.
 */
 function createCenterControl(map) {
  const controlButton = document.createElement('button');

  // Set CSS for the control.
  controlButton.style.backgroundColor = '#fff';
  controlButton.style.border = '2px solid #fff';
  controlButton.style.borderRadius = '3px';
  controlButton.style.boxShadow = '0 2px 6px rgba(0,0,0,.3)';
  controlButton.style.color = 'rgb(25,25,25)';
  controlButton.style.cursor = 'pointer';
  controlButton.style.fontFamily = 'Roboto,Arial,sans-serif';
  controlButton.style.fontSize = '16px';
  controlButton.style.lineHeight = '38px';
  controlButton.style.margin = '8px 0 22px';
  controlButton.style.padding = '0 5px';
  controlButton.style.textAlign = 'center';

  controlButton.textContent = 'Center Map';
  controlButton.title = 'Click to recenter the map';
  controlButton.type = 'button';

  // Setup the click event listeners: simply set the map to Chicago.
  controlButton.addEventListener('click', () => {
    map.setCenter(chicago);
  });

  return controlButton;
}

function initMap() {
  map = new google.maps.Map(document.getElementById('map') as HTMLElement, {
    zoom: 12,
    center: chicago,
  });

  // Create the DIV to hold the control.
  const centerControlDiv = document.createElement('div');
  // Create the control.
  const centerControl = createCenterControl(map);
  // Append the control to the DIV.
  centerControlDiv.appendChild(centerControl);

  map.controls[google.maps.ControlPosition.TOP_CENTER].push(centerControlDiv);
}

declare global {
  interface Window {
    initMap: () => void;
  }
}
window.initMap = initMap;

JavaScript

let map;
const chicago = { lat: 41.85, lng: -87.65 };

/**
 * Creates a control that recenters the map on Chicago.
 */
function createCenterControl(map) {
  const controlButton = document.createElement("button");

  // Set CSS for the control.
  controlButton.style.backgroundColor = "#fff";
  controlButton.style.border = "2px solid #fff";
  controlButton.style.borderRadius = "3px";
  controlButton.style.boxShadow = "0 2px 6px rgba(0,0,0,.3)";
  controlButton.style.color = "rgb(25,25,25)";
  controlButton.style.cursor = "pointer";
  controlButton.style.fontFamily = "Roboto,Arial,sans-serif";
  controlButton.style.fontSize = "16px";
  controlButton.style.lineHeight = "38px";
  controlButton.style.margin = "8px 0 22px";
  controlButton.style.padding = "0 5px";
  controlButton.style.textAlign = "center";
  controlButton.textContent = "Center Map";
  controlButton.title = "Click to recenter the map";
  controlButton.type = "button";
  // Setup the click event listeners: simply set the map to Chicago.
  controlButton.addEventListener("click", () => {
    map.setCenter(chicago);
  });
  return controlButton;
}

function initMap() {
  map = new google.maps.Map(document.getElementById("map"), {
    zoom: 12,
    center: chicago,
  });

  // Create the DIV to hold the control.
  const centerControlDiv = document.createElement("div");
  // Create the control.
  const centerControl = createCenterControl(map);

  // Append the control to the DIV.
  centerControlDiv.appendChild(centerControl);
  map.controls[google.maps.ControlPosition.TOP_CENTER].push(centerControlDiv);
}

window.initMap = initMap;
예시 보기

샘플 사용해 보기

컨트롤에 상태 추가

컨트롤은 상태를 저장할 수도 있습니다. 다음 예는 위에 표시된 예와 비슷하지만 새로운 홈 위치를 표시하도록 컨트롤을 설정하는 추가 '홈 설정' 버튼이 컨트롤에 포함됩니다. 이렇게 하려면 이 상태를 저장하고 해당 상태에 대한 getters 및 setters를 제공하기 위한 home_ 속성을 컨트롤 내에 만듭니다.

TypeScript

let map: google.maps.Map;

const chicago: google.maps.LatLngLiteral = { lat: 41.85, lng: -87.65 };

/**
 * The CenterControl adds a control to the map that recenters the map on
 * Chicago.
 */
class CenterControl {
  private map_: google.maps.Map;
  private center_: google.maps.LatLng;
  constructor(
    controlDiv: HTMLElement,
    map: google.maps.Map,
    center: google.maps.LatLngLiteral
  ) {
    this.map_ = map;
    // Set the center property upon construction
    this.center_ = new google.maps.LatLng(center);
    controlDiv.style.clear = "both";

    // Set CSS for the control border
    const goCenterUI = document.createElement("button");

    goCenterUI.id = "goCenterUI";
    goCenterUI.title = "Click to recenter the map";
    controlDiv.appendChild(goCenterUI);

    // Set CSS for the control interior
    const goCenterText = document.createElement("div");

    goCenterText.id = "goCenterText";
    goCenterText.innerHTML = "Center Map";
    goCenterUI.appendChild(goCenterText);

    // Set CSS for the setCenter control border
    const setCenterUI = document.createElement("button");

    setCenterUI.id = "setCenterUI";
    setCenterUI.title = "Click to change the center of the map";
    controlDiv.appendChild(setCenterUI);

    // Set CSS for the control interior
    const 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", () => {
      const currentCenter = this.center_;

      this.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", () => {
      const newCenter = this.map_.getCenter()!;

      if (newCenter) {
        this.center_ = newCenter;
      }
    });
  }
}

function initMap(): void {
  map = new google.maps.Map(document.getElementById("map") as HTMLElement, {
    zoom: 12,
    center: chicago,
  });

  // Create the DIV to hold the control and call the CenterControl()
  // constructor passing in this DIV.
  const centerControlDiv = document.createElement("div");
  const control = new CenterControl(centerControlDiv, map, chicago);

  // @ts-ignore
  centerControlDiv.index = 1;
  centerControlDiv.style.paddingTop = "10px";
  map.controls[google.maps.ControlPosition.TOP_CENTER].push(centerControlDiv);
}

declare global {
  interface Window {
    initMap: () => void;
  }
}
window.initMap = initMap;

JavaScript

let map;
const chicago = { lat: 41.85, lng: -87.65 };

/**
 * The CenterControl adds a control to the map that recenters the map on
 * Chicago.
 */
class CenterControl {
  map_;
  center_;
  constructor(controlDiv, map, center) {
    this.map_ = map;
    // Set the center property upon construction
    this.center_ = new google.maps.LatLng(center);
    controlDiv.style.clear = "both";

    // Set CSS for the control border
    const goCenterUI = document.createElement("button");

    goCenterUI.id = "goCenterUI";
    goCenterUI.title = "Click to recenter the map";
    controlDiv.appendChild(goCenterUI);

    // Set CSS for the control interior
    const goCenterText = document.createElement("div");

    goCenterText.id = "goCenterText";
    goCenterText.innerHTML = "Center Map";
    goCenterUI.appendChild(goCenterText);

    // Set CSS for the setCenter control border
    const setCenterUI = document.createElement("button");

    setCenterUI.id = "setCenterUI";
    setCenterUI.title = "Click to change the center of the map";
    controlDiv.appendChild(setCenterUI);

    // Set CSS for the control interior
    const 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", () => {
      const currentCenter = this.center_;

      this.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", () => {
      const newCenter = this.map_.getCenter();

      if (newCenter) {
        this.center_ = newCenter;
      }
    });
  }
}

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.
  const centerControlDiv = document.createElement("div");
  const control = new CenterControl(centerControlDiv, map, chicago);

  // @ts-ignore
  centerControlDiv.index = 1;
  centerControlDiv.style.paddingTop = "10px";
  map.controls[google.maps.ControlPosition.TOP_CENTER].push(centerControlDiv);
}

window.initMap = initMap;
예시 보기

샘플 사용해 보기