跳至主要內容 / Skip to main content
從零編寫第一個 Map Viewer:用網頁看香港今昔,避開常見錯誤
教學、程式示範

從零編寫第一個 Map Viewer:用網頁看香港今昔,避開常見錯誤

HK GeoTiles約 3 分鐘閱讀146 次閱讀
想要對比香港今昔面貌?只需簡單的 HTML 與 Leaflet,就能從零建立首個地圖瀏覽器,輕鬆疊加現代底圖與 1963 年歷史航拍。掌握圖磚原理與分層排錯技巧,避開初學者陷阱,親手讓歷史地圖重現眼前!
146

從零編寫第一個 Map Viewer:用網頁看香港今昔,避開常見錯誤

打開一張 1963 年的香港航拍,你可能會問:今天的街道,當年已經存在嗎?現在的海旁,以前是不是仍然一片海?如果只能看一張圖片,我們往往要一邊猜位置,一邊對照另一張地圖。假如把歷史航拍放進可以拖曳、縮放、開關圖層的網頁,觀察便容易得多。這就是一個簡單的 Map Viewer——地圖瀏覽器。

本文沿用「現代底圖加歷史航拍」的思路,從 QGIS 的桌面操作走向網頁:用 HTML 和 Leaflet 編寫第一個地圖瀏覽器。重點不是一次加入最多功能,而是先讓地圖正確出現,並在出錯時知道應該檢查甚麼。

目錄


一、觀念釐清:我們要做的是地圖瀏覽器,不是重新製作地圖
一、觀念釐清:我們要做的是地圖瀏覽器,不是重新製作地圖

一、觀念釐清:我們要做的是地圖瀏覽器,不是重新製作地圖

你不必先學會掃描舊地圖、校正航拍,或處理整套地理資料,才有資格製作自己的地圖網頁。

這次的分工很簡單:圖磚服務提供地圖,Leaflet 負責操作,網頁把兩者連起來。

「圖磚」可以想像成拼圖的小方塊。當你移動或放大畫面,瀏覽器便向服務索取當前範圍所需的小圖片,不用一次下載整幅香港地圖。Leaflet 則是一套開源 JavaScript 函式庫,替我們處理拖曳、縮放和圖層控制等工作。

第一個版本先做到四件事:顯示 LANDSD 現代底圖、疊加 1963 年歷史航拍、用圖層面板開關航拍,以及在底部顯示滑鼠位置的經緯度與目前縮放層級。搜尋、量度和時間軸等功能,可以留待下一步。

原來大綱中的「三分鐘」是精簡操作目標;對首次編寫網頁的讀者,這裏不作時間保證。理解每一步,比趕快複製完成更重要。

二、實戰準備:開始前,準備好三樣東西
二、實戰準備:開始前,準備好三樣東西

二、實戰準備:開始前,準備好三樣東西

你需要一個現代瀏覽器、一個純文字或程式碼編輯器,以及網絡連線。編輯器可以選用 Visual Studio Code;不要使用 Word 儲存程式碼。

本文採用 Leaflet 1.9.4,毋須先安裝 Node.js,也不用設定資料庫。

本文使用 HK GeoTiles 的 Leaflet HTML 範例:現代底圖來自香港地政總署 LANDSD mapapi,歷史航拍則由 HK GeoTiles 提供 DOP1000-1963G 圖磚服務。兩個圖層預設同時載入;遇到問題時,可以先關閉航拍,分開檢查底圖與疊加層。

範例的圖層名稱寫作「LANDSD 底圖」,但這段程式實際透過 L.tileLayer 載入的是 .png 圖像圖磚。辨別實際載入格式,比只看名稱更重要。

這是一個線上瀏覽器,不是離線地圖。能夠顯示圖磚,也不代表已經下載完整資料,或取得任意轉載及再分發的權利。

三、動手實作:把第一個地圖放進網頁
三、動手實作:把第一個地圖放進網頁

三、動手實作:把第一個地圖放進網頁

建立一個檔案,命名為 index.html。確認副檔名真的為 .html,而不是被系統隱藏的 index.html.txt。

將以下程式碼完整複製進去,再儲存。這個例子把網頁結構、外觀和地圖操作放在同一個檔案,方便初學者閱讀。

html<!DOCTYPE html>
<html lang="zh-HK">
<!--
  HK GeoTiles — Leaflet.js 範例
  ================================
  展示如何使用 Leaflet.js 接入 HK GeoTiles 磚服務:
    底圖:香港地政總署 LANDSD mapapi(WGS84 XYZ)
    疊加層:DOP1000-1963G 1963 年航拍影像(HK GeoTiles)

  依賴:
    Leaflet 1.9.4 — https://leafletjs.com
    (透過 unpkg CDN 載入,無需本地安裝)

  使用方法:
    直接在瀏覽器開啟此 HTML 檔案,或部署至任何靜態網頁伺服器。
    無需後端,無需 API 金鑰。

  磚服務網址:
    底圖:  https://mapapi.hkmapservice.gov.hk/gs/api/v1.0.0/xyz/basemap/WGS84/{z}/{x}/{y}.png
    疊加層:https://hkgeotiles.com/api/tiles/dataset/mbtiles-dop1000-1963/{z}/{x}/{y}

  資料來源:香港特別行政區政府地政總署 LANDSD Open Data
  更多教學:https://hkgeotiles.com/tutorials
