簡體   English   中英

如何使用Google Maps 3 API關閉信息窗口?

[英]How do I close an infowindow with Google Maps 3 API?

我看過其他文章,但是他們沒有像我一樣動態地遍歷標記。 當使用以下代碼單擊另一個標記時,如何創建一個將關閉信息窗口的事件?

$(function(){
    var latlng = new google.maps.LatLng(45.522015,-122.683811);
    var settings = {
        zoom: 10,
        center: latlng,
        disableDefaultUI:false,
        mapTypeId: google.maps.MapTypeId.SATELLITE
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"), settings);

    $.getJSON('api',function(json){
        for (var property in json) {
            if (json.hasOwnProperty(property)) {
                var json_data = json[property];
                var the_marker = new google.maps.Marker({
                    title:json_data.item.headline,
                    map:map,
                    clickable:true,
                    position:new google.maps.LatLng(
                        parseFloat(json_data.item.geoarray[0].latitude),
                        parseFloat(json_data.item.geoarray[0].longitude)
                    )
                });
                function buildHandler(map, marker, content) {
                    return function() {
                        var infowindow = new google.maps.InfoWindow({
                            content: '<div class="marker"><h1>'+content.headline+'</h1><p>'+content.full_content+'</p></div>'
                        });
                        infowindow.open(map, marker);
                    };
                }
                new google.maps.event.addListener(the_marker, 'click',buildHandler(map, the_marker, {'headline':json_data.item.headline,'full_content':json_data.item.full_content}));
            }
        }
    });
});

我終於想通了...不,謝謝這里的任何人...其實很簡單:

首先,設置一些變量來存儲信息窗口:

var infowindow;

然后將其添加到觸發其他infowindow.open()的onClick函數所在的位置。 放開它:

if(infowindow) {infowindow.close()}

在循環內部,否則添加標記。

例如:

在我腳本的最上方:

var infowindow;

在我添加標記的循環中:

function buildHandler(map, marker, content) {
    return function() {
        if(infowindow) {infowindow.close()}
        infowindow = new google.maps.InfoWindow({
            content: 'My Content here'
        });
        infowindow.open(map, marker);
    };
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM