I have successfully created a map with multiple markers generated from a JSON file. However, I am encountering an issue when trying to implement a marker cluster - instead of displaying the cluster separately, both the cluster and markers are showing up simultaneously. Here is the current view: https://i.sstatic.net/LvLvP.png
In order to add the marker cluster feature, I included the following script in my index.html page:
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"></script>
Below is the relevant section of my maps.js file:
let map;
let jsonData = "assets/Data/maps.json";
const countries = [
{ lat: 48.857497, lng: 2.347628, zoom: 5, name: "France" },
//Brazil
{ lat: -15.793889, lng: -47.882778, zoom: 5, name: "Brazil" }
];
function initMap() {
const mapOptions = {
center: {
lat: 9.072264,
lng: 7.491302
},
zoom: 2,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
countries.forEach(function (data) {
let countriesMarker = new google.maps.Marker({
map: map,
position: { lat: data.lat, lng: data.lng },
title: data.name
});
$("#selectlocation").append('<option value="' + [data.lat, data.lng, data.zoom].join('|') + '">' + data.name + '</option>');
});
let infowindow = new google.maps.InfoWindow();
//Method found on StackOverflow: https://stackoverflow.com/questions/28606149/load-data-from-json-file-into-map-markers-in-google-maps
$.getJSON(jsonData, function (jsonMarkers) {
$.each(jsonMarkers.markers, function (key, data) {
let latLng = new google.maps.LatLng(data.lat, data.lng);
let marker = new google.maps.Marker({
position: latLng,
map: map,
title: data.title
});
var clusterMarkers = jsonMarkers.markers.map(function (location) {
return new google.maps.Marker({
position: location
});
});
var markerCluster = new MarkerClusterer(map, clusterMarkers,
{ imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m' });
});
});
}