jQuery-等待循环距离矩阵服务返回最终回调,然后继续

jQuery-等待循环距离矩阵服务返回最终回调,然后继续,jquery,google-maps-api-3,Jquery,Google Maps Api 3,我有一个json格式的地址列表,我想迭代并查找与单个lon/lat(html5地理位置)的距离。我希望找到距离最短的地址(json项),稍后再处理它 我正在使用库和jQuery1.10 我在cookie中设置了用户的位置数据。(有更好的办法吗?) 然后我遍历json地址,得到最接近的地址 这个cookie(通过循环),然后用该数据设置另一个cookie。(有没有 更好的方式?) 此时,我希望根据cookie集以html的形式向用户显示最近的地址 我的设置的问题是DistanceMatrixSer

我有一个json格式的地址列表,我想迭代并查找与单个lon/lat(html5地理位置)的距离。我希望找到距离最短的地址(json项),稍后再处理它

我正在使用库和jQuery1.10

  • 我在cookie中设置了用户的位置数据。(有更好的办法吗?)
  • 然后我遍历json地址,得到最接近的地址 这个cookie(通过循环),然后用该数据设置另一个cookie。(有没有 更好的方式?)
  • 此时,我希望根据cookie集以html的形式向用户显示最近的地址 我的设置的问题是DistanceMatrixService回调是异步的,在负责向用户显示最近地址的函数之后返回

    代码如下所示:

    HTML5地理位置代码:

    function get_user_location() {
      window.onload = function () {
        var html5Options = { enableHighAccuracy: true, timeout: 6000, maximumAge: 0 };
        geolocator.locate(onGeoSuccess, onGeoError, true, html5Options);
      };
    
      function onGeoSuccess(location) {
        $.cookie('user_postal_code', location.address.postalCode);
        $.cookie('user_latitude', location.coords.latitude);
        $.cookie('user_longitude', location.coords.longitude);
        get_hca_rss();
      }
    
      function onGeoError(error) {
        console.log(error);
      }
    }
    
    get_user_location();
    
    function get_hca_rss() {
      var hcafeed = 'http://hcafeeds.medcity.net/rss/er/rss_feed.xml';
      var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from rss where url="' + hcafeed + '"') + '&format=json&diagnostics=true&callback=?';
      $.getJSON(yql,function(data){
        if(data) {
          get_closest_er(data);
        }
      });
    }
    
    function get_closest_er(data, userLocation) {
      var service = new google.maps.DistanceMatrixService();
      var rows = data.query.results.item;
      var origin = $.cookie('user_latitude') + "," + $.cookie('user_longitude');
    
      $.each(rows,function(e) {
        if(rows[e].address != undefined) {
          var destination = rows[e].address;
          tmp = Number.POSITIVE_INFINITY;
          closestIndex = null;
    
          // Google Distance Matrix API
          var service = new google.maps.DistanceMatrixService();
          service.getDistanceMatrix( {
            origins: [origin],
            destinations: [destination],
            travelMode: google.maps.TravelMode.DRIVING,
            unitSystem: google.maps.UnitSystem.IMPERIAL,
            durationInTraffic: false,
            avoidHighways: false,
            avoidTolls: false,
          }, callback);
    
          // Callback for distance api
          function callback(response, status) {
            if (status != google.maps.DistanceMatrixStatus.OK) {
              alert('Error was: ' + status);
            } else {
              var distance = response.rows[0].elements[0].distance.value;
              if (distance < tmp) {
                tmp = distance;
                $.cookie('closestIndex',e);
                $.cookie('closestDistance',response.rows[0].elements[0].distance.text);
              }
            }
          }
    
        }
      });
    
      set_closest_er_html(data);
    
    };
    
    function set_closest_er_html(data) {
      var rows = data.query.results.item;
      var hElem = $('#closestER');
      var uZip = $.cookie('user_postal_code');
      var cIdx = $.cookie('closestIndex');
      var cHospital = rows[cIdx];
      var cName = cHospital.comments.replace(" ER Wait Time", "");
      var cDistance = $.cookie('closestDistance').replace(" mi", "");
      var cWaitTime = cHospital.description.replace(" Mins", "");
    
      hElem.html('<h2>Hospital Info:</h2>');
      hElem.append('<div><span>Your Closest ER </span><span>' + uZip + ' Zip Code</span></div>');
      hElem.append('<div><strong>Hospital </strong><span>' + cName + '</span></div>');
      hElem.append('<div><label>Distance: </label><div>' + cDistance + '</div> Miles</div>');
      hElem.append('<div><label>Wait: </label><div>' + cWaitTime + '</div> Minutes</div>');
    }
    
    jSON拉取:

    function get_user_location() {
      window.onload = function () {
        var html5Options = { enableHighAccuracy: true, timeout: 6000, maximumAge: 0 };
        geolocator.locate(onGeoSuccess, onGeoError, true, html5Options);
      };
    
      function onGeoSuccess(location) {
        $.cookie('user_postal_code', location.address.postalCode);
        $.cookie('user_latitude', location.coords.latitude);
        $.cookie('user_longitude', location.coords.longitude);
        get_hca_rss();
      }
    
      function onGeoError(error) {
        console.log(error);
      }
    }
    
    get_user_location();
    
    function get_hca_rss() {
      var hcafeed = 'http://hcafeeds.medcity.net/rss/er/rss_feed.xml';
      var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from rss where url="' + hcafeed + '"') + '&format=json&diagnostics=true&callback=?';
      $.getJSON(yql,function(data){
        if(data) {
          get_closest_er(data);
        }
      });
    }
    
    function get_closest_er(data, userLocation) {
      var service = new google.maps.DistanceMatrixService();
      var rows = data.query.results.item;
      var origin = $.cookie('user_latitude') + "," + $.cookie('user_longitude');
    
      $.each(rows,function(e) {
        if(rows[e].address != undefined) {
          var destination = rows[e].address;
          tmp = Number.POSITIVE_INFINITY;
          closestIndex = null;
    
          // Google Distance Matrix API
          var service = new google.maps.DistanceMatrixService();
          service.getDistanceMatrix( {
            origins: [origin],
            destinations: [destination],
            travelMode: google.maps.TravelMode.DRIVING,
            unitSystem: google.maps.UnitSystem.IMPERIAL,
            durationInTraffic: false,
            avoidHighways: false,
            avoidTolls: false,
          }, callback);
    
          // Callback for distance api
          function callback(response, status) {
            if (status != google.maps.DistanceMatrixStatus.OK) {
              alert('Error was: ' + status);
            } else {
              var distance = response.rows[0].elements[0].distance.value;
              if (distance < tmp) {
                tmp = distance;
                $.cookie('closestIndex',e);
                $.cookie('closestDistance',response.rows[0].elements[0].distance.text);
              }
            }
          }
    
        }
      });
    
      set_closest_er_html(data);
    
    };
    
    function set_closest_er_html(data) {
      var rows = data.query.results.item;
      var hElem = $('#closestER');
      var uZip = $.cookie('user_postal_code');
      var cIdx = $.cookie('closestIndex');
      var cHospital = rows[cIdx];
      var cName = cHospital.comments.replace(" ER Wait Time", "");
      var cDistance = $.cookie('closestDistance').replace(" mi", "");
      var cWaitTime = cHospital.description.replace(" Mins", "");
    
      hElem.html('<h2>Hospital Info:</h2>');
      hElem.append('<div><span>Your Closest ER </span><span>' + uZip + ' Zip Code</span></div>');
      hElem.append('<div><strong>Hospital </strong><span>' + cName + '</span></div>');
      hElem.append('<div><label>Distance: </label><div>' + cDistance + '</div> Miles</div>');
      hElem.append('<div><label>Wait: </label><div>' + cWaitTime + '</div> Minutes</div>');
    }
    
    获取最近的地址:

    function get_user_location() {
      window.onload = function () {
        var html5Options = { enableHighAccuracy: true, timeout: 6000, maximumAge: 0 };
        geolocator.locate(onGeoSuccess, onGeoError, true, html5Options);
      };
    
      function onGeoSuccess(location) {
        $.cookie('user_postal_code', location.address.postalCode);
        $.cookie('user_latitude', location.coords.latitude);
        $.cookie('user_longitude', location.coords.longitude);
        get_hca_rss();
      }
    
      function onGeoError(error) {
        console.log(error);
      }
    }
    
    get_user_location();
    
    function get_hca_rss() {
      var hcafeed = 'http://hcafeeds.medcity.net/rss/er/rss_feed.xml';
      var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from rss where url="' + hcafeed + '"') + '&format=json&diagnostics=true&callback=?';
      $.getJSON(yql,function(data){
        if(data) {
          get_closest_er(data);
        }
      });
    }
    
    function get_closest_er(data, userLocation) {
      var service = new google.maps.DistanceMatrixService();
      var rows = data.query.results.item;
      var origin = $.cookie('user_latitude') + "," + $.cookie('user_longitude');
    
      $.each(rows,function(e) {
        if(rows[e].address != undefined) {
          var destination = rows[e].address;
          tmp = Number.POSITIVE_INFINITY;
          closestIndex = null;
    
          // Google Distance Matrix API
          var service = new google.maps.DistanceMatrixService();
          service.getDistanceMatrix( {
            origins: [origin],
            destinations: [destination],
            travelMode: google.maps.TravelMode.DRIVING,
            unitSystem: google.maps.UnitSystem.IMPERIAL,
            durationInTraffic: false,
            avoidHighways: false,
            avoidTolls: false,
          }, callback);
    
          // Callback for distance api
          function callback(response, status) {
            if (status != google.maps.DistanceMatrixStatus.OK) {
              alert('Error was: ' + status);
            } else {
              var distance = response.rows[0].elements[0].distance.value;
              if (distance < tmp) {
                tmp = distance;
                $.cookie('closestIndex',e);
                $.cookie('closestDistance',response.rows[0].elements[0].distance.text);
              }
            }
          }
    
        }
      });
    
      set_closest_er_html(data);
    
    };
    
    function set_closest_er_html(data) {
      var rows = data.query.results.item;
      var hElem = $('#closestER');
      var uZip = $.cookie('user_postal_code');
      var cIdx = $.cookie('closestIndex');
      var cHospital = rows[cIdx];
      var cName = cHospital.comments.replace(" ER Wait Time", "");
      var cDistance = $.cookie('closestDistance').replace(" mi", "");
      var cWaitTime = cHospital.description.replace(" Mins", "");
    
      hElem.html('<h2>Hospital Info:</h2>');
      hElem.append('<div><span>Your Closest ER </span><span>' + uZip + ' Zip Code</span></div>');
      hElem.append('<div><strong>Hospital </strong><span>' + cName + '</span></div>');
      hElem.append('<div><label>Distance: </label><div>' + cDistance + '</div> Miles</div>');
      hElem.append('<div><label>Wait: </label><div>' + cWaitTime + '</div> Minutes</div>');
    }
    
    函数获取最近者(数据、用户位置){
    var service=new google.maps.DistanceMatrixService();
    变量行=data.query.results.item;
    var origin=$.cookie('user_latitude')+“,”+$.cookie('user_latitude');
    $。每行,函数(e){
    if(行[e]。地址!=未定义){
    var destination=行[e]。地址;
    tmp=正无穷大数;
    closestIndex=null;
    //谷歌距离矩阵API
    var service=new google.maps.DistanceMatrixService();
    服务。getDistanceMatrix({
    来源:[来源],
    目的地:[目的地],
    travelMode:google.maps.travelMode.DRIVING,
    unitSystem:google.maps.unitSystem.IMPERIAL,
    持续时间:假,
    避免:错误,
    避免:错误,
    },回调);
    //远程api的回调
    函数回调(响应、状态){
    if(status!=google.maps.DistanceMatrixStatus.OK){
    警报(“错误为:”+状态);
    }否则{
    var distance=response.rows[0]。元素[0]。distance.value;
    if(距离
    设置该HTML:

    function get_user_location() {
      window.onload = function () {
        var html5Options = { enableHighAccuracy: true, timeout: 6000, maximumAge: 0 };
        geolocator.locate(onGeoSuccess, onGeoError, true, html5Options);
      };
    
      function onGeoSuccess(location) {
        $.cookie('user_postal_code', location.address.postalCode);
        $.cookie('user_latitude', location.coords.latitude);
        $.cookie('user_longitude', location.coords.longitude);
        get_hca_rss();
      }
    
      function onGeoError(error) {
        console.log(error);
      }
    }
    
    get_user_location();
    
    function get_hca_rss() {
      var hcafeed = 'http://hcafeeds.medcity.net/rss/er/rss_feed.xml';
      var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from rss where url="' + hcafeed + '"') + '&format=json&diagnostics=true&callback=?';
      $.getJSON(yql,function(data){
        if(data) {
          get_closest_er(data);
        }
      });
    }
    
    function get_closest_er(data, userLocation) {
      var service = new google.maps.DistanceMatrixService();
      var rows = data.query.results.item;
      var origin = $.cookie('user_latitude') + "," + $.cookie('user_longitude');
    
      $.each(rows,function(e) {
        if(rows[e].address != undefined) {
          var destination = rows[e].address;
          tmp = Number.POSITIVE_INFINITY;
          closestIndex = null;
    
          // Google Distance Matrix API
          var service = new google.maps.DistanceMatrixService();
          service.getDistanceMatrix( {
            origins: [origin],
            destinations: [destination],
            travelMode: google.maps.TravelMode.DRIVING,
            unitSystem: google.maps.UnitSystem.IMPERIAL,
            durationInTraffic: false,
            avoidHighways: false,
            avoidTolls: false,
          }, callback);
    
          // Callback for distance api
          function callback(response, status) {
            if (status != google.maps.DistanceMatrixStatus.OK) {
              alert('Error was: ' + status);
            } else {
              var distance = response.rows[0].elements[0].distance.value;
              if (distance < tmp) {
                tmp = distance;
                $.cookie('closestIndex',e);
                $.cookie('closestDistance',response.rows[0].elements[0].distance.text);
              }
            }
          }
    
        }
      });
    
      set_closest_er_html(data);
    
    };
    
    function set_closest_er_html(data) {
      var rows = data.query.results.item;
      var hElem = $('#closestER');
      var uZip = $.cookie('user_postal_code');
      var cIdx = $.cookie('closestIndex');
      var cHospital = rows[cIdx];
      var cName = cHospital.comments.replace(" ER Wait Time", "");
      var cDistance = $.cookie('closestDistance').replace(" mi", "");
      var cWaitTime = cHospital.description.replace(" Mins", "");
    
      hElem.html('<h2>Hospital Info:</h2>');
      hElem.append('<div><span>Your Closest ER </span><span>' + uZip + ' Zip Code</span></div>');
      hElem.append('<div><strong>Hospital </strong><span>' + cName + '</span></div>');
      hElem.append('<div><label>Distance: </label><div>' + cDistance + '</div> Miles</div>');
      hElem.append('<div><label>Wait: </label><div>' + cWaitTime + '</div> Minutes</div>');
    }
    
    函数集\u最近的\u er\u html(数据){
    变量行=data.query.results.item;
    var hElem=$(“#closestER”);
    var uZip=$.cookie('user_postal_code');
    var cIdx=$.cookie('closestinex');
    var cHospital=行[cIdx];
    var cName=cHospital.comments.replace(“ER等待时间”);
    var cDistance=$.cookie('closestDistance')。替换('mi',');
    var cWaitTime=cHospital.description.replace(“分钟”,“分钟”);
    html('医院信息:');
    hElem.append('您最近的ER'+uZip+'邮政编码');
    hElem.append(“医院”“+cName+”);
    hElem.append('Distance:'+cDistance+'Miles');
    hElem.append('Wait:'+cWaitTime+'Minutes');
    }
    
    我想问题是。。。如何等到循环中的最后一个callback()函数完成并设置了最近的地址cookie之后,再将其移动到set_closest_er_html函数

    提前谢谢