How can I display Google Maps markers on my map?

I have successfully created my map, but I am facing an issue with getting markers or clusters to appear on it. Below is the JavaScript code I am using:

function initMap() {
  var map = new google.maps.Map(document.getElementById("map"), {
      zoom: 12,
      center: { lat: 51.40219, lng: -0.16890 }
    });

    var labels = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    
  }

//Coordinates for the various Memorials and Cemeteries listed for the corresponding Hero that will be marked on the map.
// I used https://codepen.io/ahmadawais/pen/NQdWQx?editors=1010 to see how to do the below with the locations as this way it will show with the names of the memorials or cemeteries
var locations = [
  ['Private Richard Spearink - St Souplet British Cemetery', { lat: 50.05484, lng: 3.52440 }, 1],
  ['Private Frederick Spearink - Mitcham War Memorial', { lat: 51.40219, lng: -0.16890 }, 2],
  ['Private Frederick Spearink - Helles Memorial', { lat: 40.04597, lng: 26.17921}, 2]
];

var markers = locations.map(function(location, i) {
  return new google.maps.Marker({
      position: location,
      label: labels[i % labels.length]
  });
});

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

Can someone please help me figure out what changes I need to make in order to fix this problem?

Answer №1

It seems that you are not accurately inputting the latitude and longitude values for your markers.

Your array called locations consists of fixed-length arrays known as "tuples", where the second element is an object containing lat and lng values that align with the LatLngLiteral. This structure is correct for the position in MarkerOptions, however, in your loop using locations.map, you are passing the entire tuple instead of just the location.

To clarify this misconception, I suggest renaming location to locationTuple; even though the names themselves are inconsequential to the code, this change will make it more apparent that you should reference your position value using locationTuple[1] (or location[1]). Subsequently, you can also utilize locationTuple[0] instead of opting for a random letter as a label.

var locations = [
  ['Private Richard Spearink - St Souplet British Cemetery', { lat: 50.05484, lng: 3.52440 }, 1],
  ['Private Frederick Spearink - Mitcham War Memorial', { lat: 51.40219, lng: -0.16890 }, 2],
  ['Private Frederick Spearink - Helles Memorial', { lat: 40.04597, lng: 26.17921}, 2]
];

var markers = locations.map(function(locationTuple, i) {   // rename
  return new google.maps.Marker({
      position: locationTuple[1],                          // rename + add index 1
      label: locationTuple[0]                              // rename + add index 0
  });
});

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

A guide on printing several PDF files at once with print.js in Angular 9

After successfully using the print.js library to print a single PDF, I encountered an issue when attempting to print multiple PDFs. An error message stating "ERROR Multiple Choices" was displayed. I also experimented with plain JS, but it resulted in multi ...

Is there a way to verify the href attribute and potentially append the complete URL address if necessary?

