0

I'm trying to put out markers and info windows from an api with a for loop but only get the last in the list. I have in the for loop because I need to loop through the API and base my information on that. But in my sense I should put out the markers in the loop as well or?

    //get all the restaurants which are open
$.getJSON(uri, function(data) {
    for(i = 0; i < 5; i++) {
        var place = data.response.groups[0].items[i].venue.name;
        var placeLat = data.response.groups[0].items[i].venue.location.lat;
        var placeLng = data.response.groups[0].items[i].venue.location.lng;
        var placeAddress = data.response.groups[0].items[i].venue.location.formattedAddress;
        var openPlace = data.response.groups[0].items[i].venue.hours;
        var placeGenre = data.response.groups[0].items[i].venue.categories[0].shortName;
        console.log(place, placeLat, placeLng, placeAddress, openPlace)
        var placePosition = {
            lat: placeLat,
            lng: placeLng
        }

        var marker = new google.maps.Marker({
            position: placePosition,
            map: map
        });

        var infowindow = new google.maps.InfoWindow();

        google.maps.event.addListener(marker, 'click', function() {
            infowindow.setContent('<div><strong>' + place + ' | ' + placeGenre + '</strong><br>' + placeAddress + '<br>' + openPlace + '</div>');
            infowindow.open(map, this);
        });
    }
});
map.setCenter(pos);
    }, function() {
        handleLocationError(true, infoWindow, map.getCenter());
      });
    } 
    else {
      // Browser doesn't support Geolocation
      handleLocationError(false, infoWindow, map.getCenter());
    }
  }

Thanks for the anticipation

Chilibiff
  • 119
  • 1
  • 13

1 Answers1

0

I tried and done the code.

1st Method: Actually the IIFE is useful for this senario.

(function(place, placeGenre, placeAddress, openPlace, map, marker){
    google.maps.event.addListener(marker, 'click', function () {
        infowindow.setContent('<div><strong>' + place + ' | ' + placeGenre + '</strong><br>' + placeAddress + '<br>' + openPlace + '</div>');
        infowindow.open(map, marker);
    })
})(place, placeGenre, placeAddress, openPlace, map, marker)

2nd Method: Call a function inside your loop and then pass the values.

setInfowindow(place, placeGenre, placeAddress, openPlace, map, marker, infowindow);

Define setInfowindow function outside:

function setInfowindow(place, placeGenre, placeAddress, openPlace, map, marker, infowindow) {
    google.maps.event.addListener(marker, 'click', function () {
        infowindow.setContent('<div><strong>' + place + ' | ' + placeGenre + '</strong><br>' + placeAddress + '<br>' + openPlace + '</div>');
        infowindow.open(map, marker);
    })
}
Ankit Pandey
  • 608
  • 4
  • 17