google maps marker cluster

3 posts by 2 authors in: Forums > CMS Builder: Plugins & Add-ons
Last Post: July 18, 2022   (RSS)

By ht1080z - July 17, 2022

Hi,

Is there any easy way to add marker cluster to maps using the Geocoder plugin?

I didn't manage to create markers array within the _geocoder_addMarker function and also getting Uncaught ReferenceError: MarkerClusterer is not defined.

Any help would appreciated,
Karls

By ht1080z - July 17, 2022 - edited: July 17, 2022

I found solution minutes after I posted my question...

I added the required js call after the base maps api js:

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=<?php echo htmlEncode($GLOBALS['GEOCODER_GOOGLE_API_KEY']); ?>"></script>
<script src="https://cdn.rawgit.com/googlemaps/js-marker-clusterer/gh-pages/src/markerclusterer.js"></script>

and modified the script as:

function initialize() {
  var mapCanvasId = 'map_canvas';
  var mapOptions  = { mapTypeId: google.maps.MapTypeId.ROADMAP };
  var map         = new google.maps.Map(document.getElementById(mapCanvasId), mapOptions);
  var bounds      = new google.maps.LatLngBounds();
  var infowindow  = new google.maps.InfoWindow();
  var markers = []; // cluster related 1.
<?php
	foreach ($myRecords as $record) {
	  if (!$record['latitude'] || !$record['longitude']) { continue; }
	  $jsFunctionArgs = "{$record['latitude']}, {$record['longitude']}, {$record['num']}, '" .jsEncode($record['_link']). "'";
	  print "  _geocoder_addMarker($jsFunctionArgs);\n";
	}
?>
  //
  function _geocoder_addMarker(latitude, longitude, recordNum, detailLink) {
    var latLng       = new google.maps.LatLng(latitude, longitude);
    var infowindowEl = document.getElementById('marker_infowindow_' + recordNum);
    var marker       = new google.maps.Marker({ map: map, position: latLng });
    markers.push(marker);  // cluster related 2.
    google.maps.event.addListener(marker, 'click', function() {
      if (infowindowEl) {
        infowindow.setContent(infowindowEl.innerHTML);
        infowindow.open(map, marker);
      }
      else {
        window.location = detailLink;
      }
    });
    bounds.extend(latLng);
  }
  //
  map.fitBounds(bounds);
  
  var markerCluster = new MarkerClusterer(map, markers, {
    imagePath: 'https://cdn.rawgit.com/googlemaps/js-marker-clusterer/gh-pages/images/m'
  });  // cluster related 3.
}

I hope somebody will find this useful.

By daniel - July 18, 2022

Hi Karls,

I'm glad you were able to find a solution, and thanks for posting your example!

Daniel
Technical Lead
interactivetools.com