This post shows you how to use marker clusters to display a large number of markers on a map. You can use the “Marker Clustering” in combination with the Maps JavaScript API to combine markers of close proximity into clusters, and simplify the display of markers on the map.

To see how marker clustering works, view the map below.

To add “Marker Clustering”, We need "<script src=”https://unpkg.com/@googlemaps/markerclusterer/dist/index.min.js”></script>" this script is to be adding just after that the script of the map api is left in the head tag.

It looks exactly like that.

<head>
    <script src="https://maps.googleapis.com/maps/api/js?                                                                  
    key=googleMapApiKeyValue&callback=initMap&libraries=places&v=weekly" defer></script>
    <script src="https://unpkg.com/@googlemaps/markerclusterer/dist/index.min.js"></script>
</head>

Now we need to use the following code in the jQuery file where the map’s API “initMap()” function is used.

First you need an array where you will have details of your all locations.

var locationArray = [
     {
	"locationName": "Test 1", // It will show the marker's name on the map
	"locationLatitude": -31.56391, // Here's the Latitude of the location will be given
	"locationLongitude": 147.154312 // Here's the Longitude of the location will be given
     },
     {	
        "locationName": "Test 2",	
        "locationLatitude": -33.718234,	
        "locationLongitude": 150.363181     
     }
];

The array given above is this time we have to use the Map API wherever it is called. The following is given for example.

if ( typeof locationArray !== 'undefined' && locationArray.length > 0 ) {
    $.map( locationArray, function( val, key ) {
	const marker = new google.maps.Marker( {
	    position: { 
                lat: locationArray[ key ].locationLatitude, 
                lng:  locationArray[ key ].locationLongitude 
            },
	    map: map,
	    title: locations[ key ].locationName,
	    icon: "/assets/images/iconMapStore.svg", //Here you can give the icon on your own. 
	    optimized: true 
         } );
         markers.push( marker );
    } );
    var markerCluster = new markerClusterer.MarkerClusterer( 
      { 
        markers, 
        map // Where the variable "new google.maps.Map" of the map show will be, it will be add.
      } 
    );
}

If you want to delete the marker then you have to use it.

markerCluster.clearMarkers();

“Marker Clustering” with Autocomplete Map. Follow the full code is given below. Hopefully will understand.

var locationArray = [
     {
	"locationName": "Test 1",
	"locationLatitude": -31.56391,
	"locationLongitude": 147.154312
     },
     {	
        "locationName": "Test 2",	
        "locationLatitude": -33.718234,	
        "locationLongitude": 150.363181     
     }
];

initMap( locationArray );

function initMap( locations ) {
     const map = new google.maps.Map( document.getElementById( "map" ), {
	center: { lat: 40.749933, lng: -73.98633 },
      	zoom: 3,
	mapTypeControl: true,
     } );
     const input = document.getElementById( "address" ); // HTML input ID

     const options = {
	fields: ["address_components", "formatted_address", "geometry", "name"],
	strictBounds: false,
     };

     const autocomplete = new google.maps.places.Autocomplete(
	input,
	options
     );

     // Bind the map's bounds (viewport) property to the autocomplete object,
     // so that the autocomplete requests use the current map bounds for the
     // bounds option in the request.
     autocomplete.bindTo( "bounds", map );

     const infowindow = new google.maps.InfoWindow();
     const infowindowContent = document.getElementById( "infowindow-content" );

     infowindow.setContent( infowindowContent );
	
     if ( typeof locations !== 'undefined' && locations.length > 0 ) {
	$.map( locations, function( val, key ) {
	    const marker = new google.maps.Marker( {
		position: { 
                   lat: locations[ key ].locationLatitude, 
                   lng:  locations[ key ].locationLongitude 
                },
		map: map,
		title: locations[ key ].locationName,
		icon: "/assets/images/iconMapStore.svg",
		optimized: true 
	     } );
	     markers.push( marker );
         } );
         var markerCluster = new markerClusterer.MarkerClusterer( 
            { markers, map } 
         );
     }

     autocomplete.addListener( "place_changed", () => {
	autocompletePlaceChanged( markers, autocomplete, map, infowindowContent, infowindow, markerCluster );
     } );
}

function autocompletePlaceChanged( markers, autocomplete, map, infowindowContent, infowindow, markerCluster ) {
	infowindow.close();
	deleteOverlays( markers );
	markerCluster.clearMarkers();

	const place = autocomplete.getPlace();

	if ( !place.geometry || !place.geometry.location ) {
		// User entered the name of a Place that was not suggested and
		// pressed the Enter key, or the Place Details request failed.
		window.alert( "No details available for input: '" + place.name + "'" );
		return;
	}

	// If the place has a geometry, then present it on a map.
	if ( place.geometry.viewport ) {
		map.fitBounds( place.geometry.viewport );
	} else {
		map.setCenter( place.geometry.location );
		map.setZoom( 5 );
	}

	const marker = new google.maps.Marker( {
		position: place.geometry.location,
		map: map,
		icon: includeBaseURL + "/assets/images/iconLocation.svg"
	} );

	infowindowContent.children[ "place-name" ].textContent = place.name;
	infowindowContent.children[ "place-address" ].textContent = place.formatted_address;
	infowindow.open( map, marker );
	markers.push( marker );

	// address data set in hidden field
	let address1 = "";
	let stateFromAddress = "";
	let cityFromAddress = "";
	let postcode = "";

	for ( const component of place.address_components ) {
		// @ts-ignore remove once typings fixed
		const componentType = component.types[ 0 ];

		switch ( componentType ) {
			case "street_number": {
				address1 = `${component.long_name} ${address1}`;
				break;
			}
	
			case "route": {
				address1 = `${address1} ${component.short_name}`;
				break;
			}

			case "locality": {
				cityFromAddress = component.long_name;
				break;
			}

			case "postal_code": {
				postcode = `${component.long_name}${postcode}`;
				break;
			}
	
			case "postal_code_suffix": {
				postcode = `${postcode}-${component.long_name}`;
				break;
			}

			case "administrative_area_level_1": {
				stateFromAddress = component.short_name;
				break;
			}

		}
	}
	
	
	// "address1" variable is for street address
        // "cityFromAddress" variable is for street city
        // "postcode" variable is for street Zip Code
        // "stateFromAddress" variable is for street state
}

function deleteOverlays( markersArray ) {
	for ( var i = 0; i < markersArray.length; i++ ) {
		markersArray[i].setMap( null );
	}
}