god*_*lla 22 python python-2.7 python-3.x
我需要将经度和纬度坐标转换为国家或城市,在python中是否有这样的例子?
提前致谢!
Hol*_*rel 27
我使用谷歌的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))
Run Code Online (Sandbox Code Playgroud)
输出:
(u'Hartfield', u'United Kingdom')
(u'Edenbridge', u'United Kingdom')
(u'Sevenoaks', u'United Kingdom')
Run Code Online (Sandbox Code Playgroud)
通常,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
Run Code Online (Sandbox Code Playgroud)
小智 6
从那以后,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))
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
21474 次 |
最近记录: |