Search code examples
pythondata-analysis

determine the city from gps coordinates


I'm trying to find the city using the gps coordinates my dataframe looks like that

        tripId  latitude    longitude
    0   1828765 50.126219   8.767003
    1   1828765 50.126173   8.766984
    ... ... ... ...
    497 1828714 53.680520   10.428270
    498 1828714 53.680497   10.428355
    499 1828714 53.680484   10.428431

i tried this code :

 import numpy as np
    df['location']=np.nan
from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent="geoapiExercises")
    for i in range(df.shape[0]): 
        df['location'][i] =  geolocator.reverse(str(df['latitude'][i])+","+str(df['longitude'][i]))

but it doesn't work! init() missing 3 required positional arguments: 'address', 'point', and 'raw' does any of you have any idea how to solve this ? Thank you


Solution

  • here is the code, i hope that helps you:

    from geopy.geocoders import Nominatim
    import numpy as np
    
    geolocator = Nominatim(user_agent='your_app_name')
    
    coordinates = np.array([
        [50.126219,8.767003],
        [50.126173,8.766984],
        [53.680520,10.428270],
        [53.680497,10.428355],
        [53.680484,10.428431]
    ])
    
    addresses = []
    
    for coordinate in coordinates:
        addresses.append(geolocator.reverse(coordinate).address)
    
    print(addresses)
    
    # output:
    ['20, Willmannstraße, Fechenheim, Ost, Frankfurt am Main, Hessen, 60386, Deutschland',
     '20, Willmannstraße, Fechenheim, Ost, Frankfurt am Main, Hessen, 60386, Deutschland',
     'Pöhlen, Schönberg, Sandesneben-Nusse, Herzogtum Lauenburg, Schleswig-Holstein, 22929, Deutschland',
     'Pöhlen, Schönberg, Sandesneben-Nusse, Herzogtum Lauenburg, Schleswig-Holstein, 22929, Deutschland',
     'Pöhlen, Schönberg, Sandesneben-Nusse, Herzogtum Lauenburg, Schleswig-Holstein, 22929, Deutschland']
    

    Your only mistake was that you were trying to make a formated print, when you just needed to pass the two coordinates.

    I made that code save only the address but if you want more details you can go in the loop and exclude the .address method.

    I hope that i did help you. Good Luck, man.