Google Maps API Tutorial© 2006, 2007, 2008, 2009 Mike Williams |
Translate this page: |
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", if the problem isn't the spelling but the fact that you've used up youir geocoding quota already. 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. You could follow a failed getLatLng() with a getLocations() request and examine its status code. 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. I recommend avoiding geocoder.getLatLng(). It might seem to make the coding easier, but the lack of error handling makes things more difficult in the long run. Fitting the zoomThe geocoder now returns an ExtendedData section which gives details of a Lat/Lon box that can be used to zoom the map appropriately. Here's an example.In that example, if you search for "France" you get zoom level 6. If you search for "123 Avenue des Champs-Elysees, Paris, France" you get zoom level 16. Note that the Lat/Lng box isn't a perfect fit for the target location. It's just there to provide sensible zooming. Potential Pitfalls
|