-1

I want a callback to be called when a user clicks on a marker. I've figured out that if I use an inline defined function, the variable I want to use has a value corresponding to the last used value. In a code below it's a last value of data array.

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Simple markers</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&signed_in=true"></script>
    <script>

var data = [
  {Name: 'Limanowskiego 1', Lat: 53.785418, Long: 20.4907734},
  {Name: 'Partyzantów 12', Lat: 53.782255, Long: 20.484778}];

function createCallback(p) {
  return function(e) {
    console.log(p);
  };
}

function initialize() {
  var mapOptions = {
      zoom: 14,
      center: new google.maps.LatLng(53.785418, 20.4907734)
    };
  var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

  var infowindow = new google.maps.InfoWindow({
      content: "test string"
  });

  for (var i=0; i < data.length; i++) {
    var point = data[i];
    var myLatlng = new google.maps.LatLng(point.Lat, point.Long);
    var marker = new google.maps.Marker({
          position: myLatlng,
          map: map,
          title: point.Name,
      });
    google.maps.event.addListener(marker, 'click', function(e) {
      console.log(point);
    });
  }
}

google.maps.event.addDomListener(window, 'load', initialize);

    </script>
  </head>
  <body>
    <div id="map-canvas"></div>
  </body>
</html>

If I replace the listener registration by:

    google.maps.event.addListener(marker, 'click', createCallback(point));

it works as expected.

Paweł Szczur
  • 5,484
  • 3
  • 29
  • 32
  • You have function(e) in your first code block, but console.log(point) in that function. How does the function know what point is? – shermanzach Jun 02 '15 at 23:56

1 Answers1

0

My suspicion is that you aren't telling the anonymous function here what point is.

google.maps.event.addListener(marker, 'click', function(e) {
      console.log(point); //point?? what point?
    });

You could probably solve this by simply adjusting your parameters accordingly...

google.maps.event.addListener(marker, 'click', function(e, point) { //Oh, This point!
      console.log(point);
    });

If you don't understand why this is, it's because point was declared in the surrounding function as a local variable, not a global variable (which is best!).

When you create the new, anonymous function, it creates its own scope, and it doesn't know anything about the other function's point. To tell the anonymous function which point to use, you can just pass it in as a parameter, hence my answer above.

shermanzach
  • 591
  • 1
  • 6
  • 14