iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 29
1
自我挑戰組

Ruby菜鳥村村民遊記系列 第 29

遊記ep.29 polylines in Google村

鐵人賽也就30天,居然可以生兩次病 ... Orz
最近還有專案在趕,頂著38.1度也是直接請醫生幫我注射,
希望能快點恢復健康的狀態,也希望大家好好保重身體,健康無價~

今天想來介紹 polylines,可以在地圖上任意畫出的折線:

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Simple Polylines</title>
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 80%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script>

      // This example creates a 2-pixel-wide red polyline showing the path of
      // the first trans-Pacific flight between Oakland, CA, and Brisbane,
      // Australia which was made by Charles Kingsford Smith.

      function initMap() {
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 3,
          center: {lat: 0, lng: -180},
          // mapTypeId: 'terrain'
        });

        var flightPlanCoordinates = [
          {lat: 37.772, lng: -122.214},
          {lat: 21.291, lng: -157.821},
          {lat: -18.142, lng: 178.431},
          {lat: -27.467, lng: 153.027}
        ];
        var flightPath = new google.maps.Polyline({
          path: flightPlanCoordinates,
          geodesic: true,
          strokeColor: '#FF0000',
          strokeOpacity: 0.5,
          strokeWeight: 10
        });

        flightPath.setMap(map);
      }
    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=PutYourKeyHere&callback=initMap">
    </script>
  </body>
</html>

先產生好地圖後,可以設定幾點經緯度,
以便拿來等等作為畫線用。

var flightPlanCoordinates = [
  {lat: 37.772, lng: -122.214},
  {lat: 21.291, lng: -157.821},
  {lat: -18.142, lng: 178.431},
  {lat: -27.467, lng: 153.027}
];
var flightPath = new google.maps.Polyline({
      path: flightPlanCoordinates,
      geodesic: true,
      strokeColor: '#FF0000',
      strokeOpacity: 0.5,
      strokeWeight: 10
});
flightPath.setMap(map);

這裡就可以開始畫線了,使用的是 new google.maps.Polyline({}) 這個方法,
裡面有幾個屬性我們需要設定
path: 就是折線的路徑,代入前面幾個經緯度
geodesic:這個屬性用在測地線與否,會考量地球為一個球體而有曲折,
若false則將地球視為一個平面。
剩下就是設定線條的顏色、透明度以及線的寬度。
我們來看看成果吧!

https://ithelp.ithome.com.tw/upload/images/20191014/20120907VkjSCPbKqN.png

今天,你把玩 Google Map 了嗎?:)

參考文件:
Google Map 官方文件


上一篇
遊記ep.28 Marker labels in Google村
下一篇
遊記ep.30 Click ! Draw ! in Google村
系列文
Ruby菜鳥村村民遊記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言