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.