1

我无法关闭我正在拖动的标记的信息窗口,知道吗?谢谢你的帮助

function mapClick(event) {

        createLocationMarker(event.latLng);

}
function createLocationMarker(location) {
    var clickedLocation = new google.maps.LatLng(location)
    var gMarker = new google.maps.Marker({position:location, map:gMap2, draggable: true});

    gMap2.setCenter(location);
    displayMarkerPosition(gMarker);

     google.maps.event.addListener(gMarker, "dragstart", closeMapInfoWindow );
     google.maps.event.addListener(gMarker, "dragend", function() { displayMarkerPosition(gMarker); });
}

function closeMapInfoWindow() {infowindow.close(); }

function displayMarkerPosition(gMarker) {
    var message = "my message";
    var infowindow = new google.maps.InfoWindow(
    {   content : message,
    });

    infowindow.open(gMap2,gMarker); 
}
4

1 回答 1

3

是的,您infowindow在私有范围内定义,但在该范围之外访问它。将此添加到脚本的开头:

var infowindow;

并从您的构造函数行中删除“var”:

infowindow = new google.maps.InfoWindow(

完成的代码(来自您的示例)看起来像这样

多一点背景

当您使用 定义变量时var,它与该范围相关联。如果在函数中定义它,则只有该函数和其中定义的其他函数才能访问该变量。传递它的唯一其他方法是作为函数中的参数。

更新我会这样做以促进多个信息窗口。请注意,我已恢复到原始var声明,以使其范围仅限于该函数。然后我返回对对象的引用以供以后使用:

function mapClick(event) {
    createLocationMarker(event.latLng);
}
function createLocationMarker(location) {
    var clickedLocation = new google.maps.LatLng(location)
    var gMarker = new google.maps.Marker({position:location, map:gMap2, draggable: true});

    gMap2.setCenter(location);
    // Store reference to info window
    var info = displayMarkerPosition(gMarker);

    google.maps.event.addListener(gMarker, "dragstart", function(){ info.close } );
    google.maps.event.addListener(gMarker, "dragend", function() { displayMarkerPosition(gMarker); });
}

function displayMarkerPosition(gMarker) {
    var message = "my message";
    var infowindow = new google.maps.InfoWindow(
      {   content : message }
    );

    infowindow.open(gMap2,gMarker); 
    return infowindow; // Return the reference to the infowindow
}
于 2010-01-11T01:28:12.980 回答