如何转换经度和纬度到国家或城市?

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)

  • 对于Python> 3.5,使用`来自urllib.request import urlopen` (4认同)
  • 现在,Google Map API需要密钥才能使用。我需要注册一个计费帐户。获取密钥后,我需要将第一个URL更改为`url =“ https://maps.googleapis.com/maps/api/geocode/json?key=YourKey&”`(注意:它必须为https,而不是http) (2认同)

pfc*_*ise 6

这称为反向地理编码。我可以在Python中找到一个专注于此的库:https : //github.com/thampiman/reverse-geocoder

一些与其他想法相关的问题:


lin*_*nqu 6

通常,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)

  • 对于Python 3,使用:对于国家/地区,geoms在国家/地区中。items(): (3认同)

小智 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)