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.
<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.
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.
<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.
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.
Finally, declare a map object with your desired geographic coordinates.
I used Ottawa in this case.
const map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
center: {
lat: 45.424721,
lng: -75.695000
},
mapTypeId: google.maps.MapTypeId.ROADMAP
});
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.
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.
To get rid of the CORS error, append the proxy URL to the base URL.
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.
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.
https://cors-anywhere.herokuapp.com/corsdemo
Once the request is successful, you’ll get the data for the first 20 places.
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.
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
});
})
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.
<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.
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);
});
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!
Top comments (0)