Google Maps API Tutorial© 2006, 2007 Mike Williams |
Geocoding with error handlingThe mechanics of geocoding without error handling are well explained in the official documentation but the examples shown there do not include error handling.Geocoding requests can fail for a variety of reasons, so it's a good idea to check for successful completion before attempting to plot markers using the returned information. It's also helpful to display the failure reason to your users, where possible, otherwise your users might waste their time doing things like trying to guess the correct spelling of "Sauchiehall Street, Glasgow, UK", when the problem isn't the spelling but the fact that the API doesn't support UK geocoding for legal or contractual reasons. What you can do is to set up an array like this var reasons=[];
reasons[G_GEO_SUCCESS] = "Success";
reasons[G_GEO_MISSING_ADDRESS] = "Missing Address: The address was either missing or had
no value.";
reasons[G_GEO_UNKNOWN_ADDRESS] = "Unknown Address: No corresponding geographic location
could be found for the specified address.";
reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address: The geocode for the given address
cannot be returned due to legal or contractual reasons.";
reasons[G_GEO_BAD_KEY] = "Bad Key: The API key is either invalid or does not match
the domain for which it was given";
reasons[G_GEO_TOO_MANY_QUERIES] = "Too Many Queries: The daily geocoding quota for this site
has been exceeded.";
reasons[G_GEO_SERVER_ERROR] = "Server error: The geocoding request could not be
successfully processed.";
and display the text associated with the reply.Status.code.When using geocoder.getLocations(), accessing the status code is straight forward, see this example When using geocoder.getLatLng(), the status code is not returned directly. You can check to see if the returned point is null to detect whether an error has occurred, but getLatLng() doesn't provide a reason. There are two possible strategies for obtaining the status code - you could follow a failed getLatLng() with a getLocations() request and examine its status code (in which case there is a possibility that the status code might be different, in particular, if there was a server timeout on the first attempt, the second attempt might even succeed). Alternatively, you could look in the geocoder cache, as in this example. If you're using the default cache, then only the codes for success, unknown address and unavailable address are cached, because the API uses a GFactualGeocodeCache() by default. Using a GGeocodeCache() instead of a GFactualGeocodeCache() will cause more types of failure to be cached, but not all of them.
Potential Pitfalls
|