資料層

選取平台: Android iOS JavaScript

Google 地圖資料層提供可存放任意地理空間資料的容器。您可以使用資料層來儲存自訂資料,或是在 Google 地圖上顯示 GeoJSON 資料。

總覽

請觀看這部 DevBytes 影片,進一步瞭解資料層。

您可以透過 Maps JavaScript API,使用標記、折線、多邊形等多種疊加層來標記地圖。上述每則註解都會結合樣式資訊與位置資料。google.maps.Data 類別是可存放任意地理空間資料的容器。您可以使用資料層在地圖中加入任意地理資料,而不需要加入這些疊加層。如果資料含有幾何圖形 (例如點、線或多邊形),API 預設會將這些幾何圖形轉換成標記、折線和多邊形。您可以比照一般疊加層設定這些地圖項目的樣式,也可以根據資料集所含的其他屬性套用樣式規則。

google.maps.Data 類別可讓您:

  • 在地圖上繪製多邊形。
  • 在地圖中加入 GeoJSON 資料。
    GeoJSON 是網際網路上地理空間資料的標準。Data 類別依照 GeoJSON 的結構呈現資料,可讓您輕鬆顯示 GeoJSON 資料。使用 loadGeoJson() 方法即可輕鬆匯入 GeoJSON 資料,以及顯示點、線串和多邊形。
  • 使用 google.maps.Data 即可建立任意資料的模型。
    現實生活中大多數的實體都有相關聯的其他屬性。舉例來說,商店有營業時間、道路有車流速度,而每個女童軍團都有銷售餅乾的草坪。您可以透過 google.maps.Data 建立這些屬性的模型,然後據此設定資料樣式。
  • 選擇資料的呈現方式隨時都能改變想法
    資料層可讓您決定資料的視覺化呈現和互動方式。舉例來說,在查看便利商店地圖時,您可以選擇只顯示銷售大眾運輸票券的商店。

繪製多邊形

Data.Polygon 類別可為您處理多邊形環繞的情況。您可以將一或多個線性環陣列 (定義為經緯度座標) 傳遞給這個類別。第一個線性環定義多邊形的外邊界。如果您傳遞多個線性環,可以使用第二個和後續的線性環來定義多邊形的內部路徑 (孔)。

以下範例一個長方形的多邊形,其中含有兩個孔:

TypeScript

// This example uses the Google Maps JavaScript API's Data layer
// to create a rectangular polygon with 2 holes in it.

function initMap(): void {
  const map = new google.maps.Map(
    document.getElementById("map") as HTMLElement,
    {
      zoom: 6,
      center: { lat: -33.872, lng: 151.252 },
    }
  );

  // Define the LatLng coordinates for the outer path.
  const outerCoords = [
    { lat: -32.364, lng: 153.207 }, // north west
    { lat: -35.364, lng: 153.207 }, // south west
    { lat: -35.364, lng: 158.207 }, // south east
    { lat: -32.364, lng: 158.207 }, // north east
  ];

  // Define the LatLng coordinates for an inner path.
  const innerCoords1 = [
    { lat: -33.364, lng: 154.207 },
    { lat: -34.364, lng: 154.207 },
    { lat: -34.364, lng: 155.207 },
    { lat: -33.364, lng: 155.207 },
  ];

  // Define the LatLng coordinates for another inner path.
  const innerCoords2 = [
    { lat: -33.364, lng: 156.207 },
    { lat: -34.364, lng: 156.207 },
    { lat: -34.364, lng: 157.207 },
    { lat: -33.364, lng: 157.207 },
  ];

  map.data.add({
    geometry: new google.maps.Data.Polygon([
      outerCoords,
      innerCoords1,
      innerCoords2,
    ]),
  });
}

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

JavaScript

