Javascript 数组项 == “未定义”在谷歌地图功能中
你好 我正在循环一个 JSON 对象并为每个项目创建一个新的地图标记。创建标记后,我将其推送到一个数组(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]);
任何帮助将不胜感激。
Hello
I'm looping over a JSON object and creating a new map marker for each item. After the marker is created, I push it to an array (var markers) for future manipulation. Problem is, when I try to access the array items (eg: console.log(markers[3])), I am given an "undefined" value.
Relevant code below:
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]);
Any help would be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
get json 异步运行。试试这个:
get json runs asynchronously. try this:
尝试一下,
因为查看您的代码,
markers
数组中只有一个元素。如果您要在该数组中放入 4 个元素,那么使用
markers[3]
您将访问第四个元素。Try to
because looking at your code, there is just one element in
markers
array.If you will put into that array 4 elements, then using
markers[3]
you will access fourth element.尝试:
try: