Bing Maps群集图钉点击

时间:2016-06-10 16:07:34

标签: javascript bing-maps

我有一个带有群集引脚的地图,我想这样做,以便点击群集引脚将缩放该区域的地图。我正在使用webAPI并为各个引脚设置了一个点击处理程序。有没有办法可以为群集引脚设置点击处理程序?

1 个答案:

答案 0 :(得分:4)

是的,这很容易做到。集群模块允许您传入回调函数,该函数可用于自定义集群图钉。在此回调函数中,您可以向clustered pin添加点击事件。当该事件被触发时,您可以获取集群中的所有图钉并为它们计算边界框,以便将地图缩放到该区域。请注意,一旦放大,某些图钉可能仍然在群集中。以下是代码示例:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <script type='text/javascript'
            src='http://www.bing.com/api/maps/mapcontrol?callback=GetMap' async defer></script>
    <script type="text/javascript">
    var map, clusterLayer;

    function GetMap() {
        map = new Microsoft.Maps.Map('#myMap',{
            credentials: 'Your Bing Maps Key',
            zoom: 3
        });

        Microsoft.Maps.loadModule("Microsoft.Maps.Clustering", function () {
            //Generate 3000 random pushpins in the map view.
            var pins = Microsoft.Maps.TestDataGenerator.getPushpins(3000, map.getBounds());

            //Create a ClusterLayer with options and add it to the map.
            clusterLayer = new Microsoft.Maps.ClusterLayer(pins, {
                clusteredPinCallback: customizeClusteredPin
            });
            map.layers.insert(clusterLayer);
        });
    }

    function customizeClusteredPin(cluster) {
        Microsoft.Maps.Events.addHandler(cluster, 'click', clusterClicked);
    }

    function clusterClicked(e) {
        if (e.target.containedPushpins) {
            var locs = [];
            for (var i = 0, len = e.target.containedPushpins.length; i < len; i++) {
                //Get the location of each pushpin.
                locs.push(e.target.containedPushpins[i].getLocation());
            }

            //Create a bounding box for the pushpins.
            var bounds = Microsoft.Maps.LocationRect.fromLocations(locs);

            //Zoom into the bounding box of the cluster. 
            //Add a padding to compensate for the pixel area of the pushpins.
            map.setView({ bounds: bounds, padding: 100 });
        }
    }
    </script>
</head>
<body>
    <div id="myMap" style="position:relative;width:600px;height:400px;"></div>
</body>
</html>