谷歌搜索回调功能的问题

时间:2014-02-05 15:16:48

标签: javascript google-maps-api-3 google-places-api asynchronous

我遇到了一个奇怪的问题。这是关于谷歌地方搜索类型" textsearch"。我正在使用关键字搜索结果的地图,并使用回调函数来创建结果(" li"在html中)。

问题是google Place搜索API只能提供20个文本搜索结果。要检索更多结果,我们必须致电pagination.nextPage()。这会调用相同的callBack函数并提供更多结果。

所以,

我的代码是

var request = {query: 'pizza in newyork'};
var service = new google.maps.places.PlacesService(map);
service.textSearch(request, callBack1);

function callBack1(results, status,pagination)  {
    for (var i = 0; i < results.length; i++) {
      var place = results[i];
      //add place as li
    }
    if (pagination.hasNextPage) {
        pagination.nextPage();
    }
            doOtherOperation();
}

function doOtherOperation() {
     //do manipulations on "li" which are created from callBack1
}

问题是doOtherOperation()在callBack1()完成执行之前开始执行。

有人可以帮忙吗?如何确保callBack1将完全执行(包括pagination.nextPage()的递归调用)?

2 个答案:

答案 0 :(得分:2)

不是专家,但看起来像一个小的逻辑缺陷,所以我会这样做:

if (pagination.hasNextPage) {
    pagination.nextPage();
    }
else
   {
   doOtherOperation();
   }

否则doOtherOperation();每次都会被调用,无论你是否必须再次访问nextPage。

希望有所帮助

答案 1 :(得分:1)

尝试用doOtherOperation()

包裹setTimeout(function() { /* */}, 0)

更新......那怎么样?

var flag = false;

function callBack1(results, status,pagination)  {
    /* since callback1 is the same callback for textSearch() and nextPage() - 
        you need to call dootherOperation at the beginning of statement */
    if (flag) {
        doOtherOperation();
    }
    for (var i = 0; i < results.length; i++) {
      var place = results[i];
      //add place as li
    }
    if (pagination.hasNextPage) {
        flag = true;
        pagination.nextPage();
    }
    else {
        flag = false;
    }
}