// This example uses the Google Maps JavaScript API's Data layer
// to create a rectangular polygon with 2 holes in it.
function initMap() {
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 6,
    center: { lat: -33.872, lng: 151.252 },
  });
  // Define the LatLng coordinates for the outer path.
  const outerCoords = [
    { lat: -32.364, lng: 153.207 },
    { lat: -35.364, lng: 153.207 },
    { lat: -35.364, lng: 158.207 },
    { lat: -32.364, lng: 158.207 }, // north east
  ];
  // Define the LatLng coordinates for an inner path.
  const innerCoords1 = [
    { lat: -33.364, lng: 154.207 },
    { lat: -34.364, lng: 154.207 },
    { lat: -34.364, lng: 155.207 },
    { lat: -33.364, lng: 155.207 },
  ];
  // Define the LatLng coordinates for another inner path.
  const innerCoords2 = [
    { lat: -33.364, lng: 156.207 },
    { lat: -34.364, lng: 156.207 },
    { lat: -34.364, lng: 157.207 },
    { lat: -33.364, lng: 157.207 },
  ];

  map.data.add({
    geometry: new google.maps.Data.Polygon([
      outerCoords,
      innerCoords1,
      innerCoords2,
    ]),
  });
}

window.initMap = initMap;

載入 GeoJSON

GeoJSON 是在網際網路上分享地理空間資料的常見標準。這個標準十分簡潔,讓人一看就懂,因此很適合在分享和協作時使用。透過資料層,只要使用一行程式碼,就能在 Google 地圖中加入 GeoJSON 資料。

map.data.loadGeoJson('google.json');

每張地圖都有 map.data 物件,可做為存放任意地理空間資料 (包括 GeoJSON) 的資料層。如要載入並顯示 GeoJSON 檔案,您可以呼叫 data 物件的 loadGeoJSON() 方法。以下範例說明如何加入地圖並載入外部 GeoJSON 資料。

TypeScript

let map: google.maps.Map;

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

  // NOTE: This uses cross-domain XHR, and may not work on older browsers.
  map.data.loadGeoJson(
    "https://storage.googleapis.com/mapsdevsite/json/google.json"
  );
}

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

JavaScript

let map;

function initMap() {
  map = new google.maps.Map(document.getElementById("map"), {
    zoom: 4,
    center: { lat: -28, lng: 137 },
  });
  // NOTE: This uses cross-domain XHR, and may not work on older browsers.
  map.data.loadGeoJson(
    "https://storage.googleapis.com/mapsdevsite/json/google.json"
  );
}

window.initMap = initMap;
查看範例

試用範例

GeoJSON 範例

本頁大部分的範例都是使用常見的 GeoJSON 檔案。這個檔案將「Google」六個字定義為覆蓋在澳洲上的多邊形。測試資料層時,歡迎複製或修改這個檔案。

注意:如要從其他網域載入 JSON 檔案,該網域必須已啟用跨來源資源共享功能。

展開 google.json 旁的小箭頭,下方即會顯示檔案全文。

