Reputation: 302
I've got a google map implementation that drops the pins on the map using a couple function calls and a marker[ ] array.
It works great, but I can't figure out how to possibly add an onClick event or other type of event listener to the function since it doesn't have a marker variable defined explicitly.
Where would I be able to add something like this?:
google.maps.event.addListener(markers, 'click', function() {
window.location.href = this.url;};
Here is my basic map code and functions:
var pinlocations = [
['1', {lat: 30.266758, lng: -97.739080}, 12, '/establishments/1111'],
['2', {lat: 30.267178, lng: -97.739050}, 11, '/establishments/1222'],
['3', {lat: 30.267458, lng: -97.741231}, 10, '/establishments/1333'],
['4', {lat: 30.388880, lng: -97.892276}, 9, '/establishments/1444']
];
var markers = [];
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {lat: 30.267178, lng: -97.739050}
});
}
function drop() {
clearMarkers();
for (var i = 0; i < pinlocations.length; i++) {
var place = pinlocations[i];
addMarkerWithTimeout(place[1], place[0], place[2], place[3], i * 200);
}
}
function addMarkerWithTimeout(position, title, zindex, url, timeout) {
window.setTimeout(function() {
markers.push(new google.maps.Marker({
position: position,
map: map,
title: title,
zIndex: zindex,
url: url,
animation: google.maps.Animation.DROP
}));
}, timeout);
}
Upvotes: 1
Views: 4736
Reputation: 65808
You don't add an event to an array, you have to add it to each element within the array. You can do this with the .forEach()
array method:
// Iterate the markers array
markers.forEach(function(marker){
// Set up a click event listener for each marker in the array
marker.addListener('click', function() {
window.location.href = marker.url;
});
});
Or, you could take another approach and add the event at the moment each individual marker gets created.
function addMarkerWithTimeout(position, title, zindex, url, timeout) {
window.setTimeout(function() {
markers.push(new google.maps.Marker({
position: position,
map: map,
title: title,
zIndex: zindex,
url: url,
animation: google.maps.Animation.DROP
}).addListener('click', function() {
window.location.href = this.url;
});
}, timeout);
}
Upvotes: 2