开发者

JQuery: How to AutoComplete "City, State"?

开发者 https://www.devze.com 2022-12-25 15:52 出处:网络
Question: How can you use the JQuery Auto-Completion plugin to suggest a location (开发者_如何学C\"City, State\") for an input field?

Question: How can you use the JQuery Auto-Completion plugin to suggest a location (开发者_如何学C"City, State") for an input field?

Meaning, someone wants to type in "Chicago, IL" ... so they begin typing "Chi" and it auto-suggestions "Chicago, IL".

My biggest hurdles is finding a service that I can query to find out all US city+state names.

I essentially want to do what the StackOverflow "Tags" input form works but form "City, State" auto completion.


There's a group called GeoNames that offers both downloadable databases and free webservices to obtain this type of data. For example, the search

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

will return a bunch of JSON that includes Chicago, IL (JSON properties include, among others, "name":"Chicago" and "adminCode1":"IL").

As it happens, the jQuery UI folks used this datasource for a demo of autocomplete. (Thanks NickT for the link).


You either need to make an ajax call to the server whenever a key is pressed to update the "auto complete" drop down, or include an array of all the possible "city-state" strings and filter them when a key is pressed.


@Teleport offers an API to search cities by name, e.g.: https://api.teleport.org/api/cities/?search=San,%20United%20States%20of%20America returns San Antonio, San Diego, San Jose and San Francisco. You can also pass state, e.g. https://api.teleport.org/api/cities/?search=San,%20Tex,%20United%20States%20of%20America only returns San Antonio. And you can also search by aiport codes (e.g. SFO) and other "aliases".

There's also an autocomplete widget for this API available at https://github.com/teleport/autocomplete

Disclosure: I work for Teleport.

EDIT: Added "of America" suffix in the "United States of America" search term, as some other countries (Brazil, Venezuela) have name forms that match "United States".

0

精彩评论

暂无评论...
验证码 换一张
取 消