將資料匯入 Google 地圖

總覽

瞭解如何從本機或遠端來源匯入 GeoJSON 資料,並在地圖上顯示。本教學課程使用下方地圖說明將資料匯入地圖的各種技術。

下方是您在本教學課程中建立地圖時所需的完整程式碼。

TypeScript

let map: google.maps.Map;

function initMap(): void {
  map = new google.maps.Map(document.getElementById("map") as HTMLElement, {
    zoom: 2,
    center: new google.maps.LatLng(2.8, -187.3),
    mapTypeId: "terrain",
  });

  // Create a <script> tag and set the USGS URL as the source.
  const script = document.createElement("script");

  // This example uses a local copy of the GeoJSON stored at
  // http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojsonp
  script.src =
    "https://developers.google.com/maps/documentation/javascript/examples/json/earthquake_GeoJSONP.js";
  document.getElementsByTagName("head")[0].appendChild(script);
}

// Loop through the results array and place a marker for each
// set of coordinates.
const eqfeed_callback = function (results: any) {
  for (let i = 0; i < results.features.length; i++) {
    const coords = results.features[i].geometry.coordinates;
    const latLng = new google.maps.LatLng(coords[1], coords[0]);

    new google.maps.Marker({
      position: latLng,
      map: map,
    });
  }
};

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

JavaScript

let map;

function initMap() {
  map = new google.maps.Map(document.getElementById("map"), {
    zoom: 2,
    center: new google.maps.LatLng(2.8, -187.3),
    mapTypeId: "terrain",
  });

  // Create a <script> tag and set the USGS URL as the source.
  const script = document.createElement("script");

  // This example uses a local copy of the GeoJSON stored at
  // http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojsonp
  script.src =
    "https://developers.google.com/maps/documentation/javascript/examples/json/earthquake_GeoJSONP.js";
  document.getElementsByTagName("head")[0].appendChild(script);
}

// Loop through the results array and place a marker for each
// set of coordinates.
const eqfeed_callback = function (results) {
  for (let i = 0; i < results.features.length; i++) {
    const coords = results.features[i].geometry.coordinates;
    const latLng = new google.maps.LatLng(coords[1], coords[0]);

    new google.maps.Marker({
      position: latLng,
      map: map,
    });
  }
};

window.initMap = initMap;
window.eqfeed_callback = eqfeed_callback;

CSS

/*
 * 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;
}

HTML

<html>
  <head>
    <title>Earthquake Markers</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>

    <link rel="stylesheet" type="text/css" href="./style.css" />
    <script type="module" src="./index.js"></script>
  </head>
  <body>
    <div id="map"></div>

    <!--
      The `defer` attribute causes the callback to execute after the full HTML
      document has been parsed. For non-blocking uses, avoiding race conditions,
      and consistent behavior across browsers, consider loading using Promises.
      See https://developers.google.com/maps/documentation/javascript/load-maps-js-api
      for more information.
      -->
    <script
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initMap&v=weekly"
      defer
    ></script>
  </body>
</html>

試用範例

載入資料

這個部分說明如何從 Maps JavaScript API 應用程式所在網域或其他網域載入資料。

從相同網域載入資料

Google 地圖資料層提供可存放任意地理空間資料 (包括 GeoJSON) 的容器。如果資料所屬的檔案代管在 Maps JavaScript API 應用程式所在網域上,您可以使用 map.data.loadGeoJson() 方法載入資料。檔案必須位於相同網域上,但您可以將檔案代管在不同的子網域中。舉例來說,您可以從 www.example.comfiles.example.com 發出要求。

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

跨網域載入資料

如果網域的設定允許這類要求,您也可以從非自有網域要求資料。這項權限的標準稱為跨源資源共享 (CORS)。如果網域允許跨網域要求,回應標頭應包含下列宣告:

Access-Control-Allow-Origin: *

請使用 Chrome 開發人員工具確認網域是否已啟用 CORS。

從這類網域載入資料與從相同網域載入 JSON 的做法相同:

map.data.loadGeoJson('http://www.CORS-ENABLED-SITE.com/data.json');

要求 JSONP

目標網域必須支援 JSONP 要求,才能使用這項技術。

如要要求 JSONP,請使用 createElement() 在文件標題中新增 script 標記。

var script = document.createElement('script');
script.src = 'http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojsonp';
document.getElementsByTagName('head')[0].appendChild(script);

指令碼執行時,目標網域會將資料做為引數傳送至「其他」指令碼,通常名為 callback()。目標網域會定義回呼指令碼名稱,這是在瀏覽器中載入目標網址時,網頁上的第一個名稱。

例如,如果在瀏覽器視窗中載入http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojsonp,顯示的回呼名稱為 eqfeed_callback

您必須在程式碼中定義回呼指令碼:

function eqfeed_callback(response) {
  map.data.addGeoJson(response);
}

請使用 addGeoJson() 方法,將剖析的 GeoJSON 資料加進地圖。

設定資料樣式

在地圖物件中加入 GeoJSON 資料,即可變更資料外觀。請參閱開發人員指南,進一步瞭解如何設定資料樣式

瞭解詳情

  • GeoJSON 是一種廣為使用的開放格式,可根據 JSON (JavaScript Object Notation) 將地理資料編碼。專為 JSON 資料設計的 JavaScript 工具和方法也適用於 GeoJSON。如需詳細資訊,請參閱開發人員指南
  • JSONP 代表「填充式」JSON。這是一種在 JavaScript 程式 (在網路瀏覽器中執行) 中使用的通訊方法,用來向其他網域的伺服器要求資料。