Troubleshoot my code for clustering markers on a Google map

I'm currently working on a piece of code to generate a Google map that contains 3 hidden points within one marker. The idea is that when the main marker is clicked, these points will either merge into one or expand into 3 separate markers. However, I'm facing an issue where the map is not showing up. Can someone please take a look at my code and help me identify any potential problems?

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>favorite cities</title>
    <style>
      html, body, #map-canvas {
        height: 100%;
        margin: 0px;
        padding: 0px
      }
    </style>
   <script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
    <script>
      (function() {
        window.onload = function(){
          var options = {
            zoom: 3,
            center: new google.maps.LatLng(37.99, -93.77),
            mapTypeId: google.maps.MapTypeId.ROADMAP
          };
          var map = new google.maps.Map(document.getElementById('map'), options);
          
          var mgr = new MarkerManager(map);
          var A = new google.maps.Marker({
            position: new google.maps.LatLng(37.99, -93.77),
            icon: 'img/cluster.png'
          });
          google.maps.event.addListener(A, 'click', function() {
            map.setZoom(7);
            map.setCenter(Kloof.getPosition());
          });
          
          var Cities = [A];
          var Schools = [
            //School1
       new google.maps.Marker({position: new google.maps.LatLng(38.99, -93.97)}),
                                    //School2
       new google.maps.Marker({position: new google.maps.LatLng(37.89, -94.77)}),
                                    //School3
       new google.maps.Marker({position: new google.maps.LatLng(37.79, -95.77)})
                                    ];
                                    google.maps.event.addListener(mgr, 'loaded', function() {
                                    agr.addMarkers(Cities, 11, 6);
                                    agr.addMarkers(Schools, 6);
                                    agr.refresh
                                   });
                                   };
                                   })();
    </script>
  </head>
  <body>
    <div id="map-canvas"></div>
  </body>
</html>

Answer №1

Modify:

var map = new google.maps.Map(document.getElementById('map-canvas'), options);

To:

var map = new google.maps.Map(document.getElementById('new-map-canvas'), options);

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>popular destinations</title>
    <style>
      html, body, #new-map-canvas {
        height: 100%;
        margin: 0px;
        padding: 0px
      }
    </style>
   <script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
    <script>
      (function() {
        window.onload = function(){
          var options = {
            zoom: 3,
            center: new google.maps.LatLng(37.99, -93.77),
            mapTypeId: google.maps.MapTypeId.ROADMAP
          };
          var map = new google.maps.Map(document.getElementById('new-map-canvas'), options);
          
          var mgr = new MarkerManager(map);
          var A = new google.maps.Marker({
            position: new google.maps.LatLng(37.99, -93.77),
            icon: 'img/cluster.png'
          });
          google.maps.event.addListener(A, 'click', function() {
            map.setZoom(7);
            map.setCenter(Kloof.getPosition());
          });
          
          var Cities = [A];
          var Schools = [
            //SChool1
       new google.maps.Marker({position: new google.maps.LatLng(38.99, -93.97)}),
                                    //School2
       new google.maps.Marker({position: new google.maps.LatLng(37.89, -94.77)}),
                                    //School3
       new google.maps.Marker({position: new google.maps.LatLng(37.79, -95.77)})
                                    ];
                                    google.maps.event.addListener(mgr, 'loaded', function() {
                                    agr.addMarkers(Cities, 11, 6);
                                    agr.addMarkers(Schools, 6);
                                    agr.refresh();
                                   });
                                   };
                                   })();
    </script>
  </head>
  <body>
    <div id="new-map-canvas"></div>
  </body>
</html>

Answer №2

After some modifications, the code now looks like this:

