How to get the nearby cities of a city(geonameid) in python?

14k Views Asked by At

Given a radius of 100 KM from the base city(geonameid) i need to find the nearby cities.

My script is in python. Is there any API to find it out ?

Thanks

3

There are 3 best solutions below

7
On

If you have a database of cities, have a look at this example which shows how to build SQL queries for that particular task.

SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < 25 ORDER BY distance LIMIT 0 , 20;

So if you have your own database or cities or you are willing to create a database which has locations and coordinates of certain cities (might be available somewhere on the internet) then this solution will work for you.

Alternatively if you don't have a database and you want to use a API like Google Maps, have a look at The Google Geacoding API and Reverse Geocoding in particular. A request like:

http://maps.googleapis.com/maps/api/geocode/json?latlng=40.7,-73.9&sensor=false

Will give you possible addresses for the longitude and latitude you've provided it with.

Unfortunately the Google Places API (nearby places) only works for things like restaurants, shops, bars etc..

0
On

Since you're using the Geonames webservice, it looks like there's functionality built in to it to find nearby place names:

from: http://www.geonames.org/export/web-services.html

Find nearby populated place / reverse geocoding

Webservice Type : REST Url : api.geonames.org/findNearbyPlaceName? Parameters : lat,lng, lang: language of returned 'name' element (the pseudo language code 'local' will return it in local language), radius: radius in km (optional), maxRows: max number of rows (default 10) style: SHORT,MEDIUM,LONG,FULL (default = MEDIUM), verbosity of returned xml document Result : returns the closest populated place for the lat/lng query as xml document. The unit of the distance element is 'km'. Example: http://api.geonames.org/findNearbyPlaceName?lat=47.3&lng=9&username=demo

This service is also available in JSON format : http://api.geonames.org/findNearbyPlaceNameJSON?lat=47.3&lng=9&username=demo

2
On

I'm afraid neither the Geocoding API nor the Places API would help you the way you want.

Reverse geocoding will give you the city for a given latlng, but not the ones around that one. Places API not even that. These APIs are for different uses, but I guess you're not interested in that now.

Unless you find an API that does what you want, you'd need to build your own database and run queries like the one MMM points out. To build your database, you can use the Populated Places dataset from Natural Earth's 1:10m Cultural Vectors. You'd need some sort of GIS software to process it and extract from those populated places you'd call cities though.