Obtaining the City Based on Latitude and Longitude

To obtain city and other details based on latitude and longitude, utilize this method. Additionally, refer to instructions for obtaining a Google Map API key. The JSON parser class can also be utilized for further information. To retrieve a particular address using latitude and longitude, refer to this query which provides three potential solutions. The first solution is to attempt the method provided. Alternatively, the second solution entails employing the code provided below to retrieve the city name. Finally, the third solution is to try the code provided and hopefully resolve any complications that may arise from providing multiple arguments and obtaining multiple outcomes.


Solution:

To execute a specific operation on every row, apply() method can be utilized.

The challenge is twofold; firstly, providing multiple arguments to the function, and secondly, retrieving multiple results.

The following questions provide instructions on how to accomplish those tasks.

  • Create a function named
    python pandas- apply
    that takes two arguments as columns.
  • Return multiple columns
    from pandas apply()

Learn how to modify your code to accomplish this task with the following steps.

import pandas as pd
import io
from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent="geoapiExercises")
s = """Latitude   Longitude  
42.022506  -88.168156  
41.877445  -87.723846  
29.986801  -90.166314"""
df = pd.read_csv(io.StringIO(s), delim_whitespace=True)
def city_state_country(row):
    coord = f"{row['Latitude']}, {row['Longitude']}"
    location = geolocator.reverse(coord, exactly_one=True)
    address = location.raw['address']
    city = address.get('city', '')
    state = address.get('state', '')
    country = address.get('country', '')
    row['city'] = city
    row['state'] = state
    row['country'] = country
    return row
df = df.apply(city_state_country, axis=1)
print(df)

The call to read_csv() has been substituted with an inline definition of the dataframe, but this is insignificant to the example and is only meant to make the example self-contained.

The

city_state_country()

function is executed for each row in the dataframe using the

axis=1

argument to apply() to work with rows instead of columns. Within the function, the lat and lon are obtained and a query is performed. Finally, the retrieved information is added to the corresponding row.

This gets the following result:

    Latitude  Longitude     city      state        country
0  42.022506 -88.168156            Illinois  United States
1  41.877445 -87.723846  Chicago   Illinois  United States
2  29.986801 -90.166314           Louisiana  United States

Your example differs, however, it appears that Nominatim designates the coordinates you provided as towns instead of cities, as it does not return a city for them.

Frequently Asked Questions