Home > Mobile >  Google Maps Markers - how to get these to show please
Google Maps Markers - how to get these to show please

Time:09-17

I have my fully functioning map although am not sure why I can't get any markers or clusters to come in on this? The JS code I have is below:

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 Cemetries 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' });

Would anyone be able to tell me what I either need to add or remove please as I'm not sure why this isn't working?

CodePudding user response:

You're not correctly passing in your latitude and longitude for your markers.

Your locations array is an array of fixed-length arrays ("tuples"), the second of which is an object of lat and lng that matches LatLngLiteral. That's the right value for position in MarkerOptions, but in your locations.map you're passing location, which here is the entire tuple.

Because each entry is not a location, I've renamed location to locationTuple; the names don't matter to the code, but it does make it clearer that you'll need to use locationTuple[1] (or location[1]) to refer to your value for position. At that point you can also use the labels as locationTuple[0] rather than picking an arbitrary letter.

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
  });
});
  • Related