我使用ajax获取位置列表,然后根据从ajax结果创建的数组来标记谷歌地图。如何使回调函数具有ajax调用,数组构造,标记谷歌地图全部同步。(不调用updateMapMarkers())这是我的代码。感谢
// main function to do work
// need timer calling getLocations()
function loadMapList() {
// initial google map here
var count = 40;
$("#countdown").html(count + " seconds remaining!");
getLocations();
count--;
timeout = setInterval(function(){
$("#countdown").html(count + " seconds remaining!");
if (count == 0) {
count =40;
getLocations();
}
count--;
}, 1000);
}
// using ajax to get location info
function getLocations(){
var url = "getLocations";
$.ajax({
type: 'GET',
url: url,
dataType: 'json',
async: false,
success: function(data){
if (data.locationList == null || data == 'undefined') {
return;
}
allLocArray.length = 0;
for (i in data.locationList) {
allLocArray[i] = new Array(3);
allLocArray[i][0] = data.locationList[i].LOCATE_NAME;
allLocArray[i][1] = data.locationList[i].LATITUDE;
allLocArray[i][2] = data.locationList[i].LONGITUDE;
}
},
error: function(xhr, textStatus, error){
alert(xhr.statusText);
alert(textStatus);
alert(error);
}
});
}
// mark google map using global var array
function updateMapMarkers() {
var myOptions = {
zoom: zoomLevel,
center: new google.maps.LatLng(centerLat, centerLong),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
for (var i=0; i<allLocArray.length; i++) {
var myLatLng = new google.maps.LatLng(allLocArray[i][1], allLocArray[i][2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title:allLocArray[i][0]
});
}
}
答案 0 :(得分:0)
您可以简单地将回调函数作为参数传递:
function getLocation(callback){
...
callback();
...
}
function updateInfo(){
...
}
getLocation(updateInfo);
编辑:您可以将功能链接在一起以实现“串行”执行感:
的 1。使用数组
function foo(callbacks){
...
for(c in callbacks)
c();
}
function bar(){
...
}
function baz(){
...
}
foo([bar, baz]);
<强> 2。使用回调链
function foo(callback){
...
callback()
}
function bar(callback){
...
callback()
}
function baz(callback){
...
callback()
}
foo(function(){
bar(function(){
baz(function(){
alert('done');
});
});
});
第3。使用课程
class MyClass
{
function foo(){
...
return this;
}
function bar(callback){
...
return this;
}
function baz(callback){
...
return this;
}
}
var obj = MyClass();
obj.foo().bar().baz()