谷歌地图javascript api标记弹出窗口仅显示在中心

时间:2016-12-24 17:25:05

标签: javascript google-maps google-maps-markers

我正在使用Google地图JavaScript API创建带弹出窗口的多个标记(InfoWindow

function initMap(){

    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 2,
        center: {lat: 20, lng: 0}
    });

    //console.log(dbResults);

    for(var i=0; i<dbResults.length; i++){

        var _coords = dbResults[i].location.split(',');
        var coords = {lat: parseFloat(_coords[0]), lng: parseFloat(_coords[1])}
        //console.log(coords);

        var marker = new google.maps.Marker({
            position: coords,
            map: map
        });

        var infowindow = new google.maps.InfoWindow({
            content: '<div>'+dbResults[i].title+'</div>'
        });

        marker.addListener('click', function() {
            infowindow.open(map, marker);
        });
    }

}

标记在地图周围正确显示,但弹出窗口仅显示在地图的中心(而不是显示在所属标记位置附近)

为了使它们有效,我需要更改什么?

1 个答案:

答案 0 :(得分:1)

要解决问题(将InfoWindow与正确的标记相关联),一个选项是使用函数闭包,如对此类似问题的回答所示:Google Maps JS API v3 - Simple Multiple Marker Example

在您的代码中:

marker.addListener('click', (function(marker, infowindow) {
    return function(evt) {
    infowindow.open(map, marker);
}}(marker,infowindow)));

proof of concept fiddle

代码段

function initMap() {

  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 2,
    center: {
      lat: 20,
      lng: 0
    }
  });

  //console.log(dbResults);
  var dbResults = [{
    location: "42,-72",
    title: "Here"
  }, {
    location: "45,-112",
    title: "There"
  }, {
    location: "20,0",
    title: "Somewhere"
  }];
  for (var i = 0; i < dbResults.length; i++) {

    var _coords = dbResults[i].location.split(',');
    var coords = {
        lat: parseFloat(_coords[0]),
        lng: parseFloat(_coords[1])
      }
      //console.log(coords);

    var marker = new google.maps.Marker({
      position: coords,
      map: map
    });

    var infowindow = new google.maps.InfoWindow({
      content: '<div>' + dbResults[i].title + '</div>'
    });

    marker.addListener('click', (function(marker, infowindow) {
      return function(evt) {
        infowindow.open(map, marker);
      }
    }(marker, infowindow)));
  }

}
google.maps.event.addDomListener(window, "load", initMap);
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>