oompahlumpa
oompahlumpa

Reputation: 503

Add infoWindows to multiple markers in array

I have a map that I have been trying to figure out adding infoWindow's to markers that live in an array and I am stuck.. With a single map and a single marker I can add an info window no problem. But for the life of me I CAN NOT get the infowindows to work within my array. If anyone could possibly help me get this to work I would be forever greatful. My intentions is to be able to pull html within the infowindows. Here is a fiddle with where I am at so far.

var map;
var markers = [];

function initMap() {
  map = new google.maps.Map(document.getElementById('map_canvas'), {
    zoom: 14,
    center: new google.maps.LatLng(-33.91721, 151.22630),
    mapTypeId: 'roadmap',
    disableDefaultUI: true
  });

  // var iconBase = <?php echo "'/images/markers/'"; ?>;
  var icons = {
    typea: {
      icon: "http://maps.google.com/mapfiles/ms/micons/blue.png"
    },
    typeb: {
      icon: "http://maps.google.com/mapfiles/ms/micons/green.png"
    },
    typec: {
      icon: "http://maps.google.com/mapfiles/ms/micons/orange.png"
    }
  };

  function addMarker(feature) {
    var marker = new google.maps.Marker({
      position: feature.position,
      icon: icons[feature.type].icon,
      map: map,
      type: feature.type
    });
    marker.addListener('click', function() {
      //set zoom level
      map.setZoom(20);
      //center map
      map.setCenter(marker.getPosition());
      alert("Testing");
    });
    markers.push(marker);
  }

  filterMarkers = function(getType) {
    console.log(getType);
    for (var i = 0; i < markers.length; i++) {
      if (markers[i].type == getType || getType == "") {
        markers[i].setVisible(true);
      } else {
        markers[i].setVisible(false);
      }
    }
  }

  var features = [{
    position: new google.maps.LatLng(-33.91721, 151.22630),
    type: 'typea'
  }, {
    position: new google.maps.LatLng(-33.91539, 151.22820),
    type: 'typeb'
  }, {
    position: new google.maps.LatLng(-33.91747, 151.22912),
    type: 'typec'
  }];

  for (var i = 0, feature; feature = features[i]; i++) {
    addMarker(feature);
  }
}
google.maps.event.addDomListener(window, "load", initMap);

Complete working fiddle: http://jsfiddle.net/h80vtmye/

Upvotes: 0

Views: 324

Answers (1)

Shweta Patel
Shweta Patel

Reputation: 728

GoogleMap not allow to use infowindow like that. Create a single copy of the infowindow instead of maintaining an array and set contents with infowindow.setContent() during the mouseover event of marker.

Upvotes: 1

Related Questions