我需要将经度和纬度坐标转换为国家或城市,在python中有这样的例子吗?
提前感谢!
答案 0 :(得分:25)
我使用Google的API。
from urllib2 import urlopen
import json
def getplace(lat, lon):
url = "http://maps.googleapis.com/maps/api/geocode/json?"
url += "latlng=%s,%s&sensor=false" % (lat, lon)
v = urlopen(url).read()
j = json.loads(v)
components = j['results'][0]['address_components']
country = town = None
for c in components:
if "country" in c['types']:
country = c['long_name']
if "postal_town" in c['types']:
town = c['long_name']
return town, country
print(getplace(51.1, 0.1))
print(getplace(51.2, 0.1))
print(getplace(51.3, 0.1))
<强>输出:强>
(u'Hartfield', u'United Kingdom')
(u'Edenbridge', u'United Kingdom')
(u'Sevenoaks', u'United Kingdom')
答案 1 :(得分:5)
此后,Google已弃用了对其API的无密钥访问权限。前往Google并注册密钥,您每天可获得约1,000个免费查询。接受的答案中的代码应按以下方式进行修改(无法添加评论,代表人数不足)。
from urllib.request import urlopen
import json
def getplace(lat, lon):
key = "yourkeyhere"
url = "https://maps.googleapis.com/maps/api/geocode/json?"
url += "latlng=%s,%s&sensor=false&key=%s" % (lat, lon, key)
v = urlopen(url).read()
j = json.loads(v)
components = j['results'][0]['address_components']
country = town = None
for c in components:
if "country" in c['types']:
country = c['long_name']
if "postal_town" in c['types']:
town = c['long_name']
return town, country
print(getplace(51.1, 0.1))
print(getplace(51.2, 0.1))
print(getplace(51.3, 0.1))
答案 2 :(得分:4)
这称为反向地理编码。我可以在Python中找到一个专注于此的库:https://github.com/thampiman/reverse-geocoder
与其他想法相关的一些问题:
答案 3 :(得分:4)
一般来说,Google API是最好的方法。它不适合我的情况,因为我必须处理很多条目,api很慢。
我编写了一个相同的小版本,但首先下载了一个巨大的几何图形并计算机器上的国家/地区。
mysqli_query
答案 4 :(得分:0)
# Python3 program for reverse geocoding.
# importing necessary libraries
import reverse_geocoder as rg
from pandas import DataFrame
import pandas as pd
def reverseGeocode(coordinates):
result = rg.search(coordinates)
return result
# Coorinates tuple.Can contain more than one pair.
if __name__ == "__main__":
result = []
path = "CSV_NAME.CSV"
df = pd.read_csv(path, error_bad_lines=False)
for i in range(0, len(df)):
coordinates =(df["latitude"], df["longitude"])
result.append(reverseGeocode(coordinates))
print(result)