Implementing a basic marker clustering feature in the Google Maps application

I'm currently experiencing issues with implementing marker clusterer functionality on my map. I am trying to use a custom icon for each marker and have individual info windows that are editable.

I was able to achieve this, but now I am facing difficulties in adding the marker clusterer library functionality. I came across information about adding markers to an array, but I am unsure about the exact implications of that. Additionally, I have not found any examples with arrays that include info windows, and upon examining the code, I couldn't identify a suitable method to incorporate them.

Below is the code snippet I am working with (mostly sourced from Geocodezip.com):

    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> 
    <script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/src/markerclusterer.js"></script>
    <style type="text/css">
    html, body { height: 100%; } 
    </style>
<script type="text/javascript"> 
//<![CDATA[
var map = null;
function initialize() {
  var myOptions = {
    zoom: 8,
    center: new google.maps.LatLng(43.907787,-79.359741),
    mapTypeControl: true,
    mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
    navigationControl: true,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  map = new google.maps.Map(document.getElementById("map_canvas"),
                                myOptions);

var mcOptions = {gridSize: 50, maxZoom: 15};
var mc = new MarkerClusterer(map, [], mcOptions);

      google.maps.event.addListener(map, 'click', function() {
            infowindow.close();
            });

      // Add markers to the map
      // Set up three markers with info windows 

          var point = new google.maps.LatLng(43.65654,-79.90138); 
          var marker1 = createMarker(point,'Abc');

          var point = new google.maps.LatLng(43.91892,-78.89231);
          var marker2 = createMarker(point,'Abc');

          var point = new google.maps.LatLng(43.82589,-79.10040);
          var marker3 = createMarker(point,'Abc');

          var markerArray = new Array(marker1, marker2, marker3);
          mc.addMarkers(markerArray, true);


}

var infowindow = new google.maps.InfoWindow(
  { 
    size: new google.maps.Size(150,50)
  });

function createMarker(latlng, html) {
    var image = '/321.png';
    var contentString = html;
    var marker = new google.maps.Marker({
        position: latlng,
        map: map,
        icon: image,
        zIndex: Math.round(latlng.lat()*-100000)<<5
        });

    google.maps.event.addListener(marker, 'click', function() {
        infowindow.setContent(contentString); 
        infowindow.open(map,marker);
        });
}

//]]>
</script> 

Answer №1

Check out the operational jsfiddle demo

If you want to add markers to a marker cluster, MarkerClusterer offers support through the addMarker() and addMarkers() methods. Alternatively, you can provide an array of markers directly to the constructor:

Adding markers to the constructor using an array of markers can be done as shown below:

var markers = [];  //initialize a global array to store markers
for (var i = 0; i < 100; i++) {
  var latLng = new google.maps.LatLng(data.photos[i].latitude,
      data.photos[i].longitude);
  var marker = new google.maps.Marker({'position': latLng});
  markers.push(marker);  //add each marker to the global array
}
var markerCluster = new MarkerClusterer(map, markers);  //create clusterer and add the global array of markers

To add a marker using addMarker(), you can do so by following this pattern:

var markerCluster //cluster object created on global scope

//create your marker and add it like this:
markerCluster.addMarker(newMarker, true); //specifying true will redraw the map

Alternatively, if you prefer adding an array of markers:

var markerCluster //cluster object created on global scope

//create your markers and push them onto the array of markers:
markerCluster.addMarkers(newMarkers, true); //specifying true will redraw the map

For more information, refer to MarkerClusterer and Simple Examples

Based on the snippet of your code, you may need to modify it as follows:

var mcOptions = {gridSize: 50, maxZoom: 15};
var mc = new MarkerClusterer(map, [], mcOptions);

google.maps.event.addListener(map, 'click', function() {
    infowindow.close();
});

// Add markers to the map
// Set up three markers with info windows 

var point = new google.maps.LatLng(43.65654,-79.90138); 
var marker1 = createMarker(point,'Abc');

var point = new google.maps.LatLng(43.91892,-78.89231);
var marker2 = createMarker(point,'Def');

var point = new google.maps.LatLng(43.82589,-79.10040);
var marker3 = createMarker(point,'Ghi');

var markerArray = new Array(marker1, marker2, marker3);
mc.addMarkers(markerArray, true);

Make sure to correct the naming of your markers in the createMarker function to avoid overwriting them. Also, ensure that the function returns the marker for clustering purposes:

function createMarker(latlng, html) {
    var contentString = html;
    var marker = new google.maps.Marker({
        position: latlng,
        map: map,
        zIndex: Math.round(latlng.lat() * -100000) << 5
    });

    google.maps.event.addListener(marker, 'click', function() {
        infowindow.setContent(contentString);
        infowindow.open(map, marker);
    });

    return marker;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to create a CSS animation that gradually darkens a background image during a

Currently in the process of constructing a page with an intriguing background image: body { background:url(images/bg.png) center center no-repeat fixed; -webkit-background-size:cover; -moz-background-size:cover; -o-background-size:cover; ...

Introduce a pause interval between successive ajax get calls

I've created a script that uses an ajax GET request when the user reaches near the end of the page. $(function(){ window.addEventListener('scroll', fetchImages); window.addEventListener('scroll', fetchNotifications); }); ...

Ways to customize the TextInput component in React-Admin

I am facing a challenge with overriding specific fields in my custom theme. It seems that setting the custom theme also overrides other fields unintentionally. I attempted to use useStyles to resolve this issue, but unfortunately, it did not work as expec ...

Using the onMessage event in React Native WebView does not seem to have any functionality

I'm having trouble with the onMessage listener in React Native's WebView. The website is sending a postMessage (window.postMessage("Post message from web");) but for some reason, the onMessage listener is not working properly. I can't figure ...

Attach an event listener to a class, then use the removeEventListener method to detach the listener and eliminate any remaining references, ensuring proper functionality of the

When creating a class in JavaScript, a normal function returns the class object. However, events return the event object and the class object is lost: function class(a){ this.name=a; document.addEventListener('click',this.click,false); xhr.add ...

Save and retrieve documents within an electron application

Currently, I am developing an application that will need to download image files (jpg/png) from the web via API during its initial run. These files will then be stored locally so that users can access them without requiring an internet connection in the fu ...

Adding items dynamically to a React-Bootstrap accordion component can enhance the user experience and provide a

I am retrieving data from a database and I want to categorize them based on "item_category" and display them in a react-bootstrap accordion. Currently, my code looks like this: <Accordion> { items.map((item, index) => ...

Customize React JS Material UI's InputBase to be responsive

https://i.stack.imgur.com/9iHM1.gif Link: codesandbox Upon reaching a certain threshold, like on mobile devices, the elements inside should stack vertically instead of horizontally, taking up full length individually. How can this be achieved? ...

Insert an element into a JSON collection

I am currently working on a JavaScript function that utilizes an ajax call to retrieve data from an API in the form of a JSON array. Here is a snippet of the array structure that I receive: [ { "ErrorType": "Errors", "Explanations": [ { ...

I can't seem to figure out why I constantly struggle with adding a check mark to a checkbox using

Take a look at the code I've provided below : HTML : <input type="checkbox" name="xyz[1][]" id="sel_44" style="margin:2px;" value="12345" onclick="myClick(this)"> Javascript : <script> $('#sel_44').attr("checked", true); < ...

Unable to access a value from an object in Node.JS/MongoDB platform

I'm seeking assistance with my NodeJs project. The issue I am facing involves checking the seller's name and setting the newOrder.support to match the seller's support internally. Despite logging the correct value within the findOne() func ...

What methods can I use to ensure this car rotates smoothly, whether or not I combine meshes in Three.js?

My current challenge involves creating a car game here. The issue is that although the wheels are rotating, they are not moving in sync with the car itself. Here is the code snippet from my car.js file: export function createCar(x, y, z, color) { const ...

Inserting an item into ng-model within a dropdown menu

I have a select box populated with data from my backend. This data is an array of objects: [Object { superkund_id="4", nod_id="12068", namn="Växjö Fagrabäck"}, Object { superkund_id="5", nod_id="9548", namn="Halmstad Bågen / Pilen"}] I am using ng-o ...

When utilizing npm install buefy and npm install font-awesome, there may be an unnecessary display of [email protected] and [email protected] extraneous errors

After installing buefy and font-awesome, I noticed that it is marked as extraneous and the folder appears with an arrow icon but is empty. How can this issue be resolved? For example: +-- <a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

Verify Session Cookies through JSONP requests

I've developed a bookmark that pulls all images from a webpage upon clicking and sends the image's src back to another server using JSONP. Challenge: The remote server must validate session authentication cookies to confirm that the user sending ...

Issue with host header detected in MERN stack configuration

"proxy": "https://mango-artist-rmdnr.pwskills.app:5000", While attempting to establish a connection between my frontend and backend, I encountered an issue with an invalid host header. The backend is operating on port 5000, and the fr ...

Express application receiving repetitive post requests

Recently, I have been working on developing a YouTube video conversion app that utilizes youtube-dl for streaming videos from YouTube and saving them. Everything was going smoothly until I encountered an issue when trying to stream a video that exceeded on ...

Guide on adjusting the resolution/density of images in JPEG/PNG using JavaScript

I am looking for a way to adjust the resolution/density of JPG/PNG images using JavaScript. The purpose of this adjustment is to provide accurate metadata on the number of pixels per inch (DPI/PPI) to be used for printing by a third-party API. Is there a ...

Count up with HTML like a progressive jackpot's increasing value

I am interested in developing a progressive jackpot feature similar to the sample image provided. I would like the numbers to loop periodically. Can anyone advise me on how to achieve this effect? Any suggestions or examples, preferably using JavaScript o ...

Using a variable to store the value of the id attribute in HTML code

How can I dynamically add an ID attribute to an HTML element using a variable declared in JavaScript? Using jQuery var table_row = $('table').find('tr#' + pid); var name = table_row.find('td:nth-child(1)').html(); table_ ...