试图设置谷歌地图信息窗口内容的问题

时间:2015-08-02 20:03:14

标签: javascript

所以我从数组中出现了几个标记,但是我设置出现的InfoWindows内容有很多困难

我把标题设置得很好,但是当我尝试设置内容时,它并没有设置内容,但仍会显示标题。

我做错了什么?

for (index = 0; index < data.length; ++index) {
    locationName = data[index].LocationName;
    locationID = data[index].LocationID;
    locationX = data[index].XCord;
    locationY = data[index].YCord;
    var infoContent = '<div><h3>' + data[index].LocationName + '</h3></div><div>' + data[index].LocationID +  '</div>';
    var mapLocation = new google.maps.LatLng(locationX,locationY);
    var marker = new google.maps.Marker({ // Set the marker
        position: mapLocation, // Position marker to coordinates
        icon: image, //use our image as the marker
        map: map, // assign the marker to our map variable
        title: data[index].LocationName,
        content: infoContent
        //draggable:true //Have a guess what this does
    });

    // Allow each marker to have an info window    
    google.maps.event.addListener(marker, 'click', (function (marker, index) {
        return function () {
            infoWindow.setContent(infoContent);
            infoWindow.setContent(this.title);
            infoWindow.open(map, this);
        }
    })(marker, index));

    var infoWindow = new google.maps.InfoWindow({ 
        content: infoContent 
    }), marker, index;
}

1 个答案:

答案 0 :(得分:1)

您正在拨打setContent两次:

infoWindow.setContent(infoContent);
infoWindow.setContent(this.title);

我想应该删除最后一个。

修改

要获取正确的infoWindow内容,请尝试将eventListener的创建移动到函数:

// Allow each marker to have an info window    
updateInfoWindowOnMarkerClick(marker, infoContent); 

//Somewhere after the loop
function updateInfoWindowOnMarkerClick(marker, infoContent){
    google.maps.event.addListener(marker, "click", function () {
        infoWindow.setContent(infoContent);
        infoWindow.open(map, this);
    });      
}          

有关功能范围的更多信息,请查看JavaScript closure inside loops – simple practical example