如何阻止谷歌地图地理编码在N秒后返回

时间:2015-08-22 19:42:05

标签: javascript jquery google-maps google-maps-api-3 google-geocoder

我正在调用google.maps.geocoder()来获取一些坐标。我想设置一个计时器,在3秒后停止地理编码调用,但我不知道该怎么做?

这是我的代码。

ViewPager mViewPager ;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setOnPageChangeListener(new OnPageChangeListener(){
    ...
    @Override
    public void onPageSelected(int position) {
    switch(position){
    case 0 :
      // Do the changes for the 1st page here
    break;
    case 1 :
      // Do the changes for the 2nd page here
    break;
    }   

    }
    ...

   });
}

2 个答案:

答案 0 :(得分:1)

Geocoder()对象似乎没有公开超时方法。 您可以使用对其URL的jquery ajax调用直接调用其地理编码服务: https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=API_KEY

从ajax调用服务,这将使您更好地控制通信。见http://api.jquery.com/jquery.ajax/

答案 1 :(得分:1)

如果地理编码器在3秒内未返回结果(通过或失败),则表示出错。只有在地理编码成功的情况下才提交表单,否则不要提交表单,并且可能让用户知道出现了问题。

// here I want to stop any calls coming back from .geocode if a 
//timer times out after say 3-5 seconds.
var navbarGeocoder = new google.maps.Geocoder();
navbarGeocoder.geocode({ // call to geocode
  'address': navbarInput.value
}, function(results, status) {
  if (status == google.maps.GeocoderStatus.OK) {

    $("#latitude").val(results[0].geometry.location.G);
    $("#longitude").val(results[0].geometry.location.K);
    $("#mapType").val(results[0].types[0]);
    // only submit the form it the geocoder succeeded
    $('form')[0].submit();
  } else {
    // let the user know the request failed
    alert("geocoder failed, status = "+status);
  }

});