<
    var schoolArray = []; //Keeping track of POINTS in a global array
    var SchoolPoints = [[-29.788911, 30.852721, 'Thomas More College'], //Global array storing MARKERS
                [-29.781297, 30.838465, 'Kloof Senior Primary School'],
                [-29.827008, 30.881706, 'Pinetown Boys HighSchool']];  

    function initialize() { //Setting up the google map and its appearance on my dashboard
    var myOptions = {
        zoom: 9,
        center: new google.maps.LatLng(-29.807762, 30.854261),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

  var mcOptions = { //Determining tile grid size for clustering schools points
        gridSize: 25,
        maxZoom: 20
    };
  var mc = new MarkerClusterer(map, [], mcOptions); //Creating blue initial cluster on the map

  google.maps.event.addListener(map, 'click', function() { //Map zooms in and displays 3 schools with separate markers upon click
        infowindow.close();
    });

    // Adding markers to the map and sorting them into clusters
  for(var i=0; i<SchoolPoints.length; i++){ //Placing markers on the map based on points array elements
         createMarker(new google.maps.LatLng(SchoolPoints[i][0], SchoolPoints[i][1]), SchoolPoints[i][2]);
    }
    
  mc.addMarkers(schoolArray , true); //Clustering markers together in the blue symbol
}

  var infowindow = new google.maps.InfoWindow({ //Defining info window size for school points display
    size: new google.maps.Size(500, 250)
});

  function createMarker(latlng, html) { //Creating individual markers
    var contentString = html;
    var marker = new google.maps.Marker({
        position: latlng,
        map: map,
        icon: '',       
    });

  marker.setAnimation(google.maps.Animation.DROP); //Adding drop animation for marker aesthetics
    
  google.maps.event.addListener(marker, 'click', function() { //Displaying info windows upon clicking markers
    infowindow.setContent(contentString); 
        infowindow.open(map, marker);
    });
    
    schoolArray.push(marker); 
}

window.onload = initialize;
 
​

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

The ƒ character doesn't seem to be a match for the JavaScript regex

I am facing a requirement to only allow (extended) ASCII characters in my input. As a solution, I've implemented a JavaScript regex pattern like this: /^[\x20-\xff]+$/.test("helloê¿£×جáƒ") However, this doesn't work as expect ...

Preserving data in input fields even after a page is refreshed

I've been struggling to keep the user-entered values in the additional input fields intact even after the web page is refreshed. If anyone has any suggestions or solutions, I would greatly appreciate your assistance. Currently, I have managed to retai ...

Is there a way to alter the format of a URL?

I'm utilizing the ytdl-core library to access a URL for audio content. The provided URL is: https://r2---sn-gwpa-w5py.googlevideo.com/videoplayback?expire=1612552132&ei=ZEMdYNnJDumPz7sPyrSLmAw&ip=49.36.246.217&id=o-AFQLS1cSUJ6_bXBjMOIiWk1N ...

Utilizing a single variable across different JavaScript scripts - where one script includes a .ready function while the other does not

I am facing a challenge with 2 javascript scripts that I have: <script type="text/javascript"> function capture(){ var canvas = document.getElementById('canvas'); var video = document.getElementById('video'); canvas.getContext ...

Unfortunately, I am unable to transmit a cookie using the res.cookie method in Express

After setting up the route to send a JWT with a cookie, I'm unable to see it in my browser. Here's the code for the route: router.post('/signup', async (req, res) => { const { email, password } = req.body try { const ...

Displaying default tab content while hiding other tab content in Javascript can be achieved through a simple code implementation

I have designed tabs using the <button> element and enclosed the tab content within separate <div></div> tags like shown below: function displayTab(evt, tabName) { var i, tabcontent, tablinks; tabcontent = document.getElementsB ...

Change the text field's border color if the field is not empty

On my website, there is a TextField where users can enter values to perform a site search. My question pertains to the border color of this field. Normally, the border color is black when the field is not in use. However, when a user clicks on the field an ...

When an accordion is clicked, the content is dynamically loaded within the accordion on the page using PHP, jQuery, and AJAX

To optimize the loading speed of my information-filled page connected to two databases using php, javascript, jquery, I'm looking for a way to make the upload process faster. Currently, some data is displayed immediately while other details are hidden ...

Observables in Knockout.js vanish after being bound

I'm encountering a peculiar issue with my Knockout script. Here is the viewModel: viewModel = { viewShown: function () { if (params.id !== undefined) timer = setInterval(loadVorgangsdetails, 100); else { $( ...

Redis Recursion: The callstack has reached its maximum size limit

Looking for some assistance with creating a game timer. I've decided to utilize Redis and Web Sockets in order to synchronize the timer across multiple devices. However, I'm running into an issue when trying to call my function recursively using ...

Navigate through each of the pictures within the folder and encode them into base64

I'm currently working on a project where I need to convert images in a folder to base64 and then store them in MongoDB. At first, I successfully converted a single image: var filename = '1500.jpg'; var binarydata = fs.readFileSync(filename ...

JavaScript function for automatic scrolling to the bottom of the page is not functioning as expected

I'm working on incorporating a terminal/console feature into my website. I came across the JavaScript functions for scrolling down a page, namely window.scrollTo(0,document.body.scrollHeight); and window.scrollTo(0,document.querySelector(".fakeSc ...

The setInterval function will run just one time when triggered by an onclick event

After watching a YouTube tutorial on creating desktop notifications, I had an idea to use it as a reminder tool. For example, having a specific reminder appear as a desktop notification every 30 minutes when triggered by clicking a button. However, the cod ...

Is there a way to locate a null string within this data arrangement?

I am looking to create functionality where, when a button is clicked, the application checks the state and takes different actions based on the result. Specifically, I want to ensure that there are no empty "value" fields, and if there are, redirect to ano ...

Loop through the JSON data to obtain distinct values for certain indices

My PHP script retrieves data with the following query: SELECT objective,signal_type,signal_name FROM signals WHERE channel="Email" This is how the data is returned: [ { "objective": "Awareness", "signal_type": "Efficiency", " ...

The simplest method to make HTML elements inaccessible to the Simple HTML Dom Parser in PHP

Imagine a scenario where a basic web application is running and utilizing Simple HTML Dom Parser. The code snippet below demonstrates this: <?php include('simple_html_dom.php'); $html = file_get_html('http://someurl.com'); ...

Ways to dynamically assign a name to a div using AngularJS

Currently, I am in the process of developing a download function for an Android app using Angularjs based on this tutorial: Utilizing the Progress event in PhoneGap file transfers Everything seems to be working efficiently as planned; I can successfully d ...

Learn how to stream videos using the YouTube Player API's loadPlaylist feature

Is there a way to make the next video play automatically using the loadPlaylist option? I've tried implementing this code but unfortunately, it doesn't work and the video won't play: <div id="player"></div> <script> var ...

Sending Data from jQueryUI Dialog to PHP using AJAX

I am struggling to retrieve the user inputs from text fields within a dialog window in order to utilize them for a SQL query. The issue I am encountering is that I am unable to effectively use the array in PHP. Despite no error messages being displayed, I ...

Ways to stop a JavaScript function from running during page loading

After clicking the submit button on my form, I want to send a confirmation post using the sendPostAjax() function before submitting the form to the payment provider. However, I'm facing an issue where the sendPostAjax() function is getting executed as ...