Search code examples
jqueryjsonjquery-mobilejsonpgeonames

list Geonames WS results with jQuery mobile (autocomplete)


Does anybody have some example or tutorial about how to use the autocomplete function with JSONP call to Geonames WS with jQuery mobile?

The target should be something like http://jqueryui.com/demos/autocomplete/#remote-jsonp but, instead of the dropdown menu I'd like to get a formatted list (clickable).

I found that example http://www.raymondcamden.com/index.cfm/2012/3/27/Example-of-Autocomplete-in-jQuery-Mobile but as it doesn't use Geonames, it is not so useful for me.


Solution

  • Here the code that I used... you have to add only the href tag with your own code:

            $( document ).on( "pageinit", "#myPage", function() {
            $( "#autocomplete" ).on( "listviewbeforefilter", function ( e, data ) {
                var $ul = $( this ),
                    $input = $( data.input ),
                    value = $input.val(),
                    html = "";
                $ul.html( "" );
                if ( value && value.length > 2 ) {
                    $ul.html( "<li><div class='ui-loader'><span class='ui-icon ui-icon-loading'></span></div></li>" );
                    $ul.listview( "refresh" );
                    $.ajax({
                        url: "http://ws.geonames.org/searchJSON",
                        dataType: "jsonp",
                        crossDomain: true,
                        data: {
                            featureClass: "P",
                            style: "full",
                            maxRows: 12,
                            lang: "it",
                            name_startsWith: $input.val()
                        }
                    })
                    .then( function ( response ) {
                        $.each( response.geonames, function ( i, val ) {
                            html += "<li>" + val.name + (val.adminName1 ? ", " + val.adminName1 : "") + ", " + val.countryName + "</li>";
                        });
                        $ul.html( html );
                        $ul.listview( "refresh" );
                        $ul.trigger( "updatelayout");
                    });
                }
            });
        });