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

Issue trying to set google maps info window content with

本文关键字:窗口 信息窗 信息 设置 谷歌地图 问题      更新时间:2023-09-26

所以我有几个标记从数组中出现,但我有很多困难设置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;
}

您呼叫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闭包内循环-一个简单的实用例子,了解更多关于函数作用域的信息。