Skip to content

Instantly share code, notes, and snippets.

@mkbabb
Created August 12, 2024 19:14
Show Gist options
  • Select an option

  • Save mkbabb/e2130da16f22a2b9df9ce4cc03ae425d to your computer and use it in GitHub Desktop.

Select an option

Save mkbabb/e2130da16f22a2b9df9ce4cc03ae425d to your computer and use it in GitHub Desktop.
Google Geocoding API Example
from typing import Any # Importing typing to specify more detailed type information
import pandas as pd # Importing pandas for data manipulation and analysis
import requests # Importing requests to make HTTP requests to external APIs
# Function to geocode an address using the Google Maps API
def geocode_address(address: str, api_key: str) -> dict[str, Any]:
# Base URL for the Google Maps Geocoding API
base_url = "https://maps.googleapis.com/maps/api/geocode/json"
# Parameters for the API request, including the address and API key
params = {"address": address, "key": api_key}
# Sending a GET request to the API with the specified parameters
response = requests.get(base_url, params=params)
# Raise an error if the API request failed (e.g., due to a bad response)
response.raise_for_status()
# Parse the JSON response into a Python dictionary
data = response.json()
# Initialize the output dictionary with None values for latitude and longitude
out = {
"lat": None,
"lng": None,
}
# Extract the geometry data (which includes latitude and longitude) from the response
geometry = data["results"][0]["geometry"]
# Get the type of location (e.g., ROOFTOP, RANGE_INTERPOLATED, etc.)
location_type = geometry["location_type"]
# Extract the latitude and longitude from the location data
location = geometry["location"]
lat, lng = location["lat"], location["lng"]
# If the location type is not "ROOFTOP" (i.e., precise location), return the default output
if location_type != "ROOFTOP":
return out
# If the location type is "ROOFTOP", update the output with the latitude and longitude
out["lat"] = lat
out["lng"] = lng
# Return the output dictionary containing the latitude and longitude
return out
# Main block of code that runs when the script is executed
if __name__ == "__main__":
# Placeholder for your API key (replace with your actual key)
api_key = ...
# Placeholder for the path to your Excel file (replace with your actual file path)
data_path = ...
# Read the Excel file into a pandas DataFrame
df = pd.read_excel(data_path)
# Apply the geocode_address function to each address in the DataFrame and create new columns for latitude and longitude
df[["lat", "lng"]] = df["full_address"].apply(
lambda x: pd.Series(geocode_address(address=x, api_key=api_key))
)
# Save the updated DataFrame to a CSV file without including the index column
df.to_csv("output.csv", index=False)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment