0

我使用 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]  
      });  
    }   
} 
4

1 回答 1

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()
于 2012-08-10T07:02:57.130 回答