I have a Google Map on the webpage with markers on it that has click listeners attached to them.
Problem: On localhost, when I click on a map marker, everything works as intended. However, after uploading to the server and trying the live version, clicking on the marker causes an error Uncaught TypeError: Cannot read property 'listing_id' of undefined.
Both console.log shows that json and i are defined…
Console.log output
[ Object , Object , Object , Object , Object , Object , Object ,
Object , Object , Object , Object , Object , Object , Object ,
Object , Object , Object , Object ]i: 48
Uncaught TypeError: Cannot read property ‘listing_id’ of undefined
Why is this happening?
JS Code
$.getJSON(......., function(json) {
for(var i = 0; i < json.length; i++) {
(function(i) {
google.maps.event.addListener(markers[json[i].listing_id], 'click', function() {
console.log('json: ' + json);
console.log('i: ' + i);
console.log('json[i].listing_id :' + json[i].listing_id);
// Mark currently opened marker
markers[json[i].listing_id].setIcon(base_url + 'images/template/markers/listing_black.png');
//...
});
})(i);
}
});
It looks like you don’t pass the data to the callback function.
Try changing your first line to this instead: