There is a GoogleMap with Markers loaded by a JSON. The markers are displayed correct. But the Info Window shows only the last title (unternehmen / company). Is it a overwrite problem? How can i fix it?
<div id="map" style="height:500px;width:100%;"></div>
<script src="https://maps.googleapis.com/maps/api/js!!!######MYKEY########!!!!" type="text/javascript"></script>
<script type="text/javascript">
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(50,12),
zoom: 3,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var json = [
{
"unternehmen": "Dresden",
"address": "Dresden, Deutschland"
},
{
"unternehmen": "Frankfurt",
"address": "Frankfurt, Deutschland"
}
]
var infoWindow = new google.maps.InfoWindow();
var geocoder = new google.maps.Geocoder();
for (var i = 0, length = json.length; i < length; i++) {
var data = json[i],
address = data.address,
unternehmen = data.unternehmen;
geocoder.geocode( { 'address' : address }, function( results ) {
var marker = new google.maps.Marker( {
map: map,
position: results[0].geometry.location,
title: unternehmen,
animation: google.maps.Animation.DROP
});
(function(marker, data) {
google.maps.event.addListener(marker, "click", function( e ) {
infoWindow.setContent(unternehmen);
infoWindow.open(map, marker);
});
})(marker, data);
});
}
</script>
You have implemented closure correctly but at the wrong place
for (var i = 0, length = json.length; i < length; i++) {
var data = json[i],
address = data.address,
unternehmen = data.unternehmen;
(function(unternehmen) {
console.log(unternehmen);
geocoder.geocode( { 'address' : address }, function( results ) {
var marker = new google.maps.Marker( {
map: map,
position: results[0].geometry.location,
title: unternehmen,
animation: google.maps.Animation.DROP
});
//(function(marker, data) {
google.maps.event.addListener(marker, "click", function( e ) {
infoWindow.setContent(unternehmen);
infoWindow.open(map, marker);
});
//})(marker, data);
});
})(unternehmen);
}