簡體   English   中英

通過單擊Google地圖上的標記來打開div而不是信息窗口

[英]Open div instead of infowindow by clicking marker on Google Maps

我有一個全屏的Google Map,其底部有一個小div,可容納用於打開和關閉標記的圖像。 我還有一個隱藏的div,其中包含每個標記的信息(通常會出現在信息窗口中)。

我希望當在地圖上單擊標記時能夠顯示()或fadein()隱藏的div。 這就是我添加標記的方式。

for (i = 0; i < locations.length; i++) {
var myLatLng = new google.maps.LatLng(locations[i][1], locations[i][2]);
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][2], locations[i][2]),
icon: icons[locations[i][4]].icon,
map: map,
id: locations[i][3],
type: locations[i][4]
});
markerGroups[locations[i][4]].push(marker);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
toggleWindow(marker.id);
})(marker, i));
bounds.extend(myLatLng);
}
if (locations.length > 0){
map.fitBounds(bounds);
}

數組中的每個位置如下所示:[“ 1.50英寸”,37.5,-77.33,0,“ hail150”]

切換窗口功能為:

function toggleWindow(id){
var godiv = '#sr'+id;
if ($(godiv).css('display') == 'block') {
$(godiv).css('display', 'none');
}
else {
$("#reportframe").children().hide(); 
$(godiv).css('display', 'block');
};
};

當您單擊標記時,出現錯誤:

Uncaught TypeError:無法讀取未定義的屬性“ apply”(main.js:17)

我已經嘗試了幾種不同的方法,但是ID似乎不匹配或GMaps無法訪問var。

小提琴

用作click handler的函數調用必須返回一個函數 (返回的函數將是該處理函數)。 當前,該函數將不返回任何內容,並且在錯誤消息中undefined “ nothing”。

因此它必須例如:

google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function(){toggleWindow(marker.id);}
})(marker, i));

查看演示

匿名函數關閉有問題。 如果我使用createMarker函數創建閉包,它將對我有用。

function createMarker(location) {
    var marker = new google.maps.Marker({
        position: new google.maps.LatLng(location[1], location[2]),
        icon: icons[location[4]].icon,
        map: map,
        id: location[3],
        type: location[4]
    });
    markerGroups[location[4]].push(marker);
    google.maps.event.addListener(marker, 'click', function () {
        var godiv = '#sr' + marker.id;
        if ($(godiv).css('display') == 'block') {
            $(godiv).css('display', 'none');
        } else {
            $("#reportframe").children().hide();
            $(godiv).css('display', 'block');
        }
    });
  return marker;
}

像這樣使用它:

// add markers
var infowindow = new google.maps.InfoWindow();
var bounds = new google.maps.LatLngBounds();
var marker, i;

for (i = 0; i < locations.length; i++) {
  var marker = createMarker(locations[i]);
  bounds.extend(marker.getPosition());
}

工作小提琴

暫無
暫無

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

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