Serge's World

Blogging about software development, astronomy, genealogy and more.

A Simple City Autocomplete Field

I was playing around with some code recently, and came across a very easy way to create a city lookup field using jQuery’s UI components and a very useful webservice provided by Geonames.

How the autocomplete functionality in jQuery works, is by wrapping the functionality around a standard html text input field, populating a dropdown list of values from an ajax call to a webservice, in this case, the Geonames webservice.

When supplied with a partial city name, the GeoNames webservice returns back a list of information for cities matching the partial city name supplied, allowing you to display, and keep track of, the country, province, full city name, and a host of other info. Full documentation is provided on the GeoNames site.

$( "#city" ).autocomplete({
  source: function( request, response ) {
    $.ajax({
      url: "http://ws.geonames.org/searchJSON",
      dataType: "jsonp",
      data: {
        featureClass: "P",
        style: "full",
        maxRows: 12,
        name_startsWith: request.term
      },
      success: function( data ) {
        //Display city name, state name, country name
        response( $.map( data.geonames, function( item ) {
          return {
            label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
            value: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName
          }
        }));
      }
    });
  },
  minLength: 2,
  select: function( event, ui ) {
    $('#city').val(ui.item.value);
    return false;
  }
});

Tag Cloud

Algorithms (3) Android (10) Astronomy (25) Audio (1) Audiobooks (1) Barcodes (9) C# (69) Css (1) Deep sky (6) Esoteric languages (3) Family (3) Fractals (10) Gaming (1) Genealogy (14) General (2) Geodesy (3) Google (1) Graphics (3) Hubble (2) Humour (1) Image processing (23) Java (8) Javascript (5) jQuery (3) Jupiter (3) Maths (22) Moon (5) Music (4) Pets (5) Programming (88) Saturn (1) Science (1) Spitzer (4) Sun (4) Tutorials (68) Unity (3) Web (9) Whisky (13) Windows (1) Xamarin (2)