google.json

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {
        "letter": "G",
        "color": "blue",
        "rank": "7",
        "ascii": "71"
      },
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [123.61, -22.14], [122.38, -21.73], [121.06, -21.69], [119.66, -22.22], [119.00, -23.40],
            [118.65, -24.76], [118.43, -26.07], [118.78, -27.56], [119.22, -28.57], [120.23, -29.49],
            [121.77, -29.87], [123.57, -29.64], [124.45, -29.03], [124.71, -27.95], [124.80, -26.70],
            [124.80, -25.60], [123.61, -25.64], [122.56, -25.64], [121.72, -25.72], [121.81, -26.62],
            [121.86, -26.98], [122.60, -26.90], [123.57, -27.05], [123.57, -27.68], [123.35, -28.18],
            [122.51, -28.38], [121.77, -28.26], [121.02, -27.91], [120.49, -27.21], [120.14, -26.50],
            [120.10, -25.64], [120.27, -24.52], [120.67, -23.68], [121.72, -23.32], [122.43, -23.48],
            [123.04, -24.04], [124.54, -24.28], [124.58, -23.20], [123.61, -22.14]
          ]
        ]
      }
    },
    {
      "type": "Feature",
      "properties": {
        "letter": "o",
        "color": "red",
        "rank": "15",
        "ascii": "111"
      },
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [128.84, -25.76], [128.18, -25.60], [127.96, -25.52], [127.88, -25.52], [127.70, -25.60],
            [127.26, -25.79], [126.60, -26.11], [126.16, -26.78], [126.12, -27.68], [126.21, -28.42],
            [126.69, -29.49], [127.74, -29.80], [128.80, -29.72], [129.41, -29.03], [129.72, -27.95],
            [129.68, -27.21], [129.33, -26.23], [128.84, -25.76]
          ],
          [
            [128.45, -27.44], [128.32, -26.94], [127.70, -26.82], [127.35, -27.05], [127.17, -27.80],
            [127.57, -28.22], [128.10, -28.42], [128.49, -27.80], [128.45, -27.44]
          ]
        ]
      }
    },
    {
      "type": "Feature",
      "properties": {
        "letter": "o",
        "color": "yellow",
        "rank": "15",
        "ascii": "111"
      },
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [131.87, -25.76], [131.35, -26.07], [130.95, -26.78], [130.82, -27.64], [130.86, -28.53],
            [131.26, -29.22], [131.92, -29.76], [132.45, -29.87], [133.06, -29.76], [133.72, -29.34],
            [134.07, -28.80], [134.20, -27.91], [134.07, -27.21], [133.81, -26.31], [133.37, -25.83],
            [132.71, -25.64], [131.87, -25.76]
          ],
          [
            [133.15, -27.17], [132.71, -26.86], [132.09, -26.90], [131.74, -27.56], [131.79, -28.26],
            [132.36, -28.45], [132.93, -28.34], [133.15, -27.76], [133.15, -27.17]
          ]
        ]
      }
    },
    {
      "type": "Feature",
      "properties": {
        "letter": "g",
        "color": "blue",
        "rank": "7",
        "ascii": "103"
      },
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [138.12, -25.04], [136.84, -25.16], [135.96, -25.36], [135.26, -25.99], [135, -26.90],
            [135.04, -27.91], [135.26, -28.88], [136.05, -29.45], [137.02, -29.49], [137.81, -29.49],
            [137.94, -29.99], [137.90, -31.20], [137.85, -32.24], [136.88, -32.69], [136.45, -32.36],
            [136.27, -31.80], [134.95, -31.84], [135.17, -32.99], [135.52, -33.43], [136.14, -33.76],
            [137.06, -33.83], [138.12, -33.65], [138.86, -33.21], [139.30, -32.28], [139.30, -31.24],
            [139.30, -30.14], [139.21, -28.96], [139.17, -28.22], [139.08, -27.41], [139.08, -26.47],
            [138.99, -25.40], [138.73, -25.00 ], [138.12, -25.04]
          ],
          [
            [137.50, -26.54], [136.97, -26.47], [136.49, -26.58], [136.31, -27.13], [136.31, -27.72],
            [136.58, -27.99], [137.50, -28.03], [137.68, -27.68], [137.59, -26.78], [137.50, -26.54]
          ]
        ]
      }
    },
    {
      "type": "Feature",
      "properties": {
        "letter": "l",
        "color": "green",
        "rank": "12",
        "ascii": "108"
      },
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [140.14,-21.04], [140.31,-29.42], [141.67,-29.49], [141.59,-20.92], [140.14,-21.04]
          ]
        ]
      }
    },
    {
      "type": "Feature",
      "properties": {
        "letter": "e",
        "color": "red",
        "rank": "5",
        "ascii": "101"
      },
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [144.14, -27.41], [145.67, -27.52], [146.86, -27.09], [146.82, -25.64], [146.25, -25.04],
            [145.45, -24.68], [144.66, -24.60], [144.09, -24.76], [143.43, -25.08], [142.99, -25.40],
            [142.64, -26.03], [142.64, -27.05], [142.64, -28.26], [143.30, -29.11], [144.18, -29.57],
            [145.41, -29.64], [146.46, -29.19], [146.64, -28.72], [146.82, -28.14], [144.84, -28.42],
            [144.31, -28.26], [144.14, -27.41]
          ],
          [
            [144.18, -26.39], [144.53, -26.58], [145.19, -26.62], [145.72, -26.35], [145.81, -25.91],
            [145.41, -25.68], [144.97, -25.68], [144.49, -25.64], [144, -25.99], [144.18, -26.39]
          ]
        ]
      }
    }
  ]
}

