-2

I took over a bit of code that uses Google Map's API to create markers on a map with info windows. Here is the snippet to create the markers and listeners (note, this is only a fragment of the code):

if(markers.length > 0) {
// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow({
    maxWidth:420
}), marker, i;

// Loop through our array of markers & place each one on the map
var pinIcon = new google.maps.MarkerImage(
    "<?php echo SITE_URL;?>images/site-structure/map-marker1.png",
    null, /* size is determined at runtime */
    null, /* origin is 0,0 */
    null, /* anchor is bottom center of the scaled image */
    new google.maps.Size(20, 30));

for( i = 0; i < markers.length; i++ ) {
    var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
    bounds.extend(position);

    marker = new google.maps.Marker({
        position: position,
        map: map,
        icon:pinIcon,
        title: markers[i][0]
    });

    // Allow each marker to have an info window
    google.maps.event.addListener(marker, 'mouseover', (function(marker, i) {
        return function() {
            infoWindow.setContent(infoWindowContent[i][0]);
            infoWindow.open(map, marker);
        }
    })(marker, i));

    google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
            infoWindow.setContent(infoWindowContent[i][0]);
            infoWindow.close(map, marker);
        }
    })(marker, i));

    // Automatically center the map fitting all markers on the screen
    map.fitBounds(bounds);
}

}

The custom markers get added just fine, but the event listeners (mouseover and click) are not working. I can provide more info if needed.

keithp
  • 352
  • 1
  • 4
  • 13
  • 2
    Please provide a [mcve] that demonstrates your issue. – geocodezip Mar 12 '18 at 22:57
  • 2
    Those codes aren't enough for us to replicate your issue. However what you are trying to achieve is already done in the accepted answer here: https://stackoverflow.com/questions/3059044/google-maps-js-api-v3-simple-multiple-marker-example – tomjosef Mar 13 '18 at 07:21

1 Answers1

0

Have you tried simply doing something like:

// Allow each marker to have an info window
google.maps.event.addListener(marker, 'mouseover', function(marker, i) {
  infoWindow.setContent(infoWindowContent[i][0]);
  infoWindow.open(map, marker);
});

Unless there's some variation on adding event listeners with Google maps that I'm not aware of, you should just be able to pass a function that directly does what you want it to do, rather than passing a function that returns another function.

kshetline
  • 12,547
  • 4
  • 37
  • 73