简体   繁体   中英

geopy distance get city python

I'm not sure this is possible but I have a list of coordinates of cities, then I would like take the first coordinate in the list and calculate it's distance for each coordinate in the list, finally I would like to get shortest distance and the city name. I am able to do all the stuff except for getting the city name and state. Is there anyway to do this?

from geopy.geocoders import GoogleV3
from geopy.distance import vincenty
geolocator = GoogleV3()

cord_places = [(41.6592776, -76.7503693), (37.7792768, -122.4192704), (42.3486635, -83.0567375)
first = cord_places[0];
cord_places.remove(first)

print distance(first, cord_places)
def distance(first, cord_places):
    for ct in cord_paces
        dist = vincenty((first), (ct))#this gives me all the distances between first city and the others in the list but I would like to know which city it was
    return dist

does anyone have any hint?

I found this was simpler with the Nominatim geocoder, if you want/need to use the GoogleV3 inspect the .raw attribute and look at the google api doc

from geopy.geocoders import Nominatim
geolocator = Nominatim()

def city_and_state(coord):
    location = geolocator.reverse(coord, exactly_one=True)
    address = location.raw['address']
    city = address.get('city', '')
    state = address.get('state', '')
    return city, state

If the address is not accociated with a city or state, an empty string is returned. For your first coordinate (41.6592776, -76.7503693) you may want the hamlet key instead of city .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM