Page loads, markers are set and shown, functions work, and so on... Everything seems to be fine, but MarkerClusterer does not work. What am i missing ? Code optimization suggestions are welcomed as well :)
<script>
var map;
var markers = [];
function loadjsonmarkerstomap()
{
$.getJSON("json.php", function(json1)
{
$.each(json1, function(key, data)
{
var latlng = new google.maps.LatLng(data.lat, data.lng);
var infocontent = "<div style='width: 200px; height: 200px; border: 1px solid grey;'>ID: " + data.id + "<br/>Type: " + data.type + "<br/>Weight: " + data.weight + '<br/><input type="submit" value="Show"/></div>';
var marker = new google.maps.Marker(
{
position: latlng,
map: map,
title: data.title
});
var infowindow = new google.maps.InfoWindow({ content: infocontent });
marker.addListener('click', function()
{
infowindow.open(map, marker);
});
markers.push(marker);
});
});
}
function clearLocations()
{
for (var i = 0; i < markers.length; i++)
{
markers[i].setMap(null);
}
markers.length = 0;
}
$('#clear').click(
function()
{
clearLocations();
}
);
$('#load').click(
function()
{
loadjsonmarkerstomap();
}
);
function initMap()
{
map = new google.maps.Map(document.getElementById('map'),
{
center: {lat: 46.30499, lng: 25.292647}, //
zoom: 8 //
});
loadjsonmarkerstomap(); //
var markerCluster = new MarkerClusterer(map, markers, {imagePath: 'images/m'});
}
</script>
I believe it might not be working due to the markers being fetched asynchronously. Eg when you run your loadjsonmarkerstomap()
and then immedialtely init your cluster your markers array is still empty.
You have to make sure to init the cluster after the ajax call is successful.
var markerCluster = new MarkerClusterer(map, markers, {imagePath: 'images/m'}); }
Should go inside the callback of your ajax call. Eg directly after your $.each(json1.. loop