等待地理编码器功能完成执行然后继续

时间:2014-09-03 19:34:25

标签: javascript jquery google-maps-api-3 callback steroids

我正在使用Appgyver Steroids框架开发一个混合应用程序,我正在尝试实现一个'检测用户位置'功能,用户可以切换一个开关来选择他们是否喜欢他们的位置(长& lat) )自动检测,或者他们可以将他们的位置(城市,邮政编码或县)输入文本框,并根据他们的输入/选择点击按钮计算经度和纬度。

当用户将开关切换到“开”位置并点按提交时,navigator.geolocation.getCurrentPosition会被触发并调用相关函数,然后将其当前经度和纬度存储在localStorage中。这非常有效。

然而,当用户将开关切换到“关闭”位置时,我的地理编码功能[manualGeoCode()]将其位置编码为long和lat似乎不会及时触发,因此警报会在之后直接触发在有时间实际设置localStorage值之前调用该地理编码函数。我已经研究过使用回调,我已经研究过使用jQuery deferred方法,这两种方法都没有成功使用。任何帮助都将受到大力赞赏!谢谢你的阅读。

这是我的代码:

    <h3>Your location</h3>
      <ul class="list">
        <li class="item item-toggle">Use my current location
          <label class="toggle toggle-balanced">
            <input type="checkbox" id="myLocationToggle" checked="true">
            <div class="track">
              <div class="handle"></div>
            </div>
          </label>
        </li>
        <li class="item item-input">
          <input type="text" id="userLocation" placeholder="City, town or postcode" disabled="true">
        </li>
      </ul>

<button class="button button-balanced" id="getLongLat">Get long/lat</button>


$(function(){
  AutoGeoCode(); 
});

function AutoGeoCode(){
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(onSuccess, onError);
  }
}

$('#getLongLat').on('click',function(){
  localStorage.latToPost = '';
  localStorage.lngToPost = '';

  if(localStorage.userLatAutoDetected != '0' || localStorage.userLngAutoDetected != '0'){
    localStorage.latToPost = localStorage.userLatAutoDetected;
    localStorage.lngToPost = localStorage.userLngAutoDetected;
  }
  else{
    manuallyGeoCode(); // this doesn't finish in time so it jumps to the alert below and shows empty values.
  }

  alert('geodata is: {'+localStorage.latToPost+'}, {'+localStorage.lngToPost+'}');

});

$('#myLocationToggle').on('click',function(){
  if($(this).is(':checked')){
    $('#userLocation').val('').prop('disabled',true);
    AutoGeoCode();
  }
  else{
    $('#userLocation').val('').prop('disabled',false);
    localStorage.userLatAutoDetected = '0';
    localStorage.userLngAutoDetected = '0';
  }
});

function onSuccess(position){
    localStorage.userLatAutoDetected = position.coords.latitude;
    localStorage.userLngAutoDetected = position.coords.longitude;
}

function onError(error){
  alert('current location could not be auto detected. Error: ' + error);
}

//Autocomplete location search box
function initialize() {
  var address = (document.getElementById('userLocation'));
  var autocomplete = new google.maps.places.Autocomplete(address);
      autocomplete.setTypes(['geocode']);
  google.maps.event.addListener(autocomplete, 'place_changed', function() {
  var place = autocomplete.getPlace();
    if (!place.geometry) {
      return;
    }
  var address = '';
    if (place.address_components) {
      address = [
                  (place.address_components[0] && place.address_components[0].short_name || ''),
                  (place.address_components[1] && place.address_components[1].short_name || ''),
                  (place.address_components[2] && place.address_components[2].short_name || '')
                ].join(' ');
    }
  }); //end google.maps.event
}

function manuallyGeoCode(){
  var address = $('#userLocation').val();
  geocoder = new google.maps.Geocoder();
    geocoder.geocode({'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        localStorage.latToPost = results[0].geometry.location.lat();
        localStorage.lngToPost = results[0].geometry.location.lng();
      }
      else {
        alert('Your location could not be geocoded.');
      }
    });
}

google.maps.event.addDomListener(window, 'load', initialize);

1 个答案:

答案 0 :(得分:0)

请找出句柄和手动地理编码功能的区别

$('#getLongLat').on('click',function(){
  localStorage.latToPost = '';
  localStorage.lngToPost = '';

  if(localStorage.userLatAutoDetected != '0' || localStorage.userLngAutoDetected != '0'){
    localStorage.latToPost = localStorage.userLatAutoDetected;
    localStorage.lngToPost = localStorage.userLngAutoDetected;
    alert('geodata is: {'+localStorage.latToPost+'}, {'+localStorage.lngToPost+'}');
  }else{
    manuallyGeoCode(function(){
      alert('geodata is: {'+localStorage.latToPost+'},{'+localStorage.lngToPost+'}');

    }); // this doesn't finish in time so it jumps to the alert below and shows empty values.
  }
});

function manuallyGeoCode(cb){
  var address = $('#userLocation').val();
  geocoder = new google.maps.Geocoder();
    geocoder.geocode({'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        localStorage.latToPost = results[0].geometry.location.lat();
        localStorage.lngToPost = results[0].geometry.location.lng();
        cb();
      }
      else {
        alert('Your location could not be geocoded.');
      }
    });
}