[英]Google Map info window is only showing on one marker in JavaScript
我正在開發一個提供基於位置的服務的網站。 所以我使用JavaScript將我的網站與Google Map API集成。 然后我將數據導入Map並在Map上將每個項目顯示為標記。 在地圖上導入和顯示數據作為標記工作正常。
但是我在地圖上顯示每個標記的信息窗口時遇到問題。 問題是我的地圖上有兩個標記,但是當我點擊任何項目時,信息窗口始終顯示在同一個項目上。 請參閱下面的屏幕截圖。
正如您在屏幕截圖中看到的,我點擊了右側的標記,但信息窗口顯示在不同的項目上。
這是我對地圖的完整JavaScript:
var map;
function initialize() {
var lat = $('.region-latitude').val();
var long = $('.region-longitude').val();
map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: new google.maps.LatLng(lat, long),
mapTypeId: google.maps.MapTypeId.TERRAIN
});
var script = document.createElement('script');
script.src = $('.map-items-url').val();
document.getElementsByTagName('head')[0].appendChild(script);
}
window.items_callback = function (results) {
for (var i = 0; i < results.features.length; i++) {
var coords = results.features[i].geometry.coordinates;
var latLng = new google.maps.LatLng(coords[0], coords[1]);
var itemMarker = new google.maps.Marker({
position: latLng,
map: map,
title: results.features[i].name
});
var contentString = '<h3>' + results.features[i].name + '</h3>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
itemMarker.addListener('click', function () {
infowindow.open(map, itemMarker);
});
}
}
google.maps.event.addDomListener(window, 'load', initialize)
我的代碼出了什么問題? 如何為每個標記顯示不同的信息窗口?
這看起來像是一個范圍問題。 目前,當click
處理程序被激活時, itemMarker
指向最后添加的標記以及infowindow
點,最后的信息窗口中創建。 這就是為什么它總是只顯示最后添加的標記。 您必須創建一個封裝這些變量的范圍。
嘗試這個:
for (var i = 0; i < results.features.length; i++) {
(function(index){
var coords = results.features[index].geometry.coordinates;
var latLng = new google.maps.LatLng(coords[0], coords[1]);
var itemMarker = new google.maps.Marker({
position: latLng,
map: map,
title: results.features[index].name
});
var contentString = '<h3>' + results.features[index].name + '</h3>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
itemMarker.addListener('click', function () {
infowindow.open(map, itemMarker);
});
})(i);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.