我得到Uncaught TypeError:无法读取属性' length'尝试将json数据作为我的Google地图的标记返回时为null。我做错了什么,因为console.log(data);
会返回我的数据,所以我知道这很好。
function initialize() {
var latitude = -23.92175976307374,
longitude = 24.120724868774414,
center = new google.maps.LatLng(latitude,longitude),
mapOptions = {
center: center,
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_branches"), mapOptions);
setMarkers(center, map);
function setMarkers(center, map) {
var json = (function () {
var json = null;
$.ajax({
'dataType': "json",
'url': "/data/supplier_branches/",
'success': function (data) {
json = data;
console.log(data);
}
});
return json;
})();
for (var i = 0, length = json.length; i < length; i++) {
var data = json[i],
latLng = new google.maps.LatLng(data.lat, data.lng);
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: data.info
});
infoBranch(map, marker, data);
}
}
function infoBranch(map, marker, data) {
var infoWindow = new google.maps.InfoWindow();
// Attaching a click event to the current marker
google.maps.event.addListener(marker, "click", function(e) {
infoWindow.setContent(data.title+data.info);
infoWindow.open(map, marker);
});
// Creating a closure to retain the correct data
// Note how I pass the current data in the loop into the closure (marker, data)
(function(marker, data) {
// Attaching a click event to the current marker
google.maps.event.addListener(marker, "click", function(e) {
infoWindow.setContent(data.content);
infoWindow.open(map, marker);
});
})(marker, data);
}
};
google.maps.event.addDomListener(window, 'load', initialize);
答案 0 :(得分:0)
您的变量 json 是在您的ajax调用中定义的,因此请尝试window.json = data;
以便能够在其他函数中使用它。
还值得一提的是,之后您需要在所有window.
变量之前放置json
。例如window.json.length