Google Maps Marker Cluster Options

Google Maps Marker Cluster Options

Google Maps provides marker clustering functionality to group markers together when they are close to each other on the map. This helps in enhancing the map’s readability and performance by reducing the number of markers displayed at once. To use marker clustering, you need to enable the MarkerClusterer library and configure the cluster options.

Prerequisites

  • Create a Google Maps API project and obtain an API key.
  • Include the Google Maps JavaScript API and the MarkerClusterer library in your HTML file.

Example

Let’s imagine we have an array of markers, and we want to cluster them on our map. Here’s how you can accomplish that:

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"></script>
<script>
  function initMap() {
    var map = new google.maps.Map(document.getElementById("map"), {
      zoom: 10,
      center: { lat: 37.7749, lng: -122.4194 }
    });
    
    var markers = [
      new google.maps.Marker({ position: { lat: 37.7749, lng: -122.4194 } }),
      new google.maps.Marker({ position: { lat: 37.775, lng: -122.42 } }),
      // ... add more markers as needed
    ];
    
    var markerCluster = new MarkerClusterer(map, markers, {
      imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m',
      gridSize: 50,
      maxZoom: 15
    });
  }
</script>
<div id="map" style="height: 400px; width: 100%;"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"></script>

In the above example, we first load the Google Maps API and the MarkerClusterer library using script tags. Inside the initMap function, we create a new Map instance with a specific zoom level and center coordinates.

Next, we define an array of markers with their individual coordinates. You can add more markers to this array as needed.

Finally, we initialize the MarkerClusterer by providing it the map instance, the markers array, and an optional configuration object. In this example, we set the imagePath to specify the image used as the cluster icon, gridSize to control the distance between clusters, and maxZoom to limit the maximum zoom level at which clustering is applied.

We then create a <div> element with an id of “map” where the map will be rendered. The height and width are set to 400px and 100% respectively, but you can modify these according to your requirements.

Finally, we load the Google Maps API asynchronously with your API key and specify the callback function as initMap to initialize the map when the API is ready.

Similar post

Leave a comment