infowindow.setContent只显示一条记录



我正在Laravel做一个项目。

这是我用谷歌地图显示带有多个标记的地图的脚本。我有两个json对象,我正在检索其中一个带有位置,另一个带有autos。一个位置可以有许多自动,因此它是一对多的关系。

我想做的是在infowindow.setContent中显示位置的描述和属于该位置的自动。正确显示地图和具有正确位置的标记。但在infowindow.setContent中显示了该位置的描述和标题以及属于该位置的汽车的最后记录。

当脚本运行时,console.log会按原样显示信息。这意味着我的autos循环运行良好,但当我将结果传递给infowindow.setContent时,它只读取最后一条记录。

这是我第一次在这里寻求帮助,如果我不够清楚,请原谅。我将非常感谢任何回复我的人。

我的脚本:

<script  type="text/javascript">  
var locations = @json($locations);
var autos = @json($autos);
var infowindow = new google.maps.InfoWindow();

var mymap = new GMaps({
el: '#mymap',
center: {lat: 41.323029, lng: 19.817856},
zoom:6
});

$.each( locations, function( index, value ){
mymap.addMarker({
lat: value.lat,
lng: value.long,
title: value.title,
click: function(e) {
for (var auto in autos)
{
if(autos[auto].location_id == value.id)
{
var autoBrands =autos[auto].brand;
console.log(autoBrands);
}
}

infowindow.setContent('<div><strong>' + autoBrands + '</strong><br></div>'+  '<div><strong>' + value.title + '</strong><br></div>' + '<div><strong>' + value.description + '</strong><br></div>');
infowindow.open(mymap, this);
}
});
});
</script>

看起来您只是在循环中重新分配了autoBrands的值。为什么不将其创建为数组对象?类似的东西

<script  type="text/javascript">  
var locations = @json($locations);
var autos = @json($autos);
var infowindow = new google.maps.InfoWindow();

var mymap = new GMaps({
el: '#mymap',
center: {lat: 41.323029, lng: 19.817856},
zoom:6
});

$.each( locations, function( index, value ){
mymap.addMarker({
lat: value.lat,
lng: value.long,
title: value.title,
click: function(e) {
var autoBrands = [];
for (var auto in autos)
{
if(autos[auto].location_id == value.id)
{
autoBrands.push(autos[auto].brand);
console.log(autoBrands);
}
}

infowindow.setContent('<div><strong>' + autoBrands.join(",") + '</strong><br></div>'+  '<div><strong>' + value.title + '</strong><br></div>' + '<div><strong>' + value.description + '</strong><br></div>');
infowindow.open(mymap, this);
}
});
});

希望这能有所帮助!

您在所有位置上循环,为每个位置添加一个标记。但是,您只有一个infowindow变量。在循环的每一次迭代中,您都在更新同一信息窗口的内容,因此它最终只获取上一次迭代的内容。

有一个单独的功能,可以打开信息窗口以响应用户的点击,类似于以下内容:

$.each( locations, function( index, value ){
mymap.addMarker({
lat: value.lat,
lng: value.long,
title: value.title,
click: function(e) {
for (var auto in autos)
{
if(autos[auto].location_id == value.id)
{
var autoBrands =autos[auto].brand;
console.log(autoBrands);
}
}
openInfowindow(
'<div><strong>' + autoBrands + '</strong><br></div>'+  '<div><strong>' + value.title + '</strong><br></div>' + '<div><strong>' + value.description + '</strong><br></div>',
this
);
}
});
});
function openInfowindow(content, marker)
{
infowindow.setContent(content);
infowindow.open(mymap, marker);
}

最新更新