简体   繁体   中英

How to find Country name from city name in Java?

I want to fetch Twitter user's country name.

For that I got the location from the <location> tag in which some users wrote their country's name, some wrote their city's name and some also wrote their state's name.

I want to get the country name for all users. How can I do this?

One way would be to use the Google Maps API (though it might be overkill). For example, suppose someone has listed their country as "Jakarta" (actually a city in Indonesia). Then you would submit the following Maps API request:

http://maps.googleapis.com/maps/api/geocode/json?address=Jakarta&sensor=false

which returns a JSON object. You then parse that with your favorite JSON parser, and extract the "long_name" field of the "address components" field, with the type "country". In this case, that is "Indonesia".

Try to find an resource file or database with a convenient license (like GeoWorldMap from here ). You won't get accurate infos from twitter users anyway, and what they write in their profile might be plain wrong. So I'd use a static resource and decode as many locations as possible.

You can use Google Maps' autocomplete script to get possible countries for a city. It works like this: When you type "New York", it suggests you "New York, USA". But remember, you can't always get the country name from city name: There is a Berlin in Germany and in Connecticut, too.

You could use geo tables in YQL: http://developer.yahoo.com/yql/console/#h=select%20*%20from%20geo.places%20where%20text%3D%22jakarta%22

Example query: select * from geo.places where text="jakarta"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM