Question

I have a map with 5 markers with 4 of them being in Jacksonville, FL and 1 in West Palm Beach, FL. I want the 4 markers to be clustered in the initialized zoom level. When zoomed in to level 15 in Jacksonville, I want the cluster to show the 4 markers separately.

enter image description here

So far, this code hasn't worked for me:

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);
});

";

When I check the debugger, I get no errors or warnings. Why is this code not working?

Was it helpful?

Solution

The geocoder is asynchronous. When you load the markers array into the MarkerCluster, it is empty, none of the geocoding results have come back. I suggest you initialize the MarkerCluster before the geocode calls, then add each marker to the clusterer when the callback function runs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top