【发布时间】:2013-11-24 00:00:13
【问题描述】:
我需要将经度和纬度坐标转换为国家或城市,python中有这样的例子吗?
提前致谢!
【问题讨论】:
标签: python python-2.7 python-3.x
我需要将经度和纬度坐标转换为国家或城市,python中有这样的例子吗?
提前致谢!
【问题讨论】:
标签: python python-2.7 python-3.x
我使用 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')
【讨论】:
from urllib.request import urlopen
url = "https://maps.googleapis.com/maps/api/geocode/json?key=YourKey&"(注意:必须是https,不是http)
Google 已经移除了对其 API 的无密钥访问。前往谷歌并注册一个密钥,您每天可以获得约 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))
【讨论】:
这称为反向地理编码。我可以在 Python 中找到一个专注于此的库:https://github.com/thampiman/reverse-geocoder
一些与其他想法相关的问题:
【讨论】:
一般来说,Google API 是最好的方法。它不适合我的情况,因为我必须处理大量条目并且 api 很慢。
我编写了一个小版本,它做同样的事情,但首先下载一个巨大的几何图形并计算机器上的国家/地区。
import requests
from shapely.geometry import mapping, shape
from shapely.prepared import prep
from shapely.geometry import Point
data = requests.get("https://raw.githubusercontent.com/datasets/geo-countries/master/data/countries.geojson").json()
countries = {}
for feature in data["features"]:
geom = feature["geometry"]
country = feature["properties"]["ADMIN"]
countries[country] = prep(shape(geom))
print(len(countries))
def get_country(lon, lat):
point = Point(lon, lat)
for country, geom in countries.iteritems():
if geom.contains(point):
return country
return "unknown"
print(get_country(10.0, 47.0))
# Austria
【讨论】:
# 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)
【讨论】: