javascript - 谷歌地图聚类器没有标记

标签 javascript google-maps-api-3 markerclusterer

我正在尝试将markerclusterplus.js 与Google map API v3 一起使用。我正在循环访问一系列地址,对每个地址进行地理编码并添加标记和信息窗口。我将标记推送到一个名为标记的数组,并使用以下代码将它们添加到我的集群中

var markerCluster = new MarkerClusterer( map , 标记);

没有显示聚集标记。其余代码有效,如果我添加

map: map

对于我的标记来说,它们显示为标准标记,所以这一切都很好。当使用警告标记数组时

alert(markers.toString())

没有返回任何内容,因此可能没有任何内容被推送到数组中?

完整代码如下

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&amp;ver=3.5.1"></script>
<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclustererplus/src/markerclusterer.js"></script>

</head>

<body>

<script type="text/javascript">
var map; //Map variable
var geocoder; //Geocoder variable
var infowindow;
//var marker; //Marker variable
//Options variable
var myOptions = {
              zoom: 2,
              mapTypeId: google.maps.MapTypeId.ROADMAP,
              disableDefaultUI: true,
            }; 
var LatLngList = [];

//Geocoder function
function myGeocode() {

    infowindow = new google.maps.InfoWindow({
        maxWidth: 200
    });
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    geocoder = new google.maps.Geocoder();
    var titles = ['Anne of Cleves House',
        'Lewes Castle',
        'Michelham Priory',
        'Fishbourne Roman Palace & Gardens',
        'Marlipins Museum','The Priest House',
        'The Long Man'
        ];

    var addresses =[
        'Anne of Cleves House, 52, Southover High St, Lewes, BN7 1JA',
        'Barbican House Museum, 169, High Street, Lewes, BN7 1YE',
        'Michelham Priory, Upper Dicker, Hailsham, East Sussex, BN27 3QS',
        'Fishbourne Roman Palace, Roman Way, Fishbourne, West Sussex, PO19 3QR',
        'Marlipins Museum, High Street, Shoreham-by-Sea, West Sussex, BN43 5DA',
        'The Priest House, North Lane, West Hoathly, West Sussex, RH19 4PP',
        'The long man of wilmington'
    ];

    var descriptions = [
        'Anne of Cleves House you can explore how the Tudors and Elizabethans lived, worked and relaxed at home.',
        'Climb to the top of this 1000 year old Norman Castle for stunning panoramic views across Sussex.',
        'England\'s longest water filled moat surrounds the site which dates back to 1229.',
        'Welcome to the largest Roman home in Britain',
        'The striking chequerboard flint and Caen limestone facade is part of one of the oldest Norman buildings in Sussex.',
        'The only one of its kind open to the public, this beautiful 15th century Wealden hall house stands in a traditional cottage garden.',
        'the long man of wilmington'
    ];

    for (var i = 0; i < addresses.length; i++) { 

        var address = addresses[i];
        var title = titles[i];
        var description = descriptions[i];
        //var alink = links[i];
        var markers = [];
        var marker;

        (function(address, title, description) {

            geocoder.geocode( {"address": address }, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {

                    latlng = results[0].geometry.location;
                    LatLngList.push(latlng);

                    map.setCenter(latlng);

                    marker = new google.maps.Marker({
                        position: latlng
                        //map: map, 
                        //title: title,
                     }); 

                    markers.push(marker);

                    google.maps.event.addListener(marker, "click", function () {
                        infowindow.setContent("<div class='map-infowindow'><h4 class='gm-title'>"+title+"</h4>"+description+"'<a class='gm-directions' href='http://maps.google.com/maps?saddr="+address+"'>Get directions</a></div>");
                    infowindow.open(map, marker);
                    });

                } 
                else {
                  document.getElementById("text_status").value = status;
                }

            });//end of geocoder
        })(address, title, description); // <- Call function, pass the vars to be captured 
    }//end of for loop

    alert(markers.toString())
    var markerCluster = new MarkerClusterer(map, markers);

    //  Create a new viewpoint bound
    var bounds = new google.maps.LatLngBounds ();
    //  Go through each...
    for (var i = 0, LtLgLen = LatLngList.length; i < LtLgLen; i++) {
      //  And increase the bounds to take this point
      bounds.extend (LatLngList[i]);
    }
    //  Fit these bounds to the map
    map.fitBounds (bounds);

    //alert(LatLngList.join('\n'))
}

window.onload=myGeocode;
</script>

<div id="map_canvas" style="width:600px; height:600px;"></div>  

</body>

</html>

最佳答案

首先,每次在循环内重新定义标记数组,必须在循环外部定义标记数组。

其次,geocoder.geocode 异步工作,因此地理编码实际上直到循环结束后才完成,甚至在您的alert() 调用之后才完成。

