Google Maps Marker Clusterer无效

时间:2014-03-20 19:01:21

标签: javascript google-maps google-maps-api-3 google-maps-markers markerclusterer

我有一张带有5个标记的地图,其中4个位于佛罗里达州杰克逊维尔,1个位于佛罗里达州西棕榈滩。我希望4个标记在初始化的缩放级别中聚类。当放大到杰克逊维尔的15级时,我希望群集能够分别显示4个标记。

enter image description here

到目前为止,这段代码对我没用:

echo "
jQuery(document).ready(function($) {

var florida =  new google.maps.LatLng(28.4811689,-81.36875);

var mapOptions = {
  zoom: 6,
  center: florida
}

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

var marker_icon_for_sale = '".get_stylesheet_directory_uri()."/images/house-marker-for-sale.png';
var marker_icon_sold = '".get_stylesheet_directory_uri()."/images/house-marker-sold.png';
var marker_icon_hq = '".get_stylesheet_directory_uri()."/images/star-icon.png';

var infowindow;

var markers = [];

var geocoder = new google.maps.Geocoder();

";

$args = array(
    'post_type' => 'project',
);
$query = new WP_Query( $args );

while($query->have_posts()) : $query->the_post();

if (has_post_thumbnail($post->ID)) {
    $thumbnail_id = get_post_thumbnail_id($post->ID);
    $thumbnail_object = get_post($thumbnail_id);
}

echo "
geocoder.geocode( { 'address': '".urlencode(get_the_title())."'}, function(results, status) {
  if (status == google.maps.GeocoderStatus.OK) {
    var marker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location,
        title: '".get_the_title()."',
        draggable: false,
        icon: ".(get_post_meta($post->ID, 'hq') ? "marker_icon_hq" : (get_post_meta($post->ID, 'sold') ? "marker_icon_sold" : "marker_icon_for_sale"))."
    });

    google.maps.event.addListener(marker, 'click', function() {
        if (infowindow) infowindow.close();
        infowindow = new google.maps.InfoWindow({
          content: '".(has_post_thumbnail($post->ID) ? "<img width=\"100\" height=\"100\" src=\"".$thumbnail_object->guid."\" style=\"float: left;\">" : "")."<div style=\"width: 125px; padding: 5px; float: right;\"><b>Status:</b> ".(get_post_meta($post->ID, 'sold') ? 'Sold' : 'For Sale')."<br> ".get_the_title()."<br><a href=\"".get_permalink()."\">Project Info</a></div>'
        });
        infowindow.open(map, marker);
    });

    markers.push(marker);
  }
});

";

endwhile;
echo "

var mcOptions = {gridSize: 20, maxZoom: 15};
var mc = new MarkerClusterer(map, markers, mcOptions);
});

";

当我检查调试器时,我没有收到任何错误或警告。为什么这段代码不起作用?

1 个答案:

答案 0 :(得分:1)

地理编码器是异步的。将markers数组加载到MarkerCluster时,它是空的,没有任何地理编码结果返回。我建议你在地理编码调用之前初始化MarkerCluster,然后在回调函数运行时将每个标记添加到clusterer。