如何在For循环中为多个标记创建InfoWindows

时间:2012-09-10 15:55:42

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

我有以下代码,它正确地创建了我正在存储的所有标记,但是当我点击它们中的任何一个时,只创建了最后一个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出现。这里有明显的错误吗?

1 个答案:

答案 0 :(得分:5)

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

   // 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.