-->
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>HK GeoTiles — Leaflet.js 範例</title>
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
  <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
  <style>
    * { margin: 0; padding: 0; box-sizing: border-box; }
    html, body { width: 100%; height: 100%; font-family: monospace; }
    #map { width: 100%; height: calc(100% - 36px); }
    .info-bar {
      position: fixed; bottom: 0; left: 0; right: 0; z-index: 1000;
      background: rgba(45,80,22,0.95); color: #f5f0e8;
      font: 11px/1.4 monospace; padding: 6px 12px;
      display: flex; gap: 16px; align-items: center;
      height: 36px;
    }
    .badge {
      background: #4A7C2F; color: #fff; font-size: 10px;
      padding: 2px 6px; border-radius: 3px; font-weight: 700;
      letter-spacing: 0.05em;
    }
    .attr { margin-left: auto; opacity: 0.65; font-size: 10px; }
  </style>
</head>
<body>
<div id="map"></div>
<div class="info-bar">
  <span class="badge">LEAFLET 1.9.4</span>
  <span id="coords">座標:移動滑鼠 / 觸碰地圖</span>
  <span id="zoom">縮放:14</span>
  <span class="attr">© 香港特別行政區政府地政總署 LANDSD</span>
</div>

<script>
  // ── 初始化地圖,中心設於香港 ──────────────────────────────────────────────
  var map = L.map('map', { zoomControl: true }).setView([22.3193, 114.1694], 14);

  // ── 底圖:LANDSD 向量底圖(WGS84 XYZ) ────────────────────────────────────
  var basemap = L.tileLayer(
    'https://mapapi.hkmapservice.gov.hk/gs/api/v1.0.0/xyz/basemap/WGS84/{z}/{x}/{y}.png',
    {
      attribution: '&copy; 香港地政總署 LANDSD',
      maxZoom: 20,
      minZoom: 9
    }
  ).addTo(map);

  // ── 疊加層:DOP1000-1963G 1963 年航拍影像 ─────────────────────────────────
  // 縮放 z10 以上才有圖磚,建議 z14 以上使用以獲得最佳清晰度
  var dop1963 = L.tileLayer(
    'https://hkgeotiles.com/api/tiles/dataset/mbtiles-dop1000-1963/{z}/{x}/{y}',
    {
      attribution: '&copy; 香港地政總署 LANDSD via HK GeoTiles',
      maxZoom: 20,
      minZoom: 10,
      opacity: 0.85
    }
  ).addTo(map);

  // ── 圖層控制面板 ──────────────────────────────────────────────────────────
  L.control.layers(
    { 'LANDSD 向量底圖': basemap },
    { 'DOP1000-1963G(1963 年航拍)': dop1963 },
    { collapsed: false }
  ).addTo(map);

  // ── 座標及縮放顯示 ────────────────────────────────────────────────────────
  map.on('mousemove', function(e) {
    document.getElementById('coords').textContent =
      '座標:' + e.latlng.lat.toFixed(5) + ', ' + e.latlng.lng.toFixed(5);
  });
  map.on('zoomend', function() {
    document.getElementById('zoom').textContent = '縮放:' + map.getZoom();
  });
</script>
</body>
</html>

你也可以直接使用範例檔案 hkgeotiles-leaflet-example.html,毋須重新輸入。用瀏覽器開啟後,地圖會使用地政總署 LANDSD mapapi 與 HK GeoTiles 圖磚服務。公開網站前,應分別核對兩者的最新使用條款、署名要求及流量限制,不要因範例毋須輸入 API 金鑰,便推斷可以無限制下載、快取或再分發。若預計有大量訪客,也應先評估服務承載及合適的使用方式。

歷史航拍亦須分別核對原始資料與 HK GeoTiles 服務的條款。範例中的署名只是起點,不能代替正式的授權檢查。截圖、教學投影片、商業網站及再分發,可能有不同要求。

公開前,至少確認:

  • 地圖與圖層開關在桌面及手機上均能操作;桌面座標與縮放數字正常更新。
  • 若要支援觸控顯示座標,已補上相應事件並實測;手機窄畫面亦已檢查底部資訊列是否擠壓或溢出。
  • 航拍年份、圖層名稱及資料來源標示清楚。
  • 已核對最新服務網址、覆蓋範圍、使用條款及署名要求。
  • 沒有把放大層級誤寫成原始解像度,也沒有把視覺疊加當成精確量測。
  • 已在實際瀏覽器測試,而不是只確認程式碼看起來沒有問題。

