Google Maps Marker, same onclick function with different input values?

my team and I are using Google Maps API to display a map on our website. We have entered multiple markers on the map and want to use the same function to call on a click event. The only difference should be the input value, so that the function can differentiate between the markers.

That's why we set the input value (name) we want to give to the function in a global array and then assign the function with the specific index of the array to the EventListener.

It's not about creating the markers for the locations, but for assigning a click function to each marker with a different input value. The creation of the markers is no problem!

for (var i=0;i<all_Locations.length;i++){
    latlngPosition = new google.maps.LatLng(all_Locations[i].lat, all_Locations[i].lng);
    marker = new google.maps.Marker({
            position: latlngPosition,
            map: map,
            draggable: false,
            animation: google.maps.Animation.DROP,
            title: all_Locations[i].name
    });
    //push marker itself and marker name into two global available arrays
    markersNames.push(all_Locations[i].name);
    markers.push(marker);
    //add the click function to the markers
    google.maps.event.addListener(marker,'click',function(){filterAfterLocation(markersNames[i]);});
}

The problem is, if we do it like this every function call get the value undefined. I guess it has something to do with the initialization of the array or the time points of our call and assigning.

We tried to assign the name directly in each step of the loop, but that gave every function the same input of the last name used in the loop.

We are hoping for some help, thank you!

PS: We don't want to write 8 functions and assign them to each marker, of course that's possible, but would be our plan Z.