这是json数据
{
"title": "{exp:channel:entries channel="supplier_branches" orderby="title" sort="asc" dynamic="no" limit="500" status="open"}{title}{/exp:channel:entries}",
"info": "infoz",
"lat": "{exp:channel:entries channel="supplier_branches" orderby="title" sort="asc" dynamic="no" limit="500" status="open"}{sb_lat}{/exp:channel:entries}",
"lng": "{exp:channel:entries channel="supplier_branches" orderby="title" sort="asc" dynamic="no" limit="500" status="open"}{sb_lng}{/exp:channel:entries}"
}
这是获取标记的代码:
function setMarkers(center, map) {
var json = (function () {
var json = null;
$.ajax({
'dataType': "json",
'url': "/data/supplier_branches/",
'success': function (data) {
json = data;
console.log(JSON.stringify(data, ["title","info","lat","lng"], 4));
}
});
return json;
})();
for (var i = 0, length = json.length; i < length; i++) {
latLng = new google.maps.LatLng(data.lat, data.lng);
var data = json[i];
var marker = new google.maps.Marker({
position: latLng,
title: data.info,
map: map
});
infoBranch(map, marker, data);
}
}
我的代码返回json数据但不将其用作标记。这是什么错?
整个地图代码:
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(JSON.stringify(data, ["title","info","lat","lng"], 4));
}
});
return json;
})();
for (var i = 0, length = json.length; i < length; i++) {
latLng = new google.maps.LatLng(data.lat, data.lng);
var data = json[i];
var marker = new google.maps.Marker({
position: latLng,
title: data.info,
map: map
});
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);
Chrome中的控制台错误:
Uncaught TypeError: Cannot read property 'length' of null branches_maps.js:30
setMarkers branches_maps.js:30
initialize
答案 0 :(得分:0)
$ .ajax是异步的,所以当你启动for循环时,json是未定义的。将你的for循环粘贴在$ .ajax回调函数中。