pythonpandasgoogle-geocoding-api

Google Maps Geocoding Coordinates Search Problem


I have the dataset.They are like this:

name, longitude, langitude

My code is like this:

def get_city(latitude, longitude, api_key):
    """Google Maps Geocoding API to determine the city from coordinates."""
    url = f"https://maps.googleapis.com/maps/api/geocode/json?latlng={latitude},{longitude}&key={api_key}"
    response = requests.get(url)
    if response.status_code == 200:
        results = response.json().get('results', [])
        if results:
            for component in results[0]['address_components']:
                if 'locality' in component['types']:
                    return component['long_name']
                elif 'administrative_area_level_1' in component['types']:
                    return component['long_name']
    return "Not Found"

data['City'] = data.apply(lambda row: get_city(row['Latitude'], row['Longitude'], api_key), axis=1)

But my output is like this:

output

I want to search my coordinates via Google Geocoding API and find out which city my coordinates are in.


Solution

  • I do not have a Google API, but I know that your issue comes from the fact that you have the N, W, S, E mention in your columns. You need to remove them. With geopy your code would look like this:

    from geopy.geocoders import Nominatim
    import pandas as pd
    
    def get_city_geopy(latitude, longitude):
        geolocator = Nominatim(user_agent="geoapiExercises")
        location = geolocator.reverse(f"{latitude}, {longitude}", exactly_one=True)
        if location:
            address = location.raw.get('address', {})
            return address.get('city', address.get('town', address.get('village', 'Not Found')))
        return "Not Found"
    
    data = pd.DataFrame({
        'Mahalle': ['Ortahisar'],
        'Longitude': ['34.8668937"E'],
        'Latitude': ['38.626686"N']
    })
    
    def convert_to_decimal(coord):
        coord = coord.strip('\"NSEW')
        return float(coord)
    
    data['Latitude'] = data['Latitude'].apply(convert_to_decimal)
    data['Longitude'] = data['Longitude'].apply(convert_to_decimal)
    
    data['City'] = data.apply(lambda row: get_city_geopy(row['Latitude'], row['Longitude']), axis=1)
    
    data
    

    which will give you the name of the city Ortahisar Beldesi. With Google Map API, the function

    def get_city_geopy(latitude, longitude):
        geolocator = Nominatim(user_agent="geoapiExercises")
        location = geolocator.reverse(f"{latitude}, {longitude}", exactly_one=True)
        if location:
            address = location.raw.get('address', {})
            return address.get('city', address.get('town', address.get('village', 'Not Found')))
        return "Not Found"
    

    must be

    def get_city(latitude, longitude, api_key):
        url = f"https://maps.googleapis.com/maps/api/geocode/json?latlng={latitude},{longitude}&key={api_key}"
        response = requests.get(url)
        if response.status_code == 200:
            results = response.json().get('results', [])
            if results:
                for component in results[0]['address_components']:
                    if 'locality' in component['types']:
                        return component['long_name']
                    elif 'administrative_area_level_1' in component['types']:
                        return component['long_name']
        return "Not Found"
    

    that is, exactly the function you gave.