設定 GeoJSON 資料樣式

使用 Data.setStyle() 方法即可指定資料的呈現方式。setStyle() 方法會採用 StyleOptions 物件常值,或是用於計算各個地圖項目樣式的函式。

簡易樣式規則

要設定地圖項目樣式,最簡單的方法就是將 StyleOptions 物件常值傳遞至 setStyle()。這樣就能為集合中的每個地圖項目設定單一樣式。請注意,每種地圖項目只能算繪一部分的可用選項。換言之,您可以在單一物件常值中合併各種地圖項目的樣式。舉例來說,下方程式碼片段同時設定只影響點幾何圖形的自訂 icon,以及只影響多邊形的 fillColor

map.data.setStyle({
  icon: '//example.com/path/to/image.png',
  fillColor: 'green'
});

如要進一步瞭解有效樣式/地圖項目組合,請參閱「樣式選項」一文。

以下範例說明如何使用 StyleOptions 物件常值,設定多個地圖項目的筆觸線條和填滿顏色。請注意,每個多邊形的樣式都相同。

// Set the stroke width, and fill color for each polygon
map.data.setStyle({
  fillColor: 'green',
  strokeWeight: 1
});

宣告式樣式規則

如果您想更新大量疊加層 (例如標記或折線) 的樣式,通常必須先在地圖上反覆建立每個疊加層,並分別設定樣式。只要使用資料層,即可透過宣告方式設定規則,並套用至整個資料集。資料或規則更新完成後,樣式就會自動套用至各個地圖項目。您可以使用地圖項目屬性來自訂樣式。

舉例來說,下方程式碼會檢查 google.json 中每個字元在 ASCII 字元集的位置,以便分別為這些字元設定顏色。在本例中,我們已將字元位置連同資料一併編碼。

// Color Capital letters blue, and lower case letters red.
// Capital letters are represented in ascii by values less than 91
map.data.setStyle(function(feature) {
    var ascii = feature.getProperty('ascii');
    var color = ascii > 91 ? 'red' : 'blue';
    return {
      fillColor: color,
      strokeWeight: 1
    };
});

移除樣式

如要移除任何已套用的樣式,請將空白物件常值傳遞至 setStyles() 方法。

// Remove custom styles.
map.data.setStyle({});

這樣會移除您指定的所有自訂樣式,而地圖項目會使用預設樣式進行算繪。如果您不想再算繪這些地圖項目,請將 StyleOptionsvisible 屬性設為 false

// Hide the Data layer.
map.data.setStyle({visible: false});

覆寫預設樣式

樣式規則通常會套用至資料層中的每個地圖項目。不過,有時您可能會想將特殊樣式規則套用至特定地圖項目,例如在使用者點擊時突顯某個地圖項目。

如要套用特殊樣式規則,請使用 overrideStyle() 方法。除了已在 setStyle() 中指定的全域樣式外,系統也會套用透過 overrideStyle() 方法變更的所有屬性。舉例來說,下方程式碼會在使用者點擊時變更多邊形的填滿顏色,但不會設定任何其他樣式。

// Set the global styles.
map.data.setStyle({
  fillColor: 'green',
  strokeWeight: 3
});

// Set the fill color to red when the feature is clicked.
// Stroke weight remains 3.
map.data.addListener('click', function(event) {
   map.data.overrideStyle(event.feature, {fillColor: 'red'});
});

