2014年9月11日木曜日

複数のマーカーをバラバラと降らせて追加


今回は複数のマーカーをバラバラと降らせながら追加してみます。

仕組みはsetTimeoutで時間差でマーカーを追加しています。
追加する際、マーカーのanimationプロパティを
animation: google.maps.Animation.DROP
の様に設定することで上からバラバラと降ってくるような演出が出来ます。

また、setTimeoutは普通に引数としてオブジェクトを渡すことは出来ないので、
setTimeout(function () { addMarkers(gmap, latlng) }, index * 50);
のように無名関数をsetTimeoutに渡しています。

index * 50
の部分をランダム関数など使い、
もうちょっと工夫すればよりバラバラ感が出せると思います。

以下サンプルです。
地図の下にある
「マーカーを降らせるボタン」を押すと、
地図にマーカーが振ります。
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="utf-8" />
    <title>複数のマーカーをバラバラと降らせて追加</title>
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript">
        google.maps.event.addDomListener(window, "load", function () {
            var latlngs = [
                new google.maps.LatLng(35.496456, 139.262695),
                new google.maps.LatLng(35.906849, 139.702148),
                new google.maps.LatLng(35.433820, 140.130615),
                new google.maps.LatLng(34.985003, 139.883423),
                new google.maps.LatLng(35.732021, 140.802841),
                new google.maps.LatLng(35.691322, 138.741188),
                new google.maps.LatLng(36.299632, 139.499588),
                new google.maps.LatLng(34.779972, 138.916626),
                new google.maps.LatLng(36.033553, 140.394287),
                new google.maps.LatLng(35.880149, 139.048462)
            ];

            // マップを作成
            var mapOptions = {
                zoom: 7,
                center: new google.maps.LatLng(35.686773, 139.68815)
            };
            var gmap = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

            // マーカー追加ボタン押下
            var addButton = document.getElementById("add_button");
            google.maps.event.addDomListener(addButton, "click", function () {
                latlngs.forEach(function (latlng, index) {
                    setTimeout(function () { addMarkers(gmap, latlng) }, index * 50);
                });
            });
        });

        // マーカー追加
        function addMarkers(gmap, latlng) {
            var marker = new google.maps.Marker({
                position: latlng,
                map: gmap,
                animation: google.maps.Animation.DROP
            });
        }
    </script>
</head>
<body>
    <div id="map_canvas" style="width: 300px; height: 300px"></div>
    <span id="add_button">マーカーを降らせるボタン</span>
</body>
</html>

マーカーを降らせるボタン



このエントリーをはてなブックマークに追加

0 件のコメント:

コメントを投稿