簡體   English   中英

Google Maps API v3 - 標記全部共享相同的InfoWindow

[英]Google Maps API v3 - Markers All Share The Same InfoWindow

我一直在四處挖掘,我似乎無法弄清楚這一點。 這讓我瘋狂! 我一般都是javascript的新手,所以我不能完全理解可以解決我的問題的翻譯。 我注意到很多人都有這個問題,但他們似乎都使用比我更高級(或者只是令人困惑)的代碼。無論如何,這里有!

我一直遇到的問題是我的所有標記共享相同的內容。

function initialize() {
var myOptions = {
    center: new google.maps.LatLng(34.151271, -118.449537),
    zoom: 9,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    mapTypeControl: false,
    streetViewControl: false,
    panControl: false,
    zoomControl: true,
    zoomControlOptions: { style: google.maps.ZoomControlStyle.SMALL },
};

var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

setMarkers(map, clubs);

}

var clubs = [
['Poop', 34.223868, -118.601575, 'Dookie'],
['Test Poop', 34.151271, -118.449537, 'Test Business']
];

function setMarkers(map, locations) {
var image = new google.maps.MarkerImage('images/image.png',
    new google.maps.Size(25, 32),
    new google.maps.Point(0,0),
    new google.maps.Point(0, 32)
);
var shape = {
coord: [1, 1, 1, 20, 18, 20, 18 , 1],
type: 'poly'
};
for (var i = 0; i < locations.length; i++) {
var club = locations[i];
var myLatLng = new google.maps.LatLng(club[1], club[2]);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
    position: myLatLng,
    map: map,
    icon: image,
    shape: shape,
    title: club[0],
});
google.maps.event.addListener(marker, 'click', function(){
    infowindow.setContent(club[3]);
    infowindow.open(map, this);
});
}
}

我知道我很糟糕,但有人請幫助我! :P

問題是因為您在循環中為標記點擊設置事件偵聽器。 因此,所有標記最終只能獲取最后一個標記的內容。 試試這個。 創建一個新的全局函數:

function bindInfoWindow(marker, map, infowindow, html) {
    marker.addListener('click', function() {
        infowindow.setContent(html);
        infowindow.open(map, this);
    });
} 

然后在你的循環中,替換為:

google.maps.event.addListener(marker, 'click', function(){
    infowindow.setContent(club[3]);
    infowindow.open(map, this);
});

有了這個:

// add an event listener for this marker
bindInfoWindow(marker, map, infowindow, club[3]); 

設置標記對象(var marker = new ...)時,將此行更改為:“title:club [0]”,“title:club [i],”。 是的,只需將0更改為i。

那應該可以解決問題。

試試這個鏈接,獲取有關Google Maps API的教程和示例。

http://code.google.com/apis/maps/documentation/javascript/tutorial.html

它應該非常簡單和有用。

暫無
暫無

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

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