Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 599
Pratik Patel Avatar asked Feb 16 '12 07:02

Pratik Patel


3 Answers

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".

like image 104
Chris Taylor Avatar answered Nov 19 '22 11:11

Chris Taylor


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.

like image 31
Andreas Dolk Avatar answered Nov 19 '22 10:11

Andreas Dolk


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.

like image 4
belgther Avatar answered Nov 19 '22 10:11

belgther