Google Maps API - opening a single infoWindow

孤街醉人 提交于 2019-11-29 17:30:53

You're creating the infowindow within your .each() loop. Instead, create one infowindow outwith that loop. Then in your event listener, just update the content of that global infowindow each time.

MYMAP.init = function(selector, latLng, zoom) {
  var myOptions = {
    zoom:zoom,
    center: latLng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }

  this.map = new google.maps.Map($(selector)[0], myOptions);
  this.bounds = new google.maps.LatLngBounds();      
}

MYMAP.placeMarkers = function(filename) {
  $.get(filename, function(json){
    var infoWindow = new google.maps.InfoWindow({
            content: ""
      }); 

    $.each(json, function(i,loc){
      var marker = new google.maps.Marker({
        position: new google.maps.LatLng(loc.location.merchant_location.latitude, loc.location.merchant_location.longitude),
        map: MYMAP.map,
        title: loc.deal.subject
      });

      bindInfoWindow(marker, MYMAP.map, infoWindow, "<h3>" + loc.deal.subject + "</h3><p>" + loc.location.merchant_location.address + "</p>");
    });         
  }, "json");
}

function bindInfoWindow(marker, map, infowindow, html) {
    google.maps.event.addListener(marker, 'click', function() {
        infowindow.setContent(html);
        infowindow.open(map, marker);
    });
} 

$("#map").css({
  height: 500,
  width: 600
});

var myLatLng = new google.maps.LatLng(#{@deals.first.merchant_locations.first.latitude},#{@deals.first.merchant_locations.first.longitude});
MYMAP.init('#map', myLatLng, 11);
MYMAP.placeMarkers('/more_deals/get_locations/#{@market.id}');

Create only one InfoWindow object. Your modified code.

MYMAP.init = function(selector, latLng, zoom) {
  var myOptions = {
    zoom:zoom,
    center: latLng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }

  this.map = new google.maps.Map($(selector)[0], myOptions);
  this.bounds = new google.maps.LatLngBounds();       
}

MYMAP.placeMarkers = function(filename) {

 var infoWindow = new google.maps.InfoWindow();

  $.get(filename, function(json){
    $.each(json, function(i,loc){
      var marker = new google.maps.Marker({
        position: new google.maps.LatLng(loc.location.merchant_location.latitude, loc.location.merchant_location.longitude),
        map: MYMAP.map,
        title: loc.deal.subject
      });

      var arrMarkers = [];
      arrMarkers[i] = marker;


      google.maps.event.addListener(marker, 'click', function(){
        infoWindow.setContent (
        "<h3>" + loc.deal.subject + "</h3><p>" + loc.location.merchant_location.address + "</p>"
      );
        infoWindow.open(MYMAP.map,marker);
      });
    });         
  }, "json");
}

$("#map").css({
  height: 500,
  width: 600
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!