Hello People
Would somebody please advise me as to what I'm doing wrong with this piece of code?
I am currently using a simple JSON file to provide data for info windows using the Google maps V3 API. I am aware of the concept of closures but cannot seem to understand why the info windows are still displaying the last result on click.
Here is my JSON file:
{ "markers": [
{
"lat": 51.5001524,
"lng": -0.1262362,
"firstName": "nameOne"
},
{
"lat": 55.8656274,
"lng": -4.2572227,
"firstName": "nameTwo"
},
{
"lat": 43.834526782236814,
"lng": -37.265625,
"firstName": "nameThree"
}
] }
Here is my JS:
(function(){
function initialize() {
var latlng = new google.maps.LatLng(51.5001524, -0.1262362)
var myOptions = {
zoom: 3,
center: latlng,
mapTypeId: google.maps.MapTypeId.TERRAIN
}
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
function parseJson(){
$.ajax({
url: 'assets/js/markers.json',
dataType: 'json',
success: function(data) {
processMarkers(data)
},
error: function (data) {
console.log('fail')
}
})
}
function processMarkers(data){
var totalMarkers = data.markers.length;
for(i=0;i<totalMarkers;i++){
var latitude = data.markers[i].lat;
var longditude = data.markers[i].lng;
var putMarker = new google.maps.LatLng(latitude, longditude);
var thisMarker = new google.maps.Marker({
position: putMarker,
map: map
});
var firstName = data.markers[i].firstName;
var infoWindow = new google.maps.InfoWindow({
position: putMarker,
content: firstName
});
new google.maps.event.addListener(
thisMarker,
'click',
buildHandler(map, thisMarker));
}
function buildHandler(map, marker){
return function(){
infoWindow.open(map, marker);
};
}
}
parseJson();
}
$(document).ready(function(){
initialize();
});
})();
Any help would be greatly appreciated.
Cheers