chuckd
chuckd

Reputation: 14550

How to stop google maps geocode from returning after N seconds

I'm making a call to google.maps.geocoder() to get some coordinates. I'm want to set a timer to stop the geocode call after 3 seconds but I'm not sure how to do this?

Here is my code.

// 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]);
  }
  $('form')[0].submit();
});

Upvotes: 0

Views: 387

Answers (2)

geocodezip
geocodezip

Reputation: 161334

If the geocoder doesn't return a result (pass or fail) within 3 seconds, something is wrong. Only submit the form if the geocode succeeds, otherwise don't submit the form and potentially let the user know something went wrong.

// 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);
  }

});

Upvotes: 1

William Walseth
William Walseth

Reputation: 2923

It doesn't seem like the Geocoder() object exposes a timeout method. You can call their geocoding service directly using a jquery ajax call to their URL: https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=API_KEY

Calling the service from ajax, which will give you more control over the communication. See http://api.jquery.com/jquery.ajax/

Upvotes: 1

Related Questions