2013/08/16

Google Maps API 標記動畫

Google Maps是可以有標記,且標記可以用動畫的方式去呈現
標記動畫可是由animation這個類別去提供的,該類別僅提供兩個方法
ConstantDescription
BOUNCEMarker bounces until animation is stopped.
DROPMarker falls from the top of the map ending with a small bounce.

BOUNCE是直到animation為空才停止
DROP則是短暫跳躍


HTML:
<!DOCTYPE html>
<html lang="zh-tw">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=Key Number&sensor=false&region=zh-tw"></script>
    <script type="text/javascript" src="./Script.js"></script>
      <style type="text/css">
        html { height: 100% }
        body { height: 100%; margin: 0; padding: 0 }
        #map { height: 95% ; width: 100% }
        #address { width:40%  }   
      </style>
  </head>
  <body>
    <div id="map"></div>
      </div>
  </body>
</html>





var stockholm = new google.maps.LatLng(59.32522, 18.07002);
var parliament = new google.maps.LatLng(59.327383, 18.06747);
var marker;
var map;

function initialize()
{
    var mapOptions = {
        zoom: 13,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: stockholm
    };

    map = new google.maps.Map(document.getElementById('map'),
          mapOptions);

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

JavaScript:
function toggleBounce()
{

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

google.maps.event.addDomListener(window, 'load', initialize);

網頁載入時先載入initialize函式,並且用DROP方式呈現。




再來監聽滑鼠點擊事件,該事件觸發則啟動toggleBounce函式,如果Animation不為空,則一直跳動;反之停止




參考資料:
https://developers.google.com/maps/documentation/javascript/overlays?hl=zh-tw#MarkerAnimations