PYTHON

Converting Addresses to Coordinates with a Third-Party Geocoding API in Python

A Python snippet demonstrating how to use the `requests` library to integrate with a geocoding API, converting street addresses into latitude and longitude coordinates.

# Install: pip install requests
import requests
import os

# Replace with your actual API key. Use environment variables in production.
GEOCODING_API_KEY = os.getenv("GEOCODING_API_KEY", "YOUR_GEOCODING_API_KEY")
GEOCODING_BASE_URL = "https://api.opencagedata.com/geocode/v1/json" # Example: OpenCage Geocoding API

def geocode_address(address: str) -> dict | None:
    """
    Converts a street address to geographical coordinates (latitude, longitude)
    using a third-party geocoding API.
    """
    if not GEOCODING_API_KEY or GEOCODING_API_KEY == "YOUR_GEOCODING_API_KEY":
        print("Error: GEOCODING_API_KEY is not set. Please set it as an environment variable or replace the placeholder.")
        return None

    params = {
        "q": address,
        "key": GEOCODING_API_KEY,
        "language": "en",  # Optional: specify language for results
        "pretty": 1,       # Optional: make JSON output more readable
    }

    try:
        response = requests.get(GEOCODING_BASE_URL, params=params)
        response.raise_for_status()  # Raise an exception for HTTP errors (4xx or 5xx)
        data = response.json()

        if data and data.get("results"):
            # Get the first result's geometry (latitude and longitude)
            first_result = data["results"][0]
            latitude = first_result["geometry"]["lat"]
            longitude = first_result["geometry"]["lng"]
            formatted_address = first_result["formatted"]
            return {
                "address": formatted_address,
                "latitude": latitude,
                "longitude": longitude,
                "confidence": first_result.get("confidence", "N/A")
            }
        else:
            print(f"No results found for address: '{address}'")
            return None
    except requests.exceptions.HTTPError as http_err:
        print(f"HTTP error occurred: {http_err} - {response.text}")
        return None
    except requests.exceptions.ConnectionError as conn_err:
        print(f"Connection error occurred: {conn_err}")
        return None
    except requests.exceptions.Timeout as timeout_err:
        print(f"Timeout error occurred: {timeout_err}")
        return None
    except requests.exceptions.RequestException as req_err:
        print(f"An error occurred during the request: {req_err}")
        return None
    except Exception as e:
        print(f"An unexpected error occurred: {e}")
        return None

if __name__ == "__main__":
    test_address = "1600 Amphitheatre Parkway, Mountain View, CA"
    coordinates = geocode_address(test_address)

    if coordinates:
        print(f"Coordinates for '{test_address}':")
        print(f"  Formatted Address: {coordinates['address']}")
        print(f"  Latitude: {coordinates['latitude']}")
        print(f"  Longitude: {coordinates['longitude']}")
        print(f"  Confidence: {coordinates['confidence']}")
    else:
        print(f"Could not geocode address: '{test_address}'")

    test_address_fail = "Invalid Address Example XYZ"
    geocode_address(test_address_fail)
How it works: This Python snippet demonstrates how to integrate with a third-party geocoding API (like OpenCage) to convert a human-readable street address into geographical coordinates (latitude and longitude). It uses the `requests` library to make an HTTP GET request to the API, passing the address and a secure API key as parameters. Robust error handling is included to catch network issues or API-specific errors, and it extracts the relevant coordinate and formatted address information from the JSON response.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs