【发布时间】:2020-07-14 07:56:33
【问题描述】:
您好,我是 stackoverflow(和编码)的新手,但我正在开发一个 Web 应用程序,我想在其中基于提取的 JSON 文件添加动态标记和信息窗口。有超过 200 个标记,因此它们需要是动态的。我有可以添加标记的代码,但是一旦我添加了 infoWindows,它就没有了。有人能看出为什么吗?输出下降到只有一个标记,没有 infoWindow。
这是我的代码:
function initMap() {
var myLatLng = {
lat: 26.967,
lng: -99.25
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
$.ajax({
type: 'GET',
url: 'https://us-central1-cloud-calendar-project.cloudfunctions.net/InfoWindow',
success: function(data) {
data = JSON.parse(data)
infowindow = new google.maps.InfoWindow();
for (element in data) {
new google.maps.Marker({
position: {
lat: data[element].lat,
lng: data[element].lon
},
map: map,
title: element
});
infowindow.setContent(data[element].country);
marker.addListener('click', function() {
infowindow.open(map, marker);
});
}
}
});
}
我在 stackoverflow 上看到了一个类似问题的帖子,我也尝试过,但没有得到任何标记。
function initMap() {
var myLatLng = {
lat: 26.967,
lng: -99.25
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
$.ajax({
type: 'GET',
url: 'https://us-central1-cloud-calendar-project.cloudfunctions.net/InfoWindow',
success: function(data) {
var json = data = JSON.parse(data);
for (var i = 0; i < json.length; i++) {
point = new google.maps.LatLng(json[i].lat, json[i].lon);
contentString = json[i].Country;
addMarkers(point, contentString);
}
}
});
function addMarkers(point, contentString) {
marker = new google.maps.Marker({
position: point,
map: map
});
infowindow = new google.maps.InfoWindow({
content: contentString
});
marker.push(marker);
infos.push(infowindow);
for (var j = 0; j < markers.length; j++) {
google.maps.event.addListener(markers[j], 'click', function() {
infos[j].open(map, markers[j]);
})
}
}
}
我的 JSON 文件的输出如下所示:
{
"AA": {
"celsius": 32.27777777777778,
"country": "AA",
"day": "25",
"lat": 12.5,
"lon": -70.017,
"month": "03"
},
...
}
【问题讨论】:
-
1) 您不需要为每个标记创建一个新的 Infowindow 对象 2) 您没有在标记单击时设置 Infowindow 内容
-
我在发布的代码中出现错误:
marker is not defined- 您是否在 Javascript 控制台中查看错误? -
否则,发布一个完整的问题做得很好!
标签: json google-maps google-maps-api-3 google-maps-markers infowindow