jQuery snippet: Autocomplete city based on zip code

Just added this to my project on the registration page, after reading the Developerworks article Cross-domain communications with JSONP:

$("#zipCode").blur(function() {
	var city = $("#city");
	if (!city.val() && $(this).valid()) {
		$.getJSON("http://www.geonames.org/postalCodeLookupJSON?&country=DE&callback=?", {postalcode: this.value }, function(response) {
			if (!city.val() && response && response.postalcodes.length && response.postalcodes[0].placeName) {

Upon blur of the zip input, it checks if city is still empty and the entered zip is valid (using the validation plugin, you could just as well just check for this.value), then uses $.getJSON to request JSONP from the geonames.org webservice. The country parameter is hardcoded to “DE” in this case, while the postalcode parameter is passed as the second argument, taking the entered zip value.

When the response returns, the city field is checked again, to avoid overwriting any user input when dealing with high latency, and the response is checked for the property to insert, to avoid any “property xxx is undefined” JavaScript errors when something goes wrong. In this case its preferred to fail silently, as the feature is nothing more then a helper anyway.

Finally, the city field is updated with the placeName attribute. The webservice also provides “adminName1” and “adminCode1” properties. Here is a sample response for my location (I added some whitespace):

?({"postalcodes":[{"postalcode":"51065", "adminCode1":"NW", "countryCode":"DE", "lng":7.005625, "placeName":"Köln", "lat":50.9578, "adminName1":"Nordrhein-Westfalen"}]});


No more comments.
  1. Super, das ist doch mal eine richtig nützliche Sache!

  2. “… to request JSONP from the geonames.com webservice”

    It’s geonames.org in your code.

  3. @Dean: Fixed.

  4. Its ok to just grab data from geonames??.. I want to use this in my website

  5. @Felipe: Check the geonames.org website for licensing details.

  6. @Jorn Thanks !

  7. Tim

    @Jörn: This is great. Are you planning to add support for jsonp calls in your Autocomplete plugin as an option? I’m trying to get through your code and add support, but I’m getting a bit lost.

  8. @Tim: As jQuery handles JSONP already, there is not much to add. Basically you’d just specify a URL outside the current domain, include the question mark placeholder, then parse the result (same for JSON).

  9. @Jörn — this is an awesome code snippet! I spent three days adding a MySQL zipcodes table and writing this same functionality in plain old javascript to accomplish what you’ve done here in 10 lines of jQuery. I hadn’t ever heard of the geonames.org web service. Good job and thanks!

  10. Anton Andreasson

    Yeeha, you just made my day! Have been pulling my hairs over this one today, turns out I missed the callback part (did read about it, but didn’t know GeoNames supported it)

    Thanks a lot once again!