結語:先讓一張地圖可靠地出現

第一個 Map Viewer,不必是一套完整的 GIS 系統。

從一個 HTML 檔案開始,先顯示底圖,再加入航拍,最後學會開關和比對,你已經走過了網頁地圖最基本的流程。更重要的是,你知道畫面背後有容器、程式、圖磚服務和資料規格幾個不同環節,出錯時不必全部推倒重來。

香港圖磚提供的不只是看舊地圖的入口,也是一種讓資料被重新使用的方法。當更多人能夠建立自己的地圖瀏覽器,歷史地圖便不再只是收藏中的圖片,而可以成為教學、研究和公眾分享的共同資源。

下一步,就從你最熟悉的一條街道開始。


延伸閱讀:

EN

English Summary

Comparing historical aerial imagery with contemporary urban landscapes often presents a significant challenge when relying solely on static images, as researchers must manually cross-reference locations between different historical maps. To streamline this process for Hong Kong’s rich spatial history, the original article introduces a foundational guide for transitioning from desktop GIS applications to creating interactive, web-based map viewers. By building a custom map viewer from scratch, spatial historians and geographic enthusiasts can easily drag, zoom, and toggle between different temporal layers to observe dramatic changes in shorelines and street layouts. The primary objective is to demonstrate that constructing an interactive web map does not require users to manually scan old documents, georeference aerial photos, or manage overwhelming geographic datasets. Instead, it focuses on a streamlined approach using basic HTML and the open-source Leaflet JavaScript library, ensuring that users can bring historical geography to the web reliably and efficiently.

At the core of this tutorial is a clear conceptual breakdown of modern web mapping architecture, emphasizing the division of labour between data delivery and user interface. The article explains that a map viewer relies on map tile services, which function like dynamic puzzle pieces. Rather than downloading an enormous, high-resolution map of Hong Kong at once, the browser only requests the specific graphical tiles required for the user’s current viewing area and zoom level. Meanwhile, the Leaflet library operates as the engine handling user interactions, such as panning and layer control, without necessitating a complex backend environment or a dedicated database. The tutorial guides readers through writing a single, self-contained HTML file that seamlessly integrates a modern base map from the Hong Kong Lands Department (LANDSD) with a historical overlay. By keeping the initial implementation straightforward, the guide ensures that developers understand fundamental concepts before attempting to add advanced features like measurement tools or interactive timelines.

HK GeoTiles plays a pivotal role in enabling this interactive historical exploration by providing ready-to-use spatial infrastructure. In the provided example, the web map directly consumes the DOP1000-1963G tile service from HK GeoTiles, instantly layering 1963 aerial photography over the modern LANDSD base map. By offering standardized XYZ tile endpoints, HK GeoTiles removes the immense technical barriers traditionally associated with processing historical geographic information. Users are freed from the intensive computational tasks of image rectification, coordinate transformation, and server hosting. Consequently, raw archival imagery is transformed into highly accessible, interoperable data streams. This infrastructure not only facilitates individual curiosity regarding specific streets or historical neighborhoods but also establishes a reliable foundation for academics, educators, and developers to build custom spatial applications. Through these accessible tile services, historical maps cease to be isolated artifacts in physical archives and instead become shared, dynamic resources that actively contribute to public knowledge and urban research.

Beyond writing the underlying code, the article imparts crucial practical takeaways for GIS professionals and history enthusiasts aiming to publish their geographic projects. A significant portion of the guidance focuses on the ethical and legal responsibilities of web mapping, strongly advising developers to rigorously verify usage terms, API traffic limits, and strict attribution requirements for both government data and third-party services like HK GeoTiles. The tutorial also provides valuable troubleshooting strategies, recommending a systematic, layer-by-layer diagnostic approach—such as temporarily disabling the historical overlay to isolate base map errors—rather than rewriting entire blocks of code when an image fails to load. Furthermore, it emphasizes the necessity of rigorous cross-device testing to ensure that interface elements, such as coordinate displays and layer toggles, function seamlessly on both desktop monitors and mobile touchscreens. Ultimately, the guide reminds practitioners to maintain analytical rigor, cautioning that while interactive visual overlays are incredibly powerful tools for historical interpretation, they should be understood as exploratory aids rather than instruments for exact geospatial measurement.

香港圖磚
MAPVIEWER
地圖瀏覽器
香港航拍
HTML
Leaflet
146
H

HK GeoTiles

HK GeoTiles 撰稿人

致力於整理及分享香港歷史地圖磚資源,讓公眾更容易取用珍貴的地理資訊。

載入附件中…

相關文章

查看全部