InfoWindow不想关闭谷歌地图Api V3

时间:2010-01-11 01:23:45

标签: javascript google-maps google-maps-api-3

我无法关闭我拖动的标记的信息窗口,任何想法? 谢谢你的帮助

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); 
}

1 个答案:

答案 0 :(得分:3)

是的,您在私有作用域中定义infowindow,但在该作用域之外访问它。将其添加到脚本的开头:

var infowindow;

从构造函数行中删除'var':

infowindow = new google.maps.InfoWindow(

完成的代码(来自您的样本)将look like this

多一点背景

使用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
}