在Google地图中关闭后重新打开infowindow

时间:2012-05-18 16:27:32

标签: javascript google-maps-api-3

我有一张带有街景全景图,一个信息窗和一个可拖动标记的地图。拖动标记后,函数会请求getPanoramaByLocation查看视图服务是否可用。如果不是,那就关闭了信息窗口。这很好,但当我再次点击标记时,信息窗不再打开。你知道有什么问题吗? TX

    var sv = new google.maps.StreetViewService();

    function initialize() {

        var optionMap = {
            zoom: 13,
            center: new google.maps.LatLng(47.390251,0.68882),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var myMap = new google.maps.Map(document.getElementById("mapDiv"), optionMap);
        var optionsMarker = {
            position: new google.maps.LatLng(47.390251,0.68882),
            map: myMap,
            draggable: true,
            title: "my marker"
            }
        var marker = new google.maps.Marker(optionsMarker);
        var infowindowDiv = '<div id="streetview" style="width:300px;height:200px;"' +'</div>';

        var infoWindow = new google.maps.InfoWindow({
            content: infowindowDiv,
            position: myMap.getCenter() });

        google.maps.event.addListener(marker, 'click', function() {
         infoWindow.open(myMap, marker);
         });

        google.maps.event.addListener(infoWindow, 'domready', function() {
            var panorama = new
        google.maps.StreetViewPanorama(document.getElementById("streetview"));
            panorama.setPosition(infoWindow.getPosition());

        google.maps.event.addListener(marker, 'dragend', function(event) {
          sv.getPanoramaByLocation(event.latLng, 50, processSVData);});             

        function processSVData(data, status) {
          if (status == google.maps.StreetViewStatus.OK) {

              var markerPanoID = data.location.pano;
              // Set the Pano to use the passed panoID
              panorama.setPano(markerPanoID);
              panorama.setPov({
                heading: 270,
                pitch: 0,
                zoom: 1
              });
              panorama.setVisible(true);
            } 
            else {
            infoWindow.close();
            infoWindow = null;              
            };
        }                   
    }); 
    }

2 个答案:

答案 0 :(得分:2)

来自GMaps API文档:

close() None    Closes this InfoWindow by removing it from the DOM structure.

https://developers.google.com/maps/documentation/javascript/reference#InfoWindow

所以...如果你关闭了infowindow,它就消失了。永远。更是如此,如果你真的通过说“infoWindow = null;”来确定它已经消失了你必须做一个新的。我的建议是重构你的代码,以便有一个单独的函数,按需创建infowindow并返回它。在您的单击事件定义中,检查infowindow是否为null,如果是,则获取一个新的。

HTH

答案 1 :(得分:1)

正如另一个答案所解释的那样,当用户点击关闭按钮时,信息框html将从DOM中删除,但JS对象仍在那里。

当你创建一个infowindow时,你必须调用open方法在地图上看到它

myInfoWindow.open(mymap);

所以,如果你听'closeclick'事件并保持infowindow状态

var infoWindowClosed = false;
google.maps.event.addListener(myInfoBox, "closeclick", function () {
    infoWindowClosed = true;
});

您可以按需重新打开myInfoWindow

if(infoWindowClosed){
    myInfoWindow.open(mymap);
}