目前 WebGIS 應用較廣為人知的,應該就當屬 Google Maps Platform。另外還有 OpenLayers、Leaflet 這兩套 Open Source 的 Javascript Library 。因為工作上使用的是 OpenLayers 。所以接下來的 30 天將搭配官方案例來解說 OpenLayers 的相關實作。
打開 Visual Studio Code,建立一個 Html,然後將底下的 Code 複製貼上
<!doctype html>
<html lang="zh-tw">
  <head>
    <link rel="stylesheet" href="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.2.0/css/ol.css" type="text/css">
    <style>
      .map {
        height: 800px;
        width: 100%;
      }
    </style>
    <script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.2.0/build/ol.js"></script>
    <title>Day-01</title>
  </head>
  <body>
    <div id="map" class="map"></div>
    <script type="text/javascript">
      var map = new ol.Map({
        target: 'map',
        layers: [
          new ol.layer.Tile({
            source: new ol.source.OSM()
          })
        ],
        view: new ol.View({
          center: ol.proj.fromLonLat([120.6718112, 24.1502971]),
          zoom: 16
        })
      });
    </script>
  </body>
</html>
利用 Chrome 開啟後,你應該就會得到底下的地圖。
首先,將地圖加入到網頁上,你必須要做三件事:
OpenLayers 的 Javascript librarydiv 來當地圖容器OpenLayers 的 Javascript library<!-- OpenLayers 的 CSS,本案例為為非必要載入 -->
<link rel="stylesheet" href="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.2.0/css/ol.css" type="text/css">
<!-- OpenLayers Library -->
 <script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.2.0/build/ol.js"></script>
注意 如果你的地圖應用的客戶端是比較舊的平台,例如:IE 或者是 Android 4.x,需要另外引用底下的 Lib
 <script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList"></script>
div 來當地圖容器很單純的直接在頁面上放置一個 div 當地圖容器,因為是 Html Tag所以之後需要設定地圖大小,可以透過 CSS 來針對這個元素來控制寬高。
<style>
    .map {
    height: 800px;
    width: 100%;
    }
</style>
<div id="map" class="map"></div>
接著就是今天的核心,利用 js 來將地圖建立出來。請看底下這段程式碼:
// 宣告一個 Map 物件
var map = new ol.Map({  
        // 將 Map 物件目標指向 div,這邊要注意的是其值是 div 的 id 屬性。
        target: 'map',  
        // 這裡是宣告圖層陣列,範例加入的是 OSM 圖磚圖層。
        layers: [
          new ol.layer.Tile({
            source: new ol.source.OSM()
          })
        ],
        // 這裡是初始化地圖視圖的地方。定義初始中心位置及視圖層級
        view: new ol.View({
          center: ol.proj.fromLonLat([120.6718112, 24.1502971]),
          zoom: 16
        })
      });
以上,是今天的分享。接下來會詳細講解 View 及 Layers。