第三,没有必要在循环中使用闭包,因为每次循环都需要重新定义函数。在这种情况下,我总是喜欢在当前函数中添加私有(private)方法。因此,执行地理编码调用的函数仅定义一次并根据需要调用。现在我们需要做的就是(从地理编码器的回调函数中)观察标记数组的长度增长,直到它与地址数组的长度相同,然后我们知道所有地理编码已经完成(当然假设一切顺利),完成事情的时间:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&amp;ver=3.5.1"></script>
<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclustererplus/src/markerclusterer.js"></script>
</head>
<body>
<script type="text/javascript">
var map; //Map variable
var geocoder; //Geocoder variable
var infowindow;
//var marker; //Marker variable
//Options variable
var myOptions = {
              zoom: 2,
              mapTypeId: google.maps.MapTypeId.ROADMAP,
              disableDefaultUI: true,
            }; 
var LatLngList = [];

//Geocoder function
function myGeocode() {
    infowindow = new google.maps.InfoWindow({
        maxWidth: 200
    });
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    geocoder = new google.maps.Geocoder();
    var titles = [
        'Anne of Cleves House',
        'Lewes Castle',
        'Michelham Priory',
        'Fishbourne Roman Palace & Gardens',
        'Marlipins Museum','The Priest House',
        'The Long Man'
        ];

    var addresses =[
        'Anne of Cleves House, 52, Southover High St, Lewes, BN7 1JA',
        'Barbican House Museum, 169, High Street, Lewes, BN7 1YE',
        'Michelham Priory, Upper Dicker, Hailsham, East Sussex, BN27 3QS',
        'Fishbourne Roman Palace, Roman Way, Fishbourne, West Sussex, PO19 3QR',
        'Marlipins Museum, High Street, Shoreham-by-Sea, West Sussex, BN43 5DA',
        'The Priest House, North Lane, West Hoathly, West Sussex, RH19 4PP',
        'The long man of wilmington'
    ];

    var descriptions = [
        'Anne of Cleves House you can explore how the Tudors and Elizabethans lived, worked and relaxed at home.',
        'Climb to the top of this 1000 year old Norman Castle for stunning panoramic views across Sussex.',
        'England\'s longest water filled moat surrounds the site which dates back to 1229.',
        'Welcome to the largest Roman home in Britain',
        'The striking chequerboard flint and Caen limestone facade is part of one of the oldest Norman buildings in Sussex.',
        'The only one of its kind open to the public, this beautiful 15th century Wealden hall house stands in a traditional cottage garden.',
        'the long man of wilmington'
    ];
    var markers = [];
     //private function, only need be defined once!
    function getGeocode(address, title, description) {
        geocoder.geocode( {"address": address }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                latlng = results[0].geometry.location;
                LatLngList.push(latlng);
                map.setCenter(latlng);
                var marker = new google.maps.Marker({
                    position: latlng,
                    map: map
                    //title: title,
                }); 
                markers.push(marker);
                google.maps.event.addListener(marker, "click", function () {
                    infowindow.setContent("<div class='map-infowindow'><h4 class='gm-title'>"+title+"</h4>"+description+"'<a class='gm-directions' href='http://maps.google.com/maps?saddr="+address+"'>Get directions</a></div>");
                    infowindow.open(map, marker);
                });
                if (markers.length == addresses.length) { //we have received all of our geocoder responses
                    alert(markers);
                    var markerCluster = new MarkerClusterer(map, markers);
                    //  Create a new viewpoint bound
                    var bounds = new google.maps.LatLngBounds ();
                    //  Go through each...
                    for (var i = 0, LtLgLen = LatLngList.length; i < LtLgLen; i++) {
                        //  And increase the bounds to take this point
                        bounds.extend (LatLngList[i]);
                    }
                    //  Fit these bounds to the map
                    map.fitBounds (bounds);
                }
            } else {
                document.getElementById("text_status").value = status;
            }
        });//end of geocoder
    }
    for (var i = 0; i < addresses.length; i++) { 
        var address = addresses[i];
        var title = titles[i];
        var description = descriptions[i];
        //var alink = links[i];
         //put our private function to work:
        getGeocode(address, title, description);
    }//end of for loop
}

window.onload=myGeocode;
</script>
<div id="map_canvas" style="width:600px; height:600px;"></div>  
</body>
</html>

关于javascript - 谷歌地图聚类器没有标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16013478/

相关文章:

javascript - 使用 javascript 遍历值列表

javascript - 谷歌自动完成 setComponentRestrictions

angularjs - 地理位置 - 使用 Ionic 框架、AngularJS 和 Google API

mapbox - 标记集群 mapbox android

javascript - 如何从 SailsJS 制作 phonegap 移动应用程序

javascript - jQuery 插件回调无法正常工作

javascript - Jquery - 对于条件

javascript - 谷歌地图 JS API v3 : get markers in circle with containsLocation() doesn't work - why?

google-maps-api-3 - 在 Google Maps API 中实现 MarkerClusterer - 没有显示标记

javascript - 使用 MarkerClustererPlus 和 OverlappingMarkerSpiderfier 重叠指针