简体   繁体   English

google maps infoWindow in javascript(通过循环创建多个infoWindow)

[英]google maps infoWindow in javascript (creating multiple infoWindows through a loop)

I am pulling my latlng object from a database and when I loop through the query in the javascript the markers all populate just fine, but when ever I click on one they all open the same infoWindow object on a different marker.我正在从数据库中提取我的 latlng object,当我遍历 javascript 中的查询时,标记都填充得很好,但是当我单击一个时,它们都会在不同的标记上打开相同的 infoWindow ZA8CFDE6331BD59EB2AC9Z6F8911C4B666。 I assume this is some sort of naming issue, but I am having trouble finding out why because it all looks right to me.我认为这是某种命名问题,但我很难找出原因,因为这一切对我来说都是正确的。 the following code is in a cfoutput tag creating the loop.以下代码位于创建循环的 cfoutput 标记中。

var latlng_#get_latlng.recordcount# = new google.maps.LatLng(#get_latlng.mlat#,#get_latlng.mlong#); 
var marker_#get_latlng.recordcount# = new google.maps.Marker({
    position: latlng_#get_latlng.recordcount#,
    map: map,
    title: "test"
});

var contentString_#get_latlng.recordcount# = "test" + #get_latlng.recordcount#;

var infowindow_#get_latlng.recordcount# = new google.maps.InfoWindow({
    content: contentString_#get_latlng.recordcount#
});

google.maps.event.addListener(marker_#get_latlng.recordcount#, 'click', function() {
    infowindow_#get_latlng.recordcount#.open(map,marker_#get_latlng.recordcount#);
});

Doesn't 'recordcount' return the number of values in your result set? 'recordcount' 不返回结果集中值的数量吗? In which case, all your variable names will be the same.在这种情况下,您的所有变量名称都将相同。 Therefore they will all be rendered correctly, but will continually overwrite the JavaScript variable reference: and will all create an infoWindow based on the last one you did.因此它们都将正确呈现,但会不断覆盖 JavaScript 变量引用:并且都会根据您所做的最后一个创建一个 infoWindow。

You need a more unique name: I presume you wanted an index based on the resultset index, but a simple count would be fine.您需要一个更独特的名称:我假设您想要一个基于结果集索引的索引,但简单的计数就可以了。

Rather than producing so much redundant JS, I'd create a function that adds the markers.我不会产生这么多冗余的 JS,而是创建一个 function 来添加标记。

function addMarker(lat, lng, title, content) {
    var latlng = new google.maps.LatLng(lat, lng);
    var marker = new google.maps.Marker({
        position: latlng,
        map: map,
        title: title
    });
    var infowindow = new google.maps.InfoWindow({ content: content });
    google.maps.event.addListener(marker, "click", function() {
        infowindow.open(map, marker);
    });
}

Then in your loop:然后在你的循环中:

addMarker(#get_latlng.mlat#,#get_latlng.mlong#,"#get_latlng.title#","#get_latlng.content#");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM