Meteor - Google Maps InfoWindow Event Not Firing

2019-09-07 22:13发布

问题:

Using Meteorjs and dburles google map package for Meteor.

The Goal: Is to have the markers map out on the canvas, and then onclick to reveal the infoWindows. I am having an issue firing the google map event in order for the window to reveal.

My Code:

 Template.myMap.helpers({
   mapOptions: function() {
    var locations = [
       ['Kroger', 34.069201, -84.231052, 5],
       ['Fresh Produce', 34.069802, -84.234164, 4],
       ['Starbucks', 34.069003, -84.236323, 3],
       ['Mall of Georgia', 34.069204, -84.232016, 2],
       ['Avalanche', 34.069705, -84.238207, 1]
      ]

// Make sure the maps API has loaded
if (GoogleMaps.loaded()) {
  // We can use the `ready` callback to interact with the map API once the map is ready.
  GoogleMaps.ready('myMap', function(map) {
    var infowindow = new google.maps.InfoWindow(),
        marker, i;

    for (i = 0; i < locations.length; i++) {
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map.instance
      });

      google.maps.event.addListener(marker, 'click', function() {
        return function() {
          infowindow.setContent(locations[i][0]);
          infowindow.open(map, marker);
        }
      });
    }
  });
  return {
    center: new google.maps.LatLng(34.069705, -84.238),
    zoom: 16
  };
}
}

});

回答1:

You're returning a function from the event handler rather than just handling the event, for reasons that aren't clear. Try this:

google.maps.event.addListener(marker, 'click', function() {
  infowindow.setContent(locations[i][0]);
  infowindow.open(map, marker);
});

UPDATE

The other problem is that you're trying to add it to the GoogleMaps map object, not the instance itself. It should be:

infowindow.open(map.instance, marker);

Also, I haven't run your code, but I think you're going to run into problems with the way you've structured this, as the value of i will not be as intended when the handler is actually fired (because the loop will have subsequently continued). Consider using forEach instead (below via underscore) so that each handler is declared in its own closure.

  _.forEach(locations, function(location) {
      var marker = new google.maps.Marker({
            position: new google.maps.LatLng(location[1], location[2]),
            map: map.instance
          }); 

      google.maps.event.addListener(marker, 'click', function() {
          infowindow.setContent(location[0]);
          console.log(map, marker, infowindow);
          infowindow.open(map.instance, marker);
      });        
  });