Marker Clustering Google Maps in JavaScript
Tags: javascript, webdev, beginners, programming
Published: 2022-05-16 12:06:25

---
canonical_url: https://softauthor.com/google-map-marker-clustering-javascript/
---

In this short tutorial, I’m going to show how to implement Marker Clustering on Google Maps in JavaScript.

###Add Google Maps JavaScript SDK

Add the following Google Maps API JavaScript SDK to your index.html.

```JavaScript
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=[YOUR_API_KEY]"></script>
```

Replace [YOUR_API_KEY] with your actual Google Maps API Key.

If you do not have one, go ahead and [Create an API Key from Google Cloud Console](https://softauthor.com/google-maps-api-key/).

###Create A Google Map Object

Let’s create a Google Map view full screen on the browser window.

Create a simple div HTML element with an id called map.

```HTML
<div id="map"></div>
```

Define a CSS rule to make the div full screen so that the map inside it will appear full screen as well later.

```CSS
html,
body {
    height: 100%;
    margin: 0;
}

#map {
    width: 100%;
    height: 100%;
    background: red;
    border: 5px solid red;
    box-sizing: border-box;
}
```

>_Learn a few ways to [make a div full screen on the browser](https://softauthor.com/css-make-a-div-height-full-screen/)_.

Finally, declare a map object with your desired geographic coordinates.

I used Ottawa in this case.

```JavaScript
const map = new google.maps.Map(document.getElementById('map'), {
    zoom: 15,
    center: {
        lat: 45.424721,
        lng: -75.695000
    },
    mapTypeId: google.maps.MapTypeId.ROADMAP
});
```

![alt text](https://softauthor.com/wp-content/uploads/2022/05/Google-Maps-Marker-Clustering-in-JavaScript-Show-Google-Map-On-The-Screen.png)

###Get Places Using Nearby Search Request

Now let’s get the markers on the map using Nearby Search Request.

Here is the Nearby Search Request URL which is part of Google Maps Places API.

```JavaScript
const URL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=45.424721,-75.695000&type=restaurant&radius=1000&key=[YOUR_API_KEY]";

fetch(URL)
.then(response => {
    return response.json();
}).then(response => {
    console.log(response.results)

}).catch(error => {
    console.log(error);
});
```

When you make an HTTP request to the Places API from your frontend app, you will get this ugly CORS Error.

![alt text](https://softauthor.com/wp-content/uploads/2022/05/Google-Maps-Marker-Clustering-in-JavaScript-CORS-Error.png)

To get rid of the CORS error, append the proxy URL to the base URL.

```JavaScript
const URL = "https://cors-anywhere.herokuapp.com/https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=45.424721,-75.695000&type=restaurant&radius=1000&key=[YOUR_API_KEY]";
```

That should get rid of CORS error.

>[_Learn more ways to fix CORS error._](https://softauthor.com/cors-error-solution-in-a-nutshell/)

Sometimes you may get the 403 forbidden error because of the limitation of using a proxy URL.

You can fix it by going to the below URL and requesting temporary access to it.

```JavaScript
https://cors-anywhere.herokuapp.com/corsdemo
```

Once the request is successful, you’ll get the data for the first 20 places.

![alt text](https://softauthor.com/wp-content/uploads/2022/05/Google-Maps-Marker-Clustering-in-JavaScript-Get-Places-Data.png)

###Show Places Markers On The Maps

Now that we have places data, let’s shows them on Google Maps using Markers.

Loop through the response data and get the latitude and longitude values from it. Instantiate the marker object on each loop, passing the latitude and longitude values as well as map to it.

```JavaScript
response.results.forEach(place => {
    const lat = place.geometry.location.lat;
    const lng = place.geometry.location.lng;
    let marker = new google.maps.Marker({
        position: new google.maps.LatLng(lat, lng),
        map: map
    });
})
```

![alt text](https://softauthor.com/wp-content/uploads/2022/05/Google-Maps-Marker-Clustering-in-JavaScript-Show-Markers-On-The-Google-Maps.png)

###Marker Clustering On The Google Maps

To add the clustering functionality to the markers, you’ll need to include the Marker Clustering JavaScript library in your index.html.

```JavaScript
<script src="https://unpkg.com/@googlemaps/markerclusterer@2.0.2/dist/index.min.js"></script>
```

Finally, instantiate the markerClusterer object and pass the map and markers where they need to appear.

To accumulate all the markers into an array, define an array called markers outside of fetch() request and push each marker to the markers array inside the forEach loop.

```JavaScript
const markers = [];

fetch(URL)
.then(response => {
    return response.json();
}).then(response => {

    response.results.forEach(place => {
        const lat = place.geometry.location.lat;
        const lng = place.geometry.location.lng;
        let marker = new google.maps.Marker({
            position: new google.maps.LatLng(lat, lng),
            map: map
        });
        markers.push(marker);
    });

    new markerClusterer.MarkerClusterer({
        map,
        markers
    });

}).catch(error => {
    console.log(error);
});
```

![alt text](https://softauthor.com/wp-content/uploads/2022/05/Google-Maps-Marker-Clustering-in-JavaScript-Show-Markers-Clustering.png)

There you’ve have it.

If you’re any question or suggestion about marker clustering, please comment below and I’ll get back to as soon as I can.

Happy coding!