Search code examples
jqueryautocompletegeonames

jQuery .autocomplete() with postal code and cityname in one input field


Hi I'm trying to build a field with autocomplete for Geo-Data (geonames.org API).

I figured out how to solve input for postal code and for searching by cityname. I want to do it that it can include both. If I search with a cityname it shuold also display all possible zip-codes of the recent cities.

I hope you could help me or give me a hint.

My code is:

$(function () {
    function log(message) {
        $("#log").text(message);
        $("#log").scrollTop(0);
    }

    $("#city").autocomplete({
        source: function (request, response) {
            $.ajax({
                url: "http://api.geonames.org/postalCodeSearchJSON",
                dataType: "jsonp",
                data: {
                    postalcode_startsWith: request.term,
                    maxRows: 10,
                    country: "DE",
                    username: "username"
                },
                success: function (data) {
                    response($.map(data.postalCodes, function (item) {
                        return {
                            label: item.postalCode + "-" + item.placeName,
                            value: item.postalCode + "-" + item.placeName
                        }
                    }));
                }    
            });

        },
        minLength: 2,
        select: function (event, ui) {
            log(ui.item ?
              "Sie haben: " + ui.item.label + " ausgewählt ":
              "Nichts ausgewählt " + this.value);
        }
    });
});

Solution

  • Update:

    It was easy as usual. There's no need for special code, just change the data: into following

                data: {
                    featureClass: "P",
                    maxRows: 10,
                    country: "DE",
                    placename_startsWith: request.term,
                    username: "yourusername"
                }