你好 我正在循环一个 JSON 对象并为每个项目创建一个新的 map 标记。创建标记后,我将其推送到一个数组(varmarkers)以供将来操作。问题是,当我尝试访问数组项(例如:console.log(markers[3]))时,我得到一个“未定义”值。
相关代码如下:
var map;
var markers = [];
var activeFilters = [];
function initializeMap() {
var myLatlng = new google.maps.LatLng( 51.506873, -0.125141);
var myOptions = {
zoom: 14,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true
}
map = new google.maps.Map(document.getElementById("location_map"), myOptions);
$.getJSON('../js/hotspots.json', function(data) {
var hotspots = data.scenes[0].hotspots;
$.each(hotspots, function(i) {
var lat = hotspots[i].latitude;
var lon = hotspots[i].longitude;
var point = new google.maps.LatLng(lat,lon);
var cat = hotspots[i].hotspottype;
var weburl = hotspots[i].weburl;
var marker = addMarker(point,cat,weburl);
});
});
}
function addMarker(point, cat, weburl) {
var markerUrl = weburl;
var marker = new google.maps.Marker({
position: point,
map: map
});
marker.category = cat;
markers.push(marker);
};
initializeMap();
console.log(markers[3]);
任何帮助将不胜感激。
最佳答案
get json 异步运行。试试这个:
$.getJSON('../js/hotspots.json', function(data) {
var hotspots = data.scenes[0].hotspots;
$.each(hotspots, function(i) {
var lat = hotspots[i].latitude;
var lon = hotspots[i].longitude;
var point = new google.maps.LatLng(lat,lon);
var cat = hotspots[i].hotspottype;
var weburl = hotspots[i].weburl;
var marker = addMarker(point,cat,weburl);
});
console.log(markers);
});
关于Google map 函数中的 Javascript 数组项 == "undefined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5703436/