-1

for(i = 0; i < locations.length; i++) {
  currentLocation = locations[i];

  var mapMarker = new google.maps.Marker ({
    position: locations[i][0],
    map: map,
    label: labels[i],
    title: locations[i][1],
    zoom: 18
  })

  mapMarkers.push(mapMarker);
  mapMarkers[i].addListener('click', markerClick(currentLocation)); 
}


function markerClick(location) {
  console.log("you clicked " + location)
}

The function markerClick is being called each time it is added to an element. How can i make it so it is only called when the element is clicked? i read in another answer herethat leaving out the () would fix this, but I need to pass a paramater and am not sure how to do this. thanks for any help

KK555
  • 3
  • 1

2 Answers2

1

One option would be for your markerClick function to return a function.

function markerClick(location) {
  return function(evt) {
    console.log("you clicked " + JSON.stringify(location));
  }
}

proof of concept fiddle

code snippet:

var locations = [
  [{lat: 42,  lng: -72}, "Here"],
  [{lat: 42.1,lng: -72.1}, "There"]
];
var mapMarkers = [];

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(42, -72),
      zoom: 10,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  for (i = 0; i < locations.length; i++) {
    currentLocation = locations[i];

    var mapMarker = new google.maps.Marker({
      position: locations[i][0],
      map: map,
      // label: labels[i],
      title: locations[i][1],
      zoom: 18
    })

    mapMarkers.push(mapMarker);
    mapMarkers[i].addListener('click', markerClick(currentLocation));
  }
}

function markerClick(location) {
  return function(evt) {
    console.log("you clicked " + JSON.stringify(location));
  }
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>
geocodezip
  • 158,664
  • 13
  • 220
  • 245
0

When you add the listener, you're calling the markerClick() function rather passing it as a variable. Here's how to fix it:

//using a separate function like this avoids some nasty 
//problems with callbacks and closures in for loops
function addMapMarkerClickListener( mapMarker, location ) {
 
   //we use an anonymous function as the listener
   mapMarker.addListener('click', function() {
      markerClick( location );
   });
}

for(i = 0; i < locations.length; i++) {
  currentLocation = locations[i];

  var mapMarker = new google.maps.Marker ({
    position: locations[i][0],
    map: map,
    label: labels[i],
    title: locations[i][1],
    zoom: 18
  })

  mapMarkers.push(mapMarker);

  addMapMarkerClickListener( mapMarkers[i], currentLocation );
}


function markerClick(location) {
  console.log("you clicked " + location)
}
Duncan Thacker
  • 5,073
  • 1
  • 10
  • 20