控制項

選取平台: Android iOS JavaScript

控制項總覽

透過 Maps JavaScript API 顯示的地圖包含 UI 元素,可讓使用者與地圖互動。這些元素稱為「控制項」,您可以在應用程式中加入這些控制項的變化版本。或者,您也可以不進行任何操作,讓 Maps JavaScript API 處理所有控制項行為。

以下為透過 Maps JavaScript API 顯示的地圖預設控制項組合:

您可在地圖中使用的整組控制項包括:

  • 「縮放控制項」會顯示「+」和「-」按鈕,用於變更地圖的縮放等級。根據預設,這個控制項會顯示在地圖的右下角。
  • 「地圖類型控制項」提供下拉式選單或水平按鈕列兩種樣式,可讓使用者選擇地圖類型 (ROADMAPSATELLITEHYBRIDTERRAIN)。根據預設,這個控制項會顯示在地圖左上角。
  • 「街景服務控制項」包含衣夾人圖示,可拖曳到地圖上啟用街景服務。根據預設,這個控制項會顯示在地圖右下方附近。
  • 「旋轉控制項」為包含傾斜圖像的地圖提供一組傾斜和旋轉選項。根據預設,這個控制項會顯示在地圖右下方附近。詳情請參閱「45° 圖像」。
  • 「比例尺控制項」會顯示地圖比例尺元素,且預設為停用。
  • 「全螢幕控制項」提供以全螢幕模式開啟地圖的選項。電腦和行動裝置預設會啟用這個控制項。注意:iOS 裝置不支援全螢幕功能,因此不會顯示全螢幕控制項。
  • 「鍵盤快速鍵控制項」會列出可與地圖互動的鍵盤快速鍵。

您無法直接存取或變更這些地圖控制項,但可以修改地圖的 MapOptions 欄位,這些欄位會影響控制項的顯示設定和呈現方式。您可以在執行地圖個體化時 (使用適當的 MapOptions) 調整控制項的呈現方式,也可以呼叫 setOptions() 變更地圖的選項,藉此動態修改地圖。

在預設情況下,並非所有控制項都會啟用。如要瞭解預設的 UI 行為 (以及如何修改這類行為),請參閱下方的「預設 UI」一節。

預設 UI

根據預設,如果地圖太小 (200 x 200 像素),所有控制項都會隱藏。如要覆寫這項行為,您可以明確將控制項設為可見。請參閱「在地圖中加入控制項」一節。

除了全螢幕控制項以外,其他控制項的行為及外觀在行動裝置和電腦裝置上都相同 (請參閱控制項清單中說明的行為)。

此外,所有裝置都會預設啟用鍵盤處理功能。

停用預設 UI

您可以完全停用 API 的預設 UI 按鈕。方法很簡單,只要將地圖的 disableDefaultUI 屬性 (位於 MapOptions 物件內) 設為 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
}

根據預設,如果地圖小於 200 x 200 像素,所有控制項都會隱藏。如要覆寫這項行為,您可以明確將控制項設為可見。舉例來說,下表顯示在不同地圖尺寸和 zoomControl 欄位的設定中,縮放控制項是否可見。

地圖尺寸 zoomControl 是否可見?
不限 false
不限 true
>= 200 x 200 像素 undefined
< 200 x 200 像素 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 標誌) 的位置重疊,您無法修改 UI 元素的位置。在這些情況下,控制項會根據每個位置的邏輯排列,且盡可能靠近指定的位置。

下例是一張簡易地圖,其中所有控制項都在不同的位置啟用。

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 狀態變更。

如要回應使用者輸入內容,請使用 addEventListener(),該方法會處理支援的 DOM 事件。下列程式碼片段會針對瀏覽器的 '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;
查看範例

試用範例

在控制項中加入狀態

控制項也可以儲存狀態。下例與之前顯示的範例類似,但多了一個「設定住家」按鈕,可將控制項設為顯示新的住家位置。我們的做法是在控制項內建立 home_ 屬性來儲存這個狀態,並提供該狀態適用的 getter 和 setter。

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;
查看範例

試用範例