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

Is there a way to align the image next to the form and ensure they are both the same size?

I've been struggling to resize the image to match the form size, but I can't seem to get it right. Can anyone provide me with some guidance on this issue? I have obtained this contact form from a website that I plan to modify slightly, but I need ...

Building a Meteor query in MongoDB using $in operator while handling duplicate values

I have a collection of songs that I want to present to a user. Each song is associated with a specific id. The issue I am encountering is that some songs should be displayed multiple times. Currently, I am using the $in operator in my MongoDB query, but it ...

Execute a function on elements that are added dynamically

I'm in the early stages of learning javascript and jquery, so this issue might be very basic. Please bear with me. Currently, I am dynamically adding new link (a) elements to a division with the id "whatever" using the following code: $("#whatever") ...

Display the HTML/CSS layout following the JavaScript window.open action

Encountering issues with printing output in an opened window using JavaScript. I'm creating a new document through window.open and including CDN links to Bootstrap files. While everything appears fine in the opened window, when attempting to print (XP ...

Using Javascript to fetch JSON data from a PHP file hosted on an IIS server, incorporating JSONP with

I have set up an HTML5, JavaScript, and CSS3 https application on Windows IIS (Internet Information Services). The structure of the root directory is as follows: index.html, src/index.js, src/send_payment.php Currently, I am attempting to retrieve a basi ...

JavaScript syntax issue: Required formal parameter not found

Can someone help me understand why this error message is showing up in the console for the code provided? I've followed the link indicated as the issue and it points to this specific line: " $('tr').each(function() { ". (I may have included ...

Ways to center align text in a div vertically

I'm working with 2 divs that are floating side by side. The left div contains a part number, which is only one line. The right div holds the product description, which can span multiple lines. I am looking for a way to vertically align the text in t ...

Having trouble retrieving values for jVectorMap? The getElementById method doesn't seem to be functioning as

I have been trying to set markers on a jVectormap. I retrieve the content from my database and store it in a hidden input field. The format of the data is as follows: {latLng:[52.5200066,13.404954],name:'Berlin'},{latLng:[53.0792962,8.8016937],n ...

Implementing Ajax to Load Template-Part in Wordpress

Hey there! I'm currently working on enhancing my online store by adding a new feature. What I'd like to achieve is that when a customer clicks on a product, instead of being taken to the product page, the product details load using AJAX right on ...

Bookmarklet in JavaScript that automatically extracts and displays Meta keywords in a new tab within the browser

I successfully implemented a script that extracts site meta keywords and writes them into the DOM. javascript:(function metaKeywords() { metaCollection = document.getElementsByTagName('meta'); for (i=0;i<metaCollection.length;i++) { nameAttri ...

"Utilizing jQuery and Bootstrap 4 in TypeScript, attempting to close modal window using jQuery is not functioning

Trying to make use of jquery to close a bootstrap modal within an angular project using typescript code. The following is the code: function call in html: (click)="populaterfpfromsaved(i, createSaved, createProp)" createSaved and createProp are local ...

Utilize the input type=date value in the date function to obtain a specific format

How can I pass the value of input type=date to a JavaScript date function? In my HTML code, I have used: <input type=date ng-model="dueDate"> <input type="time" ng-model="dueTime"> <button class="button button-block" ng-click="upload_dueda ...

Tips for clearing out outdated information from a bar chart

My bar chart is receiving JSON data based on the selected dropdown value. The chart updates when the dropdown changes, but there seems to be a problem with the hover functionality causing the last visited value to shake the chart. Any suggestions on how ...

The Philosophy Behind Structuring Node.js Modules

There appears to be a common understanding regarding the directory structure in node.js, but I have not come across any official documentation on this topic. Based on my exploration of open source projects, it seems that most projects typically include a ...

There was an issue with Sails.js where it was unable to retrieve a recently created user using a date

One issue I encountered with Sails.js was using sails-disk as the database. When querying for a user with specific date parameters, such as: // Assuming the current date is end_date var end_date="2014-06-06T15:59:59.000Z" var start_date="2014-06-02T16:0 ...

How to combine two tables in Sequelize using a one-to-many relationship

I'm currently working with two models: User and Foto. In my application, each User can have multiple fotos, and each foto is associated with only one user. My challenge lies in using the include function. I am able to use it when querying for the us ...

The present URL of Next.js version 13

When working with Next.js App Router in SSR, how can I retrieve the complete URL of the current page? I am unable to use window.location.href due to the absence of a defined window object, and using useRouter() does not provide access to the full URL. ...

Activate the Bootstrap Jquery/Ajax inline editing feature by simply clicking on the Edit button

Seeking recommendations for a way to implement inline editing. When the edit button is clicked, I want the label's content to be replaced with an input text field that can be updated in my MySQL database. This is what my code looks like: <label s ...

The 'log' property cannot be found on the type '{ new (): Console; prototype: Console; }' - error code TS2339

class welcome { constructor(public msg: string){} } var greeting = new welcome('hello Vishal'); Console.log(greeting.msg); I encountered an error at the Console.log statement. The details of the error can be seen in the image attached below. ...

"Implementing a feature in Angular to display only a single ul element at a time while iterating through a

In the image above, there is an Add Person button. When this button is clicked, a new row labeled Person 1 is created, and this process continues for each subsequent click. At the right end of every row, there is a share icon that, when clicked, should ope ...