2014年9月11日木曜日

全てのマーカーが自動で表示されるようにする


今回は沢山のマーカーを表示する際、
全てのマーカーを表示するために、
自動で地図のズーム値・中心座標を設定する方法を紹介します。

作り方は簡単で、まずは
var latLngBounds = new google.maps.LatLngBounds();
のようにLatLngBoundsオブジェクトを作成して、
そこに
latlngs.forEach(function (latlng, index) {
    latLngBounds.extend(latlng);
    new google.maps.Marker({
        position: latlng,
        map: gmap
    });
});
の様に表示したいマーカーの座標を詰め込みます。

そして、
gmap.fitBounds(latLngBounds);
のようにfitBoundsに渡してあげれば完了です。

以下サンプルです。
<!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),
                new google.maps.LatLng(36.633162, 138.186035)
            ];

            // マップを作成
            var gmap = new google.maps.Map(document.getElementById("map_canvas"));

            // マーカーを作成
            var latLngBounds = new google.maps.LatLngBounds();
            latlngs.forEach(function (latlng, index) {
                latLngBounds.extend(latlng);
                new google.maps.Marker({
                    position: latlng,
                    map: gmap
                });
            });

            // 全てのマーカーが表示される様に表示領域を設定する
            gmap.fitBounds(latLngBounds);
        });
    </script>
</head>
<body>
    <div id="map_canvas" style="width: 300px; height: 300px"></div>
</body>
</html>

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

0 件のコメント:

コメントを投稿