IT筆記 :Leaflet開源JavaScript地圖學習篇(1)

 使用leaflet製作網頁版的地圖,首先引入基本的avaScript 庫(leaflet.js)和一個CSS 樣式表(leaflet.css)。

較為方便的做法就是引用CDN上的版本

    <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>

    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />


添加一個div容器來顯示地圖

<div id="map"></div>

設定地圖div的高度,可使用pixel或者%,如果沒有設定,地圖會顯現不出來!


   #map {

        /* configure the size of the map */

        width: 100%;

        height: 100%;

      }

設定地圖的中心點座標及縮放等級。

 var map = L.map('map').setView({lon: 114.20847, lat:22.29227},16);

或者

var map = L.map('map',{

                center: [22.29227, 114.20847],

                zoom: 16

            });

在容器中加底圖,添加 OpenStreetMap 地圖圖塊作為範例。

      // add the OpenStreetMap tiles

      L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {

        maxZoom: 19,

        attribution: '&copy; <a href="https://openstreetmap.org/copyright">OpenStreetMap contributors</a>'

      }).addTo(map);


在左下角顯示比例尺

      // show the scale bar on the lower left corner

      L.control.scale({imperial: true, metric: true}).addTo(map);


  在地圖上顯示一個標記

// show a marker on the map

 L.marker({lon: 114.18014627779849, lat:22.450669219333417}).bindPopup('大埔海濱公園').addTo(map);


完整的源代碼 :
Source code modified from Leaflet.Js Essentials by Paul Crickard III:

<!DOCTYPE HTML>

<html lang="en">

  <head>

    <meta charset="utf-8" />

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>

    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />

    <style>

      html, body {

        height: 100%;

        padding: 0;

        margin: 0;

      }

      #map {

        /* configure the size of the map */

        width: 100%;

        height: 100%;

      }

    </style>

  </head>

  <body>

    <div id="map"></div>

    <script>

      // initialize Leaflet

      var map = L.map('map').setView({lon: 114.18014627779849, lat:22.450669219333417},16);

  

      // add the OpenStreetMap tiles

      L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {

        maxZoom: 19,

        attribution: '&copy; <a href="https://openstreetmap.org/copyright">OpenStreetMap contributors</a>'

      }).addTo(map);


      // show the scale bar on the lower left corner

      L.control.scale({imperial: true, metric: true}).addTo(map);


      // show a marker on the map

      L.marker({lon: 114.18014627779849, lat:22.450669219333417}).bindPopup('大埔海濱公園').addTo(map);

    </script>

  </body>

</html>


 

Comments

Popular posts from this blog

旅遊筆記 : 吉隆坡前往檳城交通方式及網上購買馬來西亞KTM火車票教學

旅遊筆記 : 馬來西亞電動 Platinum ETS 列車初體驗

閒遊深水灣、淺水灣觀無敵海景,順走赤柱古道訪老虎坑、獅子坑古石橋尋歷史。