cli*_*ray 5 javascript jinja2 google-maps-api-3 google-maps-markers
我有以下代码,它正确创建我存储的所有标记,但是当我点击它们中的任何一个时,只创建了最后一个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 %}
Run Code Online (Sandbox Code Playgroud)
我尝试将事件监听器更改为:
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent({{record.description|json_encode|safe}});
infowindow.open(map, this);
});
Run Code Online (Sandbox Code Playgroud)
正如我所看到的那样,在SO上为其他一些用户工作但是没有InfoWindows出现.这里有明显的错误吗?
您需要在单独的函数中创建标记:
// Global var
var infowindow = new google.maps.InfoWindow();
Run Code Online (Sandbox Code Playgroud)
然后,在循环内:
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);
Run Code Online (Sandbox Code Playgroud)
最后:
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);
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3806 次 |
| 最近记录: |