检索多个位置的经度和纬度

问题描述 投票:0回答:2

如何获得一个以上的经度和纬度?我正在尝试获取多伦多15个行政区的坐标。我已经尝试过

address = ['Toronto Canada', 'East York', 'Davenport', 'Eglinton', 'Etobicoke', 'Toronto-Danforth']
geolocator = Nominatim(user_agent="foursquare_agent")
location = geolocator.geocode(address)
lat = location.latitude
lng = location.longitude
print(lat, lng)

以上返回:AttributeError:'NoneType'对象没有属性'纬度'

python geolocation foursquare
2个回答
0
投票

单个geocode()查询将搜索单个位置。要查找多个位置,您需要循环运行。

city = 'Toronto, Canada'
boroughs  = ['East York', 'Davenport', 'Eglinton', 'Etobicoke', 'Toronto-Danforth']
for borough in boroughs:
    address = borough + ', ' + city
    location = geolocator.geocode(address)
    lat = location.latitude
    lng = location.longitude
    print(address, lat, lng)

0
投票

您收到该错误是因为您在尝试传递Python列表时将错误的类型传递给geolocator.geocode,该类型将查询作为dict(用于结构化查询)或str

请参见GeoPy文档:https://geopy.readthedocs.io/en/stable/#nominatim

因此,获取您想要的信息的一种直接但不一定有效的方法是将编码为字符串的每个自治市镇单独传递给您的geolocator实例。类似以下内容应该可以工作:

# your usual imports and data assigments

locations = [geolocator.geocode(borough) for borough in address]

from pprint import pprint
pprint(locations)
---
[Location(Toronto, Golden Horseshoe, Ontario, M6K 1X9, Canada, (43.653963, -79.387207, 0.0)),
 Location(East York, Toronto—Danforth, East York, Toronto, Golden Horseshoe, Ontario, M4J 2G9, Canada, (43.6913391, -79.3278212, 0.0)),
 Location(Davenport, Scott County, Iowa, USA, (41.5236436, -90.5776368, 0.0)),
 Location(Eglinton, County Londonderry, Northern Ireland, BT47 3GY, United Kingdom, (55.0266097, -7.176451, 0.0)),
 Location(Etobicoke, Toronto, Golden Horseshoe, Ontario, Canada, (43.67145915, -79.5524920661167, 0.0)),
 Location(Toronto—Danforth, Old Toronto, Toronto, Golden Horseshoe, Ontario, Canada, (43.6789439, -79.3448597, 0.0))]

并且从这里,您应该能够从Location对象的列表中获得纬度,经度以及其他所需的信息。

还请注意,“ Davenport”和“ Eglinton”显然不够明确,因此您可能要指定“ Davenport,Toronto”,依此类推。

最后说明:geocode类的Nominatim方法确实有一个可选参数exactly_one(默认为True),因此也许确实存在某种方式来获取整个列表的地理编码位置通过一次方法调用就可以确定不同的地址,但是我并没有真正研究如何做到这一点(如果确实可行的话),因为我从未使用过GeoPy,也不熟悉对自己进行地理编码的主题。

顺便说一句,我也是多伦多人,所以我知道你提到的所有这些地方:D

© www.soinside.com 2019 - 2024. All rights reserved.