如何获取多个地点经纬度?多伦多15个行政区坐标获取遇报错
Fixing the AttributeError When Geocoding Toronto Neighborhoods
Got it, let's break down why you're hitting this AttributeError: 'NoneType' object has no attribute 'latitude' and fix it step by step:
What's Going Wrong?
geocode()doesn't accept lists: You're passing the entireaddresslist directly togeolocator.geocode(), but this method expects a single string address, not a list of strings.- Ambiguous addresses: Short names like "East York" or "Davenport" lack context—without specifying they're in Toronto, Nominatim might fail to find the correct location and return
None, which triggers the error when you try to access.latitude.
Corrected Code
Here's a revised version that fixes both issues, adds error handling, and properly processes all your addresses:
from geopy.geocoders import Nominatim # Add full context to each neighborhood to ensure accurate geocoding addresses = [ 'Toronto, Canada', 'East York, Toronto, Canada', 'Davenport, Toronto, Canada', 'Eglinton, Toronto, Canada', 'Etobicoke, Toronto, Canada', 'Toronto-Danforth, Toronto, Canada' ] geolocator = Nominatim(user_agent="foursquare_agent") # Process each address individually for addr in addresses: try: location = geolocator.geocode(addr) if location: lat = location.latitude lng = location.longitude print(f"{addr}: Latitude = {lat}, Longitude = {lng}") else: print(f"Could not find coordinates for: {addr}") except Exception as e: print(f"Error processing {addr}: {str(e)}")
Key Improvements
- Per-address iteration: We loop through each entry in the list instead of passing the whole list to
geocode(), which matches the method's expected input. - Specific address formatting: Appending ", Toronto, Canada" to each neighborhood name gives Nominatim clear context, so it targets the correct Toronto locations instead of places with the same name elsewhere.
- Error resilience: The
try-exceptblock andif locationcheck prevent the program from crashing if an address can't be parsed, and tells you exactly which entry needs adjustment.
For Your 15 Neighborhoods
Just extend the addresses list with your remaining 9 neighborhoods, each formatted as [Neighborhood Name], Toronto, Canada—this should give you reliable coordinates for all of them.
内容的提问来源于stack exchange,提问作者Organic Heart
相关产品推荐
相关产品推荐