Is there a way to verify the href attribute and replace it with a full URL if it doesn't contain the full path? I tried using JavaScript for this, but it doesn't seem to work on IE 8. This is my JavaScript code: fullUrl = $(this).filter('[ ...

Has Chrome's console disappeared?

After reinstalling Chrome and opening the dev tools with F12, I encountered an error with the following code: console.debug('test'); The error message displayed was Uncaught ReferenceError: console is not defined(…) This issue persisted acro ...

Unable to append Jquery attribute to a div component

My code snippet is creating a div with specific classes and elements: '<div class="ctrl-info-panel col-md-12 col-centered">'+ '<h2>You do not have any projects created at the moment.</h2>'+ '<div id="t ...

Creating HTML inputs dynamically using jQuery in an ASP.NET application

I have written this JavaScript code to dynamically generate and add HTML elements within my asp.net webform: var i = 0; function addFields() { i++; var quantity = '<td class="auto-style2"><input type="text" size="3" name= ...

Error encountered while submitting ajax request to server

When I click a button, a function is triggered with the argument insertSongPlay(newSong.songID);. After logging the value of newSong.songID, which is 90 as desired, an ajax call is made: function insertSongPlay(songID) { $.ajax ({ type: " ...

Ways to standardize the input email address?

While using express-validator, I came across an issue where I used normalize email for validation of email during sign up and stored the normalized email on the server. Validation code: router.post( "/signup", [ check("name").n ...

Experience the dynamic bouncing marker feature in Next.js React-Leaflet with the powerful tool Leaflet.SmoothMarkerB

I'm a beginner in front-end development and I'm attempting to create a bouncing marker in React-leaflet using the leaflet.smooth_marker_bouncing plugin version 1.3.0 available at this link. Unfortunately, I couldn't find enough documentation ...

Utilizing an Express API within a Kubernetes environment to enhance functionality for React and React Native

Currently, I am in the process of learning Kubernetes and have set up an Apollo-express GraphQL API along with a React frontend and a React Native app. I am trying to figure out how to connect my GraphQL API with both the frontend and mobile apps - what se ...

Showing a collection of cards within a dynamic container set up in a 3x3 grid layout to start

In an attempt to showcase cards within a responsive container utilizing bootstrap and django, my goal is to create a 3x3 grid layout on extra-large screens with scrollable overflow that adjusts based on device width. Initially, I experimented with wrapping ...

The AJAX request is failing to reach the server

I'm currently using AJAX to populate a dropdown, but for some reason the call isn't reaching the server. Upon checking Firebug, I see the following error: POST 0 status 404 not found This is the code I'm working with: function selec ...

Display a div in jQuery when a specific radio button is selected

I have set up three radio buttons to display three different divs, but the functionality is not working correctly. Below is the script I am using: <script> $(document).ready(function() { $("input[name$='Want_To']").click(function() { ...

Promise<IDropdownOption[]> converted to <IDropdownOption[]>

I wrote a function to retrieve field values from my SPFx list: async getFieldOptions(){ const optionDrop: IDropdownOption[]= []; const variable: IEleccion = await sp.web.lists.getByTitle("Groups").fields.getByTitle("Sector").get ...

Trying my hand at using JQuery to dynamically update the image source of a draggable element upon dropping

Essentially, I have an object being dragged with the class .dragme, a dropzone with the class .dropzone1 for it to be dropped at, and an image that I want the .dragme object to become once it has been dropped. My current code looks like this: $(".dropzon ...

Sorting arrays in JavaScript can become tricky when dealing with arrays that contain values from two different arrays

When working with two arrays in JavaScript that are received from PHP, I combine them into a single array. Each element in these arrays contains a created_at value (from Laravel), and I want to sort these elements by their created_at values. The issue ari ...

Performing a task solely in the event that the preceding one does not succeed

I've been putting together a facebook login feature for my app and have encountered a glitch that needs fixing. What should the next steps be? 1 - Authenticate on facebook (DONE) 2 - Retrieve user data from Facebook (DONE) 3 - Check if user exists ...

Using angularjs ng-repeat in combination with owl-carousel

<div class="owl-carousel"> <div ng-repeat="items in itemlist"> <a href="series.html"><img ng-src="{{items.imageUrl}}" /></a> </div> <div> <a href="series.html><img src="http://p ...

Tips for successfully sending parameters in a Google Geocoding request

Dealing with an array of objects containing addresses, each with four fields. The first field is the current location (store), while the others provide address information. The challenge is ensuring that I end up with a result in the format key:value (sto ...

Triggering the browser to prompt the "Save As" dialog box when initiating a file download

After researching extensively on this particular topic, I have come to realize that none of the solutions available meet my requirements. What I am trying to achieve is to instruct my WinCE 6.0 board to generate a backup file via an AJAX request and then s ...

Guide to adding an active class to each block using Javascript

My website utilizes a Bootstrap layout consisting of a container, rows, and multiple "block-divs," each containing three separate divs. The number of block-divs is generated dynamically by a script based on user input. The issue I am facing is that when a ...