iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 26
1
自我挑戰組

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

遊記ep.26 舞い躍る ! Marker ! in Google村

  • 分享至 

  • twitterImage
  •  

經過前幾天累積,我們已經能夠讓 marker 隨意地出現在 Google Map 上,
但總覺得光出現而已好像有點滿足不了人類的視覺~
如果能讓 marker 動態一些是不是會更好呢?
Let's Do This!

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Marker Animations</title>
    <style>
      /* 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;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script>

      // The following example creates a marker in Stockholm, Sweden using a DROP
      // animation. Clicking on the marker will toggle the animation between a BOUNCE
      // animation and no animation.

      var marker;
      var taiwan = {lat: 23.5, lng: 121}
      function initMap() {
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 8,
          center: taiwan
        });

        marker = new google.maps.Marker({
          map: map,
          draggable: true,
          animation: google.maps.Animation.DROP,
          position: taiwan
        });
        marker.addListener('click', toggleBounce);
      }

      function toggleBounce() {
        if (marker.getAnimation() !== null) {
          marker.setAnimation(null);
          }
        else {
          marker.setAnimation(google.maps.Animation.BOUNCE);
        }
      }
    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
    </script>
  </body>
</html>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
  zoom: 8,
  center: taiwan
});

我們一樣先初始化一張地圖,
設定好 center 以及 zoom,

function toggleBounce() {
  if (marker.getAnimation() !== null) {
    marker.setAnimation(null);
  }
  else {
  marker.setAnimation(google.maps.Animation.BOUNCE);
  }
}

這邊先產生一個函式,
主要需要做的是判斷 marker 是否有動畫
"如果有動畫、那就讓它停下,沒有動畫的話就給它"

marker = new google.maps.Marker({
  map: map,
  draggable: true,
  animation: google.maps.Animation.DROP,
  position: taiwan
});
marker.addListener('click', toggleBounce);
}

最後我們來處理 marker 該做的事,
首先當然是需要讓他出現在 Google Map 上,
並且給 marker 一個可以被拖曳的屬性,
以及讓他出現在 map 的時候,有個掉落的動畫,
再來設定出現的位置就完成囉!
最後別忘了,設定一個觸發(Click)要素來讓他做我們想要做的動作!

這樣一來,開啟地圖時就會看到 marker 從天而降,
並且點擊 marker 可以原地彈跳~ 還可以拖著 marker 到處跑呢!

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

參考文件:
Google Map 官方文件


上一篇
遊記ep.25 Control Zoom and Pan in Google村
下一篇
遊記ep.27 Remove / Delete Marker in Google村
系列文
Ruby菜鳥村村民遊記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言