Problem with a code trying to retrieve all addresses within a specified region (Geolocator API)

66 Views Asked by At

I have written this code addressing to Geolocator API of Google Maps and it is not functional. Note that as an entry level devoloper I do this through Google collabs.

`import requests
import smtplib
import pandas as pd
file_path = "C:/Users/30697/Downloads/addresses.xlsx"
api_key = "MED_316KQ_4XqvYLSYa2k="
lat1 = 38.1579862
lng1 = 23.9626608
lat2 = 38.1579862
lng2 = 23.9626608
lat3 = 38.1540804
lng3 = 23.9595323
lat4 = 38.1540804
lng4 = 23.9595323

def save_addresses_to_excel(addresses, file_path):
    # Create a DataFrame with the addresses
    df = pd.DataFrame({"Address": addresses})

    # Write the DataFrame to an Excel file
    df.to_excel(file_path, index=False)
def get_addresses_in_region(api_key, lat1, lng1, lat2, lng2, lat3, lng3, lat4, lng4):
    # Define the bounds of the region
    bounds = f"{lat1},{lng1}|{lat2},{lng2}|{lat3},{lng3}|{lat4},{lng4}"

    # Make the API request
    response = requests.get(f"https://maps.googleapis.com/maps/api/geocode/json?bounds={bounds}&key={api_key}")

    # Check if the request was successful
    if response.status_code == 200:
        # Parse the response JSON
        data = response.json()

        # Extract the addresses from the response
        addresses = [result["formatted_address"] for result in data["results"]]

        return addresses
    else:
        # Return an error message
        return "Error: Could not retrieve addresses."

I expect a series of addresses to be displayed as a result.

1

There are 1 best solutions below

0
isshp On

According to the documentation, the bounds parameter is an optional addition to the request, which helps to refine the results. You must also specify address, components, latlng or place_id. Assuming you're trying to do reverse geocoding, you probably need to specify a single coordinate using latlng.