J.Zil
J.Zil

Reputation: 2449

Modifying JSON Ajax Request for Geonames

I have the code I am after from an example site but I was wondering if anyone could tell me how to modify the code below to only return results from the USA.

This is the code I have so far:

  $(function() {
    function log( message ) {
      $( "<div>" ).text( message ).prependTo( "#log" );
      $( "#log" ).scrollTop( 0 );
    }

    $( "#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 ) {
            response( $.map( data.geonames, function( item ) {
              return {
                label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
                value: item.name
              }
            }));
          }
        });
      },
      minLength: 2,
      select: function( event, ui ) {
        log( ui.item ?
          "Selected: " + ui.item.label :
          "Nothing selected, input was " + this.value);
      },
      open: function() {
        $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
      },
      close: function() {
        $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
      }
    });
  });

Apparently you can request JSON like this:

http://ws.geonames.org/searchJSON?name_startsWith=Chic&country=US

So my question is, how do I modify the code above to include "&country=US" onto the request. I've tried a few things but it breaks the request entirely.

Upvotes: 0

Views: 1115

Answers (1)

Renato Todorov
Renato Todorov

Reputation: 560

Put the country parameter on the data variable:

      data: {
        featureClass: "P",
        style: "full",
        maxRows: 12,
        name_startsWith: request.term,
        country: "US"
      },

Simple like that!

The data variable in this case is used to build the querystring of the Ajax request.

Upvotes: 2

Related Questions