This is something I wanted to do for a long time : to have the city field autofilled in a Flex form when the zip code and the country are given. This, using a free HTTPService or WebService.
I started the task this week and it’s now done using the services of GeoNames.org.
GeoNames provides millions of geographical data, freely, through webservices or downloadable databases.
This is a very precious place where you can find everything you want related to geographical data.
By downloading their databases, you can build and then manage your own one, for your own purpose but this requires maintenance, regular updates (that can be automated ok) but this is not my requirement, or very partially actually: I just wanted to auto fill my little city field in my little Flex form (an AIR form actually, containing client information).
So, how to do this ?
Very easily using the HTTPService class of the Flex framework.
To use GeoNames services, you will need the URL of the service and parameters. Everything can be found on their documentation page.
In our case, the URL is http://ws.geonames.org/postalCodeSearch? and main parameters: postalcode and country as strings. You define the HTTPService as follows:
1 2 3 4 5
<mx:HTTPService id="cityService" url="http://ws.geonames.org/postalCodeSearch?" resultFormat="object" result="cityResultHandler(event);" fault="hsFaultHandler(event);"/>
1 2 3 4
The send instruction sends the request and you will get the following kind of result (using maxRows=1 and style=”short” as additional parameters):
1 2 3 4 5 6 7 8 9 10
<geonames> <totalresultscount>1</totalresultscount> <geocode> <postalcode>75009</postalcode> <name>Paris 09</name> <countrycode>FR</countrycode> <lat>48.841069</lat> <lng>2.387908</lng> </geocode> </geonames>
To catch and deal with this result, you use the listener cityResultHandler attached to the HTTPService.
You can find below a very simple sample form (just play with the zip and the country fields):
and you can download the corresponding code here:
Downloaded a total of 499 times
I hope this will help you when you need this kind of stuff in your projet.