Search code examples
pythonbing-mapsgeocoder

How to get the postal code, providing the geographical coordinates, using geocoder in python


I'm using the following function to convert postal codes to geographical coordinates and to append it to the source dataframe (using geocoder powered by Bing maps api)

My question is, how can I modify it to do the reverse. I want to provide the latitude and longitude, and get in return the postal code.


def get_lats_longs(df): 

    lat_lng_coords = None
    # create lists to store our new lats and longs
    lats = []
    longs=[]
    #loop through our dataframe and look up the lat/long of each postal code
    for index, row in df.iterrows():
        postal_code=row[0]
        # loop until you get the coordinates
        lat_lng_coords = None
        while(lat_lng_coords is None):
            g = geocoder.bing('{}, Toronto, Ontario'.format(postal_code),key=bing_key)
            lat_lng_coords = g.latlng

        lats.append(lat_lng_coords[0])
        longs.append(lat_lng_coords[1])

    df['Latitude'] = lats
    df['Longitude'] = longs
    return df

Thanks in advance


Solution

  • From https://geocoder.readthedocs.io/providers/Bing.html#reverse-geocoding

    g = geocoder.google([45.15, -75.14], method='reverse')
    print(g.postal)