Google地图infoWindow仅加载标记上的最后一条记录

kna*_*ejj 10 javascript coldfusion google-maps

我正在尝试使用动态标记和动态infoWindows加载谷歌地图.基本上我有标记工作.infoWindows是可点击和可关闭的,但它们没有正确的内容.似乎每个infoWindow的内容是查询循环中找到的最后一条记录.你会看到这里发生什么这是代码:

<script type="text/javascript"> 


//Load the Google Map with Options//
  function initialize() {
    var myLatlng = new google.maps.LatLng(42.48019996901214, -90.670166015625);
    var myOptions = {
      zoom: 6,
      center: myLatlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    //Begin query loop to set the markers and infoWindow content//

    <cfoutput query="GetCoord">
    var LatLng = new google.maps.LatLng(#Client_Lat#, #Client_Lng#);

    var marker = new google.maps.Marker({
        position: LatLng,
        map: map,
        title: "#Client_Company#"
    });   

    var contentString = '<p><b>#Client_Company#</b><br>'+
                        '#Client_Address#<br>'+
                        '#Client_City#,&nbsp; #Client_State# &nbsp; #Client_Zip#<br>'+
                        '<a href="member_detail.cfm?ID=#Client_ID#">View Details</a>';

    var infowindow = new google.maps.InfoWindow({
        content: contentString
    });

    google.maps.event.addListener(marker, 'click', function() {
        infowindow.open(map,this);

     });
    </cfoutput>
    //End query loop
    }

</script>
Run Code Online (Sandbox Code Playgroud)

有关为什么会发生这种情况的任何想法?

小智 42

content作为标记对象的属性添加并this.content在事件处理程序中使用:

var marker = new google.maps.Marker(options);
marker.content = '<div>Content goes here....</div>';

var infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', function () {
                                infoWindow.setContent(this.content);
                                infoWindow.open(this.getMap(), this);
                            });
Run Code Online (Sandbox Code Playgroud)

  • 接受的答案对我不起作用.这个解决方案.谢谢@HM (2认同)

Gal*_*len 13

在您的代码中,您静态设置加载时的infowindow内容

var infowindow = new google.maps.InfoWindow({
    content: contentString
});
Run Code Online (Sandbox Code Playgroud)

然后当你的标记被点击时,你只是打开那个信息窗口

google.maps.event.addListener(marker, 'click', function() {
    infowindow.open(map,marker);
 });
Run Code Online (Sandbox Code Playgroud)

这将为每个标记显示相同的内容,您不希望这样.


你想要做的只是创建一个没有内容的infowindow(在你的标记循环之前).然后,当单击标记时,将内容附加到信息窗口...然后打开信息窗口.这将节省代码行并导致信息窗口自动关闭.

在创建标记之前(使用循环)添加此标记

infowindow = new google.maps.InfoWindow();
Run Code Online (Sandbox Code Playgroud)

在您的标记代码中添加infowindow.setContent调用

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

 });
Run Code Online (Sandbox Code Playgroud)