【问题标题】:How to Create InfoWindows for Multiple Markers in a For loop如何在 For 循环中为多个标记创建 InfoWindows
【发布时间】:2012-09-03 12:42:58
【问题描述】:

我有以下代码,它正确地创建了我正在存储的所有标记,但是当我单击其中任何一个时,只会创建最后一个 InfoWindow,并且无论我单击哪个标记,它都只会出现在最后一个标记上。我想这与我的 for 循环中使用的相同变量有关。

{% for record in records %}

//need to do the JSON encoding because JavaScript can't have Jinja2 variables
//I need the safe here because Jinja2 tries to escape the characters otherwise
var GPSlocation = {{record.GPSlocation|json_encode|safe}};  
var LatLng = GPSlocation.replace("(", "").replace(")", "").split(", ")
var Lat = parseFloat(LatLng[0]);
var Lng = parseFloat(LatLng[1]);

var markerLatlng = new google.maps.LatLng(Lat, Lng);

var marker = new google.maps.Marker({
    position: markerLatlng,
    title: {{record.title|json_encode|safe}}
});

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

google.maps.event.addListener(marker, 'click', function () {
    infowindow.setContent({{record.description|json_encode|safe}});
    infowindow.open(map, marker);
    });

//add the marker to the map
marker.setMap(map);

{% endfor %}

我尝试将事件侦听器更改为:

google.maps.event.addListener(marker, 'click', function () {
        infowindow.setContent({{record.description|json_encode|safe}});
        infowindow.open(map, this);
        });

正如我所见,这对 SO 上的其他一些用户有效,但随后没有 InfoWindows 出现。这里有什么明显的错误吗?

【问题讨论】:

    标签: javascript google-maps-api-3 google-maps-markers jinja2


    【解决方案1】:

    您需要在单独的函数中创建标记:

       // Global var
       var infowindow = new google.maps.InfoWindow();
    

    然后,在循环内部:

        var markerLatlng = new google.maps.LatLng(Lat, Lng);
        var title = {{record.title|json_encode|safe}}
        var iwContent = {{record.description|json_encode|safe}}
        createMarker(markerLatlng ,title,iwContent);
    

    最后:

        function createMarker(latlon,title,iwContent) {
          var marker = new google.maps.Marker({
              position: latlon,
              title: title,
              map: map
        });
    
    
    google.maps.event.addListener(marker, 'click', function () {
        infowindow.setContent(iwContent);
        infowindow.open(map, marker);
        });
    
        }
    

    Explanation here.

    【讨论】:

    • 啊,这一切都清楚了。感谢您的帮助,我非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多