Using JSON multi markers for marker clustering on Google Maps

I have successfully created a map with multiple markers generated from a JSON file. However, I am encountering an issue when trying to implement a marker cluster - instead of displaying the cluster separately, both the cluster and markers are showing up simultaneously. Here is the current view: https://i.sstatic.net/LvLvP.png

In order to add the marker cluster feature, I included the following script in my index.html page:

<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"></script>

Below is the relevant section of my maps.js file:

    let map;
let jsonData = "assets/Data/maps.json";

const countries = [
    { lat: 48.857497, lng: 2.347628, zoom: 5, name: "France" },
    //Brazil
    { lat: -15.793889, lng: -47.882778, zoom: 5, name: "Brazil" }
];


function initMap() {
    const mapOptions = {
        center: {
            lat: 9.072264,
            lng: 7.491302
        },
        zoom: 2,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map"), mapOptions);
    countries.forEach(function (data) {
        let countriesMarker = new google.maps.Marker({
            map: map,
            position: { lat: data.lat, lng: data.lng },
            title: data.name
        });
        $("#selectlocation").append('<option value="' + [data.lat, data.lng, data.zoom].join('|') + '">' + data.name + '</option>');
    });


    let infowindow = new google.maps.InfoWindow();

    //Method found on StackOverflow: https://stackoverflow.com/questions/28606149/load-data-from-json-file-into-map-markers-in-google-maps
    $.getJSON(jsonData, function (jsonMarkers) {
        $.each(jsonMarkers.markers, function (key, data) {
            let latLng = new google.maps.LatLng(data.lat, data.lng);
            let marker = new google.maps.Marker({
                position: latLng,
                map: map,
                title: data.title
            });

            var clusterMarkers = jsonMarkers.markers.map(function (location) {
                return new google.maps.Marker({
                    position: location
                });
            });
            var markerCluster = new MarkerClusterer(map, clusterMarkers,
                { imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m' });

        });

    });
}

Answer №1

You seem to be facing multiple issues that need attention.

  1. It appears that you are creating the markers twice, as mentioned by @xomena. Make sure to remove one set of the redundant code.

  2. Additionally, you are creating a MarkerClusterer for each marker inside a loop. To resolve this, move the creation of the MarkerClusterer outside the loop responsible for creating the markers.

To address these concerns and optimize your code, consider implementing something like the following:

$.each(jsonMarkers.markers, function (key, data) {
  let latLng = new google.maps.LatLng(data.lat, data.lng);
  let marker = new google.maps.Marker({
    position: latLng,
    map: map,
    title: data.title
  });
  clusterMarkers.push(marker);
});
var markerCluster = new MarkerClusterer(map, clusterMarkers,
  { imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});

For a demonstration of the suggested solution, refer to this proof of concept fiddle.

Here is the updated code snippet:

 // Updated JavaScript Code
let map;
let jsonData = "assets/Data/maps.json";

const countries = [
    { lat: 48.857497, lng: 2.347628, zoom: 5, name: "France" },
    { lat: -15.793889, lng: -47.882778, zoom: 5, name: "Brazil" }
];

// Function to initialize the map
function initMap() {
    const mapOptions = {
        center: {
            lat: -19.072264,
            lng: 117.491302
        },
        zoom: 1,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map"), mapOptions);
    
    // Adding markers for predefined countries
    countries.forEach(function (data) {
        let countriesMarker = new google.maps.Marker({
            map: map,
            position: { lat: data.lat, lng: data.lng },
            title: data.name
        });
        $("#selectlocation").append('<option value="' + [data.lat, data.lng, data.zoom].join('|') + '">' + data.name + '</option>');
    });

    let infowindow = new google.maps.InfoWindow();
    let clusterMarkers = [];
    
    // Create and cluster additional markers from JSON data
    var jsonMarkers = {markers: [
        // Include your marker coordinates here as needed
      ]};
    $.each(jsonMarkers.markers, function (key, data) {
        let latLng = new google.maps.LatLng(data.lat, data.lng);
        if (!data.title)
          data.title = ""+key;
        let marker = new google.maps.Marker({
            position: latLng,
            map: map,
            title: data.title
        });

        clusterMarkers.push(marker);
    });
    
    // Apply MarkerClusterer to manage clustered markers
    var markerCluster = new MarkerClusterer(map, clusterMarkers,
      { imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
    });
}
#map {
  height: 100%;
}
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="map"></div>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"></script>
<!-- Don't forget to replace the key parameter with your own API key before deployment -->
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY_HERE&callback=initMap"></script>

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

What could be causing Wordpress Jquery to only function properly after a page refresh?

Here is the code snippet I am working with: <script type="text/javascript"> jQuery( document ).ready(function() { jQuery('#bookbtn_loc_1').on('click', function(event){ jQuery("a.da-close").click(); ...

What is the process for generating a custom Firebase Authentication token in Node.js without using a service account JSON file?

I am looking to generate a custom token without relying on a service account json file. I have attempted the following configuration options: https://firebase.google.com/docs/auth/admin/create-custom-tokens#using_a_service_account_id https://firebase.goog ...

AngularJS: Mastering the art of structuring a single route application

Exploring the best approach to utilize Angular's features for a specific problem I'm working on. The app I am developing will be a single page application with only one route, devoid of any other URL states. It seems like controllers and views c ...

React-router can manage non-matching paths by utilizing a basic JavaScript router configuration

Is there a way to manage non-matching paths using plain JavaScript in React router configuration? const rootRoute = { component: 'div', childRoutes: [ { path: '/', component: App, childRoutes: [ requir ...

Developing a custom jQuery plugin that incorporates the getJSON method within its functionality

There seems to be some confusion regarding the asynchronous nature of the getJSON function. I suspect that this could be the reason for the issue, but I lack a clear understanding of how it operates. When I invoke the healthCheck method in my js file on th ...

Magnific Popup displaying only the initial item

As someone new to using jQuery and Magnific Popup, I am working on a grid of images. When an image is clicked, I want Magnific Popup to display a specific div containing information relevant to that particular image. <div class="grid"> <div c ...

Bootstraps paves the way for the destruction of a dropdown element

https://getbootstrap.com/docs/4.0/components/dropdowns/ $().dropdown('dispose') Erases the dropdown functionality of an element. What exactly does this mean? Does it remove the tag entirely? Does it render the tag unusable as a dropdown lis ...

JavaScript - convert the values of an array within a JSON object into separate strings

I am receiving a JSON object from an API, and my next step involves some string analysis of each key value. This process works perfectly for 90% of the objects I receive because the key values are strings. { ID: '0012784', utm_source: 'webs ...

Can you help me with sorting asynchronous line points for KineticJS?

For the past couple of days, I've been grappling with a peculiar issue that I found difficult to articulate in the title. The challenge I'm facing involves a KineticJs Line, which contains an array of points (line.attrs.points) represented as ob ...

Using Javascript or ES6, you can compare a nested array object with another array of elements and generate a new array based on

I am dealing with a complicated array structure as shown below sectionInfo = [{id: 1, name:'ma'}, {id: 2, name:'na'}, {id: 3, name:'ra'}, {id: 4, name:'ka'}, {id: 5, name:'pa'}]; abc = [{id:'1' ...

Error message "undefined" occurs while searching for systemuserid in CRM 2011

Below is a code snippet that evaluates a JSON data and seems to return "undefined" for the systemuserid field, even though the data clearly shows it is available. Any help on this would be greatly appreciated. { "d" : { "results": [ { ...

Exploring the mechanics of callbacks in jQuery's Ajax functionality

Greetings fellow developers! I've embarked on a new programming project with the firm intention of writing cleaner and more easily maintainable code than ever before. However, I have encountered my old nemesis - jQuery AJAX returns. The last time I t ...

Nuxt and Express server are unable to receive API requests when in production mode and the /dist directory

My Nuxt app is running smoothly on my local server, with all API requests working perfectly using the serverMiddleware property in nuxt.config.js. However, when I run yarn generate, the path to the API server gets lost and no data is loaded. Here are some ...

Is JavaScript the Key to Navigating Through a Website?

I am faced with the challenge of creating a script to extract a database from a website. The website's main page features a table where each row contains a link to another page that holds the desired database. Currently, my script can successfully e ...

Serialization of Passport Session failed due to a Bad Gateway error

I am currently utilizing the following dependencies: express session passport passport-local passport-local-mongoose Upon registering a user and posting the data, the information is successfully saved to the database, but a bad request error is generated ...

What is the best way to swap out the outdated schemas for the updated ones?

Hello there! I have some schemas set up like this: { user: '123', code: 'abc', uses: [...] }, { user: '123', code: 'def', uses: [...] }, and my goal is to transform them into this format: { user: '123', co ...

Efficiently assign multiple attributes using a single d3 function

Hey everyone! I'm currently working with SVG lines and have come across an example object that looks like this: { _id: 5, coordinates:{ x1: 100, y1: 100, x2: 500, y2: 500, } Now, imagine I have an array of these obje ...

Can we create a command that searches for the argument input in a JSON file and then displays all the findings in a Discord embed?

I'm working on a command where users can enter the name of a state as an argument. The client then searches through the voter.json file to find dictionaries with the matching state. Currently, the code is functioning but it sends each result in a sepa ...

Retrieve the Checkbox id of a material-ui checkbox by accessing the object

I'm currently working on extracting the id of a Checkbox object in my JSX code. Here's how I've set it up: <div style={{display: 'inline-block', }}><Checkbox id='q1' onclick={toggleField(this)}/></div> ...

Tips for Hosting Multiple Websites with Unique Domain Names on One Web Hosting Account

I am currently seeking recommendations for mechanisms that would work well in my specific situation. After trying out the iframe solution, I realized it was not suitable due to responsiveness issues on the website. I then looked into using a responsive i ...