呼叫 revertStyle() 方法即可移除所有樣式覆寫。

樣式選項

為每個地圖項目設定樣式時可用的選項,取決於地圖項目類型。舉例來說,fillColor 只會顯示在多邊形幾何圖形上,而 icon 只會顯示在點幾何圖形上。詳情請參閱 StyleOptions 的參考說明文件。

適用於所有幾何圖形

  • clickable:如果為 true,這個地圖項目就會接收滑鼠和觸控事件
  • visible:如果為 true,地圖項目就會顯示。
  • zIndex:所有地圖項目皆按照 zIndex 順序顯示在地圖上,值較高的地圖項目會比值較低的地圖項目優先顯示。標記一律會顯示在線串和多邊形的前方。

適用於點幾何圖形

  • cursor:懸停時要顯示的滑鼠游標。
  • icon:針對點幾何圖形顯示的圖示。
  • shape:定義用於偵測命中的圖片點擊區。
  • title:滑鼠游標懸停效果文字。

適用於線幾何圖形

  • strokeColor:筆觸顏色。系統支援所有 CSS3 顏色,延伸的具名顏色除外。
  • strokeOpacity:筆觸不透明度,範圍介於 0.0 和 1.0 之間。
  • strokeWeight:筆觸寬度 (以像素為單位)。

適用於多邊形幾何圖形

  • fillColor:填滿顏色。系統支援所有 CSS3 顏色,延伸的具名顏色除外。
  • fillOpacity:填滿不透明度,範圍介於 0.01.0. 之間
  • strokeColor:筆觸顏色。系統支援所有 CSS3 顏色,延伸的具名顏色除外。
  • strokeOpacity:筆觸不透明度,範圍介於 0.0 和 1.0 之間。
  • strokeWeight:筆觸寬度 (以像素為單位)。

新增事件處理常式

地圖項目會回應事件,例如 mouseupmousedown。您可以新增事件監聽器,讓使用者能在地圖上與資料互動。在下例中,我們新增滑鼠游標懸停事件,讓地圖項目相關資訊顯示在滑鼠游標下方。

// Set mouseover event for each feature.
map.data.addListener('mouseover', function(event) {
  document.getElementById('info-box').textContent =
      event.feature.getProperty('letter');
});

資料層事件

以下是所有地圖項目常見的事件 (不受幾何圖形類型影響):

  • addfeature
  • click
  • dblclick
  • mousedown
  • mouseout
  • mouseover
  • mouseup
  • removefeature
  • removeproperty
  • rightclick
  • setgeometry
  • setproperty

如要進一步瞭解這些事件,請參閱 google.maps.data 類別的參考說明文件。

動態變更外觀

如要設定資料層的樣式,您可以將計算每個地圖項目樣式的函式傳遞至 google.maps.data.setStyle() 方法。每當地圖項目的屬性更新時,系統就會呼叫這個函式。

在下例中,我們為 click 事件新增事件監聽器,以便更新地圖項目 isColorful。屬性設定完成後,系統會按照上述變更內容更新地圖項目樣式。

// Color each letter gray. Change the color when the isColorful property
// is set to true.
map.data.setStyle(function(feature) {
  var color = 'gray';
  if (feature.getProperty('isColorful')) {
    color = feature.getProperty('color');
  }
  return /** @type {!google.maps.Data.StyleOptions} */({
    fillColor: color,
    strokeColor: color,
    strokeWeight: 2
  });
});

// When the user clicks, set 'isColorful', changing the color of the letters.
map.data.addListener('click', function(event) {
  event.feature.setProperty('isColorful', true);
});

// When the user hovers, tempt them to click by outlining the letters.
// Call revertStyle() to remove all overrides. This will use the style rules
// defined in the function passed to setStyle()
map.data.addListener('mouseover', function(event) {
  map.data.revertStyle();
  map.data.overrideStyle(event.feature, {strokeWeight: 8});
});

map.data.addListener('mouseout', function(event) {
  map.data.revertStyle();
});