为城市或国家查找经纬度对
我想在Python中使用Twitter的API,对于流式API,我需要知道如何找到一个城市、国家或任何地点的经纬度对。
有没有办法在Python中找到这个对,或者有没有一个文件包含城市、国家等的经纬度对?
我需要一对经纬度,也就是两个经度和两个纬度。一个是这个地点的东北方向,另一个是西南方向(假设这个城市可以用一个矩形来表示)。
2 个回答
0
快速查了一下谷歌,发现了这个链接:http://www.kindle-maps.com/blog/csv-location-of-all-the-cities-in-the-world.html
把这个CSV文件读到内存里应该很简单。
另外,既然你已经在线了,可以使用谷歌地图或者其他的API来获取这些信息。
1
这里介绍一个非常有用的工具,叫做BeautifulSoup。
代码如下:
import re
import urllib2
# Import Custom libraries
from BeautifulSoup import BeautifulSoup, BeautifulStoneSoup
def render_google_uri(idict):
'''
Render the appropriate Google Map Api request uri
'''
base_url = "http://maps.googleapis.com/maps/api/geocode/xml?"
options = [(key,re.sub("\s+", "+", value)) for (key, value) in idict.items()]
options = map(lambda x: "=".join(x), options)
options = "&".join(options)
url = base_url + options
return url
def get_street_position(*args):
'''
Longitude and Latitude from Street Address
'''
def is_result(itag):
if itag.name == "result":
if itag.type.text == "locality":
return True
return False
ret_list = []
for address in args:
google_api_dict = \
{
"address" : address,
"sensor" : "false",
}
request_uri = render_google_uri(google_api_dict)
request = urllib2.Request(request_uri, None, {})
try:
response = urllib2.urlopen(request)
the_page = response.read()
except Exception:
the_page = ""
if the_page:
pool = BeautifulStoneSoup(the_page)
result = pool.find(is_result)
if result:
bounds = result.find("bounds")
if bounds:
cur_dict = \
{
"Address" : address,
"Google Address" : result.formatted_address.text,
"Bounds" : \
{
"SW" :
{
"Longitude" : bounds.southwest.lng.text,
"Latitude" : bounds.southwest.lat.text
},
"NE" :
{
"Longitude" : bounds.northeast.lng.text,
"Latitude" : bounds.northeast.lat.text
}
}
}
ret_list += [cur_dict]
return ret_list
if __name__ == "__main__":
print get_street_position("Sydney", "Marrakech")