Map Power-Plant Emitters with Claude
Use Claude Code to rank nearby power plants and map their annual emissions.
Introduction
30 Second Summary
National emissions rankings can hide what is happening close to home. A smaller power plant nearby may matter more to your local question than a major facility hundreds of kilometres away.
In this project, you will use Claude Code to build a local Python emissions finder. The finished tool identifies the biggest annual power-plant emitter within 50 km of your town.
What You'll Build
Imagine entering your town to reveal a map where the biggest nearby power-plant emitter stands out as the largest circle.
By the end of this project, you'll have:
- A location search that lets you choose the correct town from a numbered list.
- A ranked emissions table that shows every power plant within 50 km. The biggest annual emitter appears at rank 1.
- An interactive proportional-symbol map where circle size represents annual emissions. A monthly readout shows how current the top plant's data is.
- Secret Mission: Paginate your home country plus nearby countries so a national border cannot hide a closer plant.
Are there any prerequisites?
You need a Mac or Windows computer with internet access. You also need permission to install software plus an existing Claude Pro account.
No coding experience is required.
Before We Start
This is your moment to commit to the local emissions map before the hands-on work begins. Choose the town you want to search and connect it to your reason for comparing nearby power plants.
Set Up Claude Code
A verified workspace gives Claude Code a safe place to inspect your setup before it creates anything.
An activated virtual environment keeps future project packages inside one folder. A supported Python runtime gives those packages a reliable foundation.
In this step, get ready to:
- Verify Python 3.11 or later and confirm Claude Code is available.
- Create the my-carbon-neighbours folder with an activated .venv virtual environment.
- Open Claude Code and complete a read-only Python check without creating source files.
Open the correct terminal and verify your tools
Your terminal is where you check Python and launch Claude Code. macOS uses Terminal while Windows uses PowerShell.
macOS
- Press Cmd + Space to open Spotlight.
- Type Terminal into the search bar.
- Press Enter to open Terminal.
You should see a Terminal prompt where you can type commands.
Windows
- Press Win + X to open the system menu.
- Select Windows PowerShell or Terminal.
- Confirm the prompt begins with PS.
You should see a PowerShell prompt ready for commands.
- Check your installed Python version by running the command for your platform:
macOS
python3 --version
What does this command do?
The command asks the python.org interpreter to print its installed version. The project requires Python 3.11 or later.
You should see a Python version number in the terminal.
Windows
python --version
What does this command do?
The command asks the default Windows Python runtime to print its installed version. The project requires Python 3.11 or later.
You should see a Python version number in PowerShell.
✔️ I see a supported Python version
Your Python runtime is ready for the project.
ⓧ I see an older Python version
Your current runtime is below the project's minimum. Install a current Python release using the action below.
ⓧ Python is not found
Python needs to be installed before you create the virtual environment. Use the official installer in the next action.
- Install a current Python release from the official Python downloads page if your version is missing or lower than 3.11.
- Run Install Certificates.command from /Applications/Python 3.15/ after completing the macOS installer.
- Repeat the Python version check after the installation completes.
Continue when the version output shows Python 3.11 or later.
- Check whether Claude Code is installed by running:
claude --version
What does this command do?
The --version option asks Claude Code to print its installed version without starting an interactive session.
A working installation prints a Claude Code version number.
If the command does not print a version number, install Claude Code with the command for your platform.
macOS
- Install Claude Code on macOS by running:
curl -fsSL https://claude.ai/install.sh | bash
What does this command do?
The command downloads the official Claude Code installation script. It sends that script to your shell for installation.
You should see installation progress followed by a completion message.
Windows
- Install Claude Code in PowerShell by running:
irm https://claude.ai/install.ps1 | iex
What does this command do?
The command downloads the official Claude Code PowerShell installation script. It passes that script to PowerShell for installation.
You should see installation progress followed by a completion message.
Claude Code installation failed?
Check that your internet connection is active. Confirm that your terminal has permission to install software.
Use help me troubleshoot my Claude Code installation with the terminal output if the installer still fails.
- Repeat the Claude Code version check after the installation completes.
Good progress. Both Python and Claude Code now respond from your terminal.
Create and activate the project workspace
The my-carbon-neighbours folder keeps every local project artifact together. Its .venv folder isolates the Python packages you install later.
macOS
- Create the my-carbon-neighbours folder and move into it by running:
mkdir -p my-carbon-neighbours && cd my-carbon-neighbours
What does this command do?
- The mkdir -p command creates the project folder if it does not already exist.
- The cd command moves your terminal into that folder.
Your terminal prompt should now show that you are inside my-carbon-neighbours.
- Create the .venv environment and activate it by running:
python3 -m venv .venv && source .venv/bin/activate
What does this command do?
Python creates an isolated environment inside .venv. The activation command makes that environment the current terminal's Python context.
You should see (.venv) at the beginning of your terminal prompt.
Windows
- Create the my-carbon-neighbours folder and move into it by running:
New-Item -ItemType Directory -Force my-carbon-neighbours; Set-Location my-carbon-neighbours
What does this command do?
- The New-Item command creates the project folder.
- The Set-Location command moves PowerShell into that folder.
Your PowerShell prompt should now show that you are inside my-carbon-neighbours.
- Create the .venv environment and activate it by running:
python -m venv .venv; .\.venv\Scripts\Activate.ps1
What does this command do?
Python creates an isolated environment inside .venv. The activation script makes that environment the current PowerShell Python context.
You should see (.venv) at the beginning of your PowerShell prompt.
Start Claude Code and approve a read-only check
The final check proves both tools work from inside the project folder. It also confirms Claude Code follows a request that allows inspection without file creation.
Before you run the checks, do you expect both tools to report their versions from inside the activated environment?
macOS
- Verify Python and Claude Code together by running:
python3 --version && claude --version
What does this command do?
The first check prints the active Python version. The second check runs only when the Python check succeeds.
You should see a supported Python version followed by a Claude Code version.
Windows
- Verify Python and Claude Code together by running:
python --version; claude --version
What does this command do?
The first check prints the active Python version. The second check prints the installed Claude Code version.
You should see a supported Python version followed by a Claude Code version.
The first Claude Code launch may open your browser for authentication. Use your existing Claude Pro account to complete the sign-in.
- Start the interactive Claude Code session by running:
claude
What does this command do?
The command starts Claude Code inside the current my-carbon-neighbours folder. Claude can inspect that folder after you approve its requested actions.
- Complete the browser sign-in with your existing Claude Pro account if authentication opens.
You should see the Claude Code welcome screen inside your terminal.
- Ask Claude Code to inspect the workspace by pasting this exact message:
Before we build anything, check this folder and tell me whether Python is available. Do not create files yet.
What does this prompt do?
The prompt permits a read-only environment check. Its final sentence sets a clear boundary against creating project files.
- Approve Claude Code's read-only Python version check.
- Decline any request to create a file.
Claude should report that Python is available. Your project folder should still contain no source files.
Your isolated Claude Code workspace is ready. Next, you will turn your town into the coordinates that power the emissions search.
Save Your Home Location
Your Claude Code workspace is ready. The first data your emissions map needs is a precise home location.
A visible town lookup creates the coordinates behind every later distance calculation.
In this step, get ready to:
- Install the four pinned packages in the activated .venv environment.
- Create find_me.py with a numbered location lookup.
- Save your selected coordinates and three-letter country code in home.json.
Install the pinned packages
Requests handles the location lookup. pycountry converts the returned two-letter country code into the three-letter format used later.
Folium and branca support the interactive map you build later. Installing all four pinned packages now gives every learner the same versions.
macOS
- Install the pinned packages in your activated virtual environment by running:
python3 -m pip install requests==2.34.2 folium==1.0.0 pycountry==26.2.16 branca==0.8.2
What does this command do?
This command uses the active Python environment's package installer. The four version pins keep your project reproducible.
You should see the four packages finish installing without an error.
Windows
- Install the pinned packages in your activated virtual environment by running:
python -m pip install requests==2.34.2 folium==1.0.0 pycountry==26.2.16 branca==0.8.2
What does this command do?
This command uses the active Python environment's package installer. The four version pins keep your project reproducible.
You should see the four packages finish installing without an error.
Package installation failed?
Confirm that the virtual environment from the previous step is still active. Retry the command after restoring the activation.
Help me troubleshoot the pinned package installation in my activated Python virtual environment.
Ask Claude Code to create the location finder
The Open-Meteo Geocoding API turns a town search into possible locations. Each result arrives as JSON with a name and coordinates.
The script presents those results as a numbered list. Your choice prevents a town with the same name in another country from becoming your saved home.
- Paste this exact message into Claude Code:
Install requests and folium. Then write find_me.py. Ask me for my town, call the Open-Meteo geocoding API, show me a numbered list of matches with country names, let me choose one, then save its name, latitude, longitude and three-letter country code to home.json. Then run it.
What does this prompt ask for?
- Claude creates one script that searches for possible locations.
- The numbered choice gives you control over which location is saved.
- The selected result becomes the input data for every later distance calculation.
- Review Claude Code's requested tool actions before approving them.
- Approve creation of find_me.py.
- Decline any new unpinned installation request.
You should see Claude create find_me.py. It should then request permission to run the script.
Choose and verify your location
A short town name can match several places. The country and region beside each result help you choose the intended location.
Before you approve the run, do you expect a town name alone to identify one place or several possible matches?
macOS
- Run find_me.py from Claude Code by approving this command:
python3 find_me.py
What does this command do?
The command executes your location finder with Python. The script pauses so you can enter a town and choose a match.
Windows
- Run find_me.py from Claude Code by approving this command:
python find_me.py
What does this command do?
The command executes your location finder with Python. The script pauses so you can enter a town and choose a match.
- Approve the read-only request to Open-Meteo if Claude Code asks for permission.
- Type your town at the Town or place name: prompt.
- Inspect the country beside each numbered match.
- Enter the number for your intended location.
You should see a confirmation containing your selected place. It also shows the latitude and longitude.
The confirmation ends with a three-letter country code. This proves the two-letter result was converted successfully.
Cannot find the intended town?
Search again with a longer query such as Town, Country. Including the country narrows ambiguous results.
Help me diagnose why my Open-Meteo town search is missing the intended location.
- Confirm the saved location by pasting this read-only message into Claude Code:
Read home.json without changing it. Show me the saved name, country, latitude, longitude and country_code.
What does this check do?
Claude reads the saved file without editing it. Listing the five fields confirms that the next scripts have the location data they need.
That first live lookup is working. Claude should show name, country, latitude, longitude, and country_code from home.json.
✔️ Awesome, I've got everything!
Your location finder matches the project checkpoint.
ⓧ I'd like to double check the full code
- Compare your saved find_me.py with this complete file:
import json
import pycountry
import requests
GEOCODING_URL = "https://geocoding-api.open-meteo.com/v1/search"
def main():
town = input("Town or place name: ").strip()
if not town:
raise SystemExit("Enter a town or place name.")
response = requests.get(
GEOCODING_URL,
params={"name": town, "count": 5, "language": "en", "format": "json"},
timeout=30,
)
response.raise_for_status()
results = response.json().get("results") or []
if not results:
raise SystemExit("No matches found. Try Town, Country.")
for index, result in enumerate(results, start=1):
country = result.get("country", "Unknown country")
admin1 = result.get("admin1")
region = f", {admin1}" if admin1 else ""
print(f"{index}. {result['name']}{region}, {country}")
while True:
try:
choice = int(input(f"Choose 1-{len(results)}: "))
selected = results[choice - 1]
break
except (ValueError, IndexError):
print("Choose one of the listed numbers.")
country = pycountry.countries.get(alpha_2=selected["country_code"])
if country is None:
raise SystemExit("Could not convert the two-letter country code.")
home = {
"name": selected["name"],
"country": selected.get("country", country.name),
"latitude": selected["latitude"],
"longitude": selected["longitude"],
"country_code": country.alpha_3,
}
with open("home.json", "w", encoding="utf-8") as file:
json.dump(home, file, indent=2, ensure_ascii=False)
print(
f"Saved {home['name']}, {home['country']} "
f"({home['latitude']}, {home['longitude']}) as {home['country_code']}."
)
if __name__ == "__main__":
main()
Your coordinates are ready. Next, you will use the saved country code to retrieve national power-plant emissions data.
Retrieve National Plant Data
Your selected town is now stored in home.json. That file gives Claude Code the country code for the next data request.
A country-wide plant list proves that annual emissions can be ranked before you determine which plants are close to home.
In this step, get ready to:
- Create get_plants.py to retrieve your country's 2025 electricity-generation sources.
- Save plants.json with the greatest annual emitters first.
- Inspect zero-tonne records and keep them as valid returned plant data.
Build the national data pull
The Climate TRACE API returns emissions source summaries as JSON. The country code in home.json limits the request to your selected country.
- Paste this exact message into Claude Code:
- Switch back to the Claude Code session from earlier.
- Place your cursor in the active prompt.
Write get_plants.py. Read the country code from home.json. Call https://api.climatetrace.org/v7/sources with year=2025, gadmId set to my country code, sectors=power, subsectors=electricity-generation and limit=1000. Save the response to plants.json sorted by emissionsQuantity descending. Print the total number of plants and the three largest emitters. Then run it.
What does this prompt do?
- The request uses home.json to select the learner's three-letter country code.
- The filters select 2025 power sources from electricity generation.
- The limit=1000 parameter requests up to one thousand sources.
- The descending sort places the greatest emissionsQuantity value first.
The Requests library makes the public API call. This request does not use an API key.
This API call uses no credentials, so the permission review stays limited to one file and read-only public data access.
- Approve creation of get_plants.py.
- Review the file path in Claude Code's permission prompt.
- Choose the option that allows this file creation.
You should see get_plants.py appear inside my-carbon-neighbours.
- Approve the read-only request to api.climatetrace.org.
- Review the API host in Claude Code's permission prompt.
- Choose the option that allows the read-only request.
You should see Claude Code continue with the public data request.
- Reject any request for credentials or unrelated file changes.
- Choose the deny option if the requested action falls outside this step.
Review the national ranking
The script sorts the returned plants by emissionsQuantity. This produces a national emissions ranking from the largest annual value to the smallest.
Before you approve the run, which plants do you expect in the first three positions: the nearest plants or the greatest annual emitters.
- Approve Claude Code's local run of get_plants.py.
- Review the local script command in Claude Code's permission prompt.
- Choose the option that allows this run.
You should see plants.json created. The terminal should print the total plant count plus the three greatest 2025 emitters.
That is the national baseline working. Its top three plants lead by annual emissions without proving that any of them are near your town.
The request asks for up to 1,000 sources in one response. Some large countries can have additional sources beyond that single page.
✔️ Awesome, I've got everything!
Your original location script remains available. Your new national data script now matches the expected project state.
ⓧ I'd like to double check the full code
- Compare find_me.py with this unchanged reference.
import json
import pycountry
import requests
GEOCODING_URL = "https://geocoding-api.open-meteo.com/v1/search"
def main():
town = input("Town or place name: ").strip()
if not town:
raise SystemExit("Enter a town or place name.")
response = requests.get(
GEOCODING_URL,
params={"name": town, "count": 5, "language": "en", "format": "json"},
timeout=30,
)
response.raise_for_status()
results = response.json().get("results") or []
if not results:
raise SystemExit("No matches found. Try Town, Country.")
for index, result in enumerate(results, start=1):
country = result.get("country", "Unknown country")
admin1 = result.get("admin1")
region = f", {admin1}" if admin1 else ""
print(f"{index}. {result['name']}{region}, {country}")
while True:
try:
choice = int(input(f"Choose 1-{len(results)}: "))
selected = results[choice - 1]
break
except (ValueError, IndexError):
print("Choose one of the listed numbers.")
country = pycountry.countries.get(alpha_2=selected["country_code"])
if country is None:
raise SystemExit("Could not convert the two-letter country code.")
home = {
"name": selected["name"],
"country": selected.get("country", country.name),
"latitude": selected["latitude"],
"longitude": selected["longitude"],
"country_code": country.alpha_3,
}
with open("home.json", "w", encoding="utf-8") as file:
json.dump(home, file, indent=2, ensure_ascii=False)
print(
f"Saved {home['name']}, {home['country']} "
f"({home['latitude']}, {home['longitude']}) as {home['country_code']}."
)
if __name__ == "__main__":
main()
- Compare get_plants.py with this reference.
import json
import requests
SOURCES_URL = "https://api.climatetrace.org/v7/sources"
def main():
with open("home.json", encoding="utf-8") as file:
home = json.load(file)
response = requests.get(
SOURCES_URL,
params={
"year": 2025,
"gadmId": home["country_code"],
"sectors": "power",
"subsectors": "electricity-generation",
"limit": 1000,
},
timeout=30,
)
response.raise_for_status()
plants = response.json() or []
if not isinstance(plants, list):
raise SystemExit("Climate TRACE returned an unexpected response.")
plants.sort(key=lambda plant: plant.get("emissionsQuantity") or 0, reverse=True)
with open("plants.json", "w", encoding="utf-8") as file:
json.dump(plants, file, indent=2, ensure_ascii=False)
print(f"Saved {len(plants)} plants to plants.json.")
print("Three largest 2025 emitters:")
for rank, plant in enumerate(plants[:3], start=1):
tonnes = plant.get("emissionsQuantity") or 0
print(f"{rank}. {plant.get('name', 'Unknown')}: {tonnes:,.0f} tonnes")
if __name__ == "__main__":
main()
Inspect zero-valued records
A plant can appear in the response with an annual emissionsQuantity of 0. That value remains part of a valid returned plant record.
- Check the final records in plants.json for emissionsQuantity values of 0.
- Open plants.json in the Claude Code session from earlier.
- Scroll to the final plant records.
Any zero-valued entries should still contain plant details such as an identity and a location.
- Keep every zero-valued plant record in plants.json.
Why keep zero-valued records?
A returned 0 is an emissions value. It does not prove that the request failed.
In the verified GBR snapshot, positive values ended at offset 125. Zero values continued from offset 126 through offset 203.
The records at offsets 126 and 203 were biomass plants.
Before you rerun the script, which order do you expect in the printed top three.
macOS
- Refresh plants.json by running this command:
python3 get_plants.py
What does this command do?
The command runs get_plants.py with Python. The script retrieves the national list before replacing plants.json with the sorted response.
You should see the total number of saved plants. The next three lines should list the greatest annual emitters in descending order.
Windows
- Refresh plants.json by running this command:
python get_plants.py
What does this command do?
The command runs get_plants.py with Python. The script retrieves the national list before replacing plants.json with the sorted response.
You should see the total number of saved plants. The next three lines should list the greatest annual emitters in descending order.
API request failed?
- Confirm your computer still has internet access.
- Confirm home.json contains a three-letter country_code value.
- Compare SOURCES_URL with the full-code reference.
Help me diagnose the failed Climate TRACE request.
Your national emissions dataset is ready. Next, you will test which of these plants fall within 50 km of your town.
Rank Nearby Plants
Your country-wide Climate TRACE list is ready. Now you will narrow that list to the power plants around your selected location.
The national top three may be hundreds of kilometres away, so this step uses Haversine distance to filter plants before ranking the nearby results by annual emissions.
In this step, get ready to:
- Create near_me.py with a Haversine distance calculation.
- Keep only power plants within 50 km of your selected location.
- Rank the filtered plants so the largest nearby annual emitter appears first.
Turn the national list into a local question
Each plant record stores a geographic centre called a centroid. Haversine distance turns the home coordinates plus each centroid into a distance along Earth’s surface.
- Ask Claude Code to create the nearby filter by pasting this exact message:
Write near_me.py. Read home.json and plants.json. Calculate the Haversine distance from my location to each plant using its centroid. Keep plants within 50km. Sort those plants by emissionsQuantity descending, not by distance. Print a ranked table with rank, plant name, fuel type, annual tonnes and distance in km. Then run it.
What does this prompt do?
The prompt makes distance the inclusion test. It makes annual emissions the ranking key.
Claude reads your existing local files, so this step needs no new network request.
- Approve Claude’s request to create near_me.py.
- Read the requested file path in Claude Code’s permission prompt.
- Accept the request only when it targets near_me.py.
- Leave Claude’s run request pending until you have checked the new file.
You should see near_me.py appear inside my-carbon-neighbours.
Check the filter and ranking order
Distance decides which plants belong in the result. Annual emissions decide their order after that filter has finished.
- In near_me.py, confirm RADIUS_KM is set to 50.
- Confirm EARTH_RADIUS_KM is set to 6371.0.
- Confirm load_ranked_nearby() applies distance <= RADIUS_KM before adding a plant to nearby.
- Confirm nearby.sort() uses emissionsQuantity with reverse=True.
The distance filter should finish before the descending emissions sort begins. This order keeps every ranked row local.
Your near_me.py file should now match the complete reference below.
✔️ Awesome, I've got everything!
- Save near_me.py.
Your distance filter is ready for its first local ranking.
ⓧ I'd like to double check the full code
- Compare near_me.py with this complete reference.
import json
from math import asin, cos, radians, sin, sqrt
RADIUS_KM = 50
EARTH_RADIUS_KM = 6371.0
def haversine_km(latitude1, longitude1, latitude2, longitude2):
lat1 = radians(latitude1)
lon1 = radians(longitude1)
lat2 = radians(latitude2)
lon2 = radians(longitude2)
delta_lat = lat2 - lat1
delta_lon = lon2 - lon1
value = (
sin(delta_lat / 2) ** 2
+ cos(lat1) * cos(lat2) * sin(delta_lon / 2) ** 2
)
return 2 * EARTH_RADIUS_KM * asin(sqrt(value))
def load_ranked_nearby():
with open("home.json", encoding="utf-8") as file:
home = json.load(file)
with open("plants.json", encoding="utf-8") as file:
plants = json.load(file)
nearby = []
for plant in plants:
centroid = plant.get("centroid") or {}
latitude = centroid.get("latitude")
longitude = centroid.get("longitude")
if latitude is None or longitude is None:
continue
distance = haversine_km(
home["latitude"],
home["longitude"],
latitude,
longitude,
)
if distance <= RADIUS_KM:
ranked_plant = dict(plant)
ranked_plant["distanceKm"] = distance
nearby.append(ranked_plant)
nearby.sort(
key=lambda plant: plant.get("emissionsQuantity") or 0,
reverse=True,
)
return home, nearby
def main():
home, nearby = load_ranked_nearby()
print(f"Power plants within {RADIUS_KM} km of {home['name']}: {len(nearby)}")
print(f"{'Rank':<5} {'Plant':<40} {'Fuel':<22} {'Tonnes':>14} {'Km':>8}")
print("-" * 95)
for rank, plant in enumerate(nearby, start=1):
name = plant.get("name", "Unknown")[:40]
fuel = (plant.get("assetType") or "unknown")[:22]
tonnes = plant.get("emissionsQuantity") or 0
distance = plant["distanceKm"]
print(f"{rank:<5} {name:<40} {fuel:<22} {tonnes:>14,.0f} {distance:>8.1f}")
if __name__ == "__main__":
main()
Verify the ranking invariant
The table places annual tonnes beside distance. This makes it easy to confirm that a closer plant can still rank below a larger emitter.
Before the run, which plant do you expect at rank 1: the closest plant or the nearby plant with the most annual emissions?
macOS
- Verify the local ranking by checking that Claude is asking to run this command:
python3 near_me.py
What does this command do?
The python3 command runs near_me.py inside your active virtual environment. The script reads both local data files before printing the filtered table.
- Approve this command in Claude Code.
- Read the pending command in Claude Code’s permission prompt.
- Accept it when it matches the command above.
Windows
- Verify the local ranking by checking that Claude is asking to run this command:
python near_me.py
What does this command do?
The python command runs near_me.py inside your active virtual environment. The script reads both local data files before printing the filtered table.
- Approve this command in Claude Code.
- Read the pending command in Claude Code’s permission prompt.
- Accept it when it matches the command above.
You should see a table with rank, plant name, fuel type, annual tonnes, and distance in kilometres. The tonnes column should descend from the largest nearby emitter to the smallest.
Rank 1 should have the greatest emissionsQuantity among every row within 50 km. That is the local ranking working as intended.
If you searched London, the dated checkpoint found 21 plants within 50 km. Rye House power station ranked first with 737,530 tonnes.
Its recorded distance was about 30.0 km. Your result can shift as Climate TRACE revises estimates or Open-Meteo returns a slightly different coordinate.
No nearby rows?
- Confirm home.json contains latitude plus longitude values.
- Confirm plants.json contains plant records with centroid coordinates.
- Check that load_ranked_nearby() reads the existing files from my-carbon-neighbours.
Ask for help with an empty nearby-plant table.
Your local emissions ranking now separates proximity from impact. Next, you will turn the same order into an interactive map.
Map and Check Monthly Emissions
Your 50 km table now identifies the biggest nearby emitter. The next view turns that ranking into something you can inspect on a map.
This step makes your ranking spatially visible while grounding its monthly series in live Climate TRACE freshness metadata.
In this step, get ready to:
- Create an interactive map where the rank-1 plant has the largest circle inside the 50 km boundary.
- Confirm the same top plant appears in your table, your map, and Climate TRACE Explore.
- Check the live metadata and print the top plant's monthly emissions through the latest published month.
Create the proportional emissions map
Folium turns your ranked location data into an interactive HTML map. Each plant's circle uses its annual emissions to determine its visible size.
- Ask Claude Code to create and run the map by pasting this exact message:
Write make_map.py using folium. Read home.json and plants.json. Create map.html centered on my location. Add a home marker, a 50km boundary circle, and a proportional circle for each plant within 50km. Circle size must represent annual emissionsQuantity, so the rank 1 plant is the largest circle. Each popup should show the plant name, fuel type, annual tonnes and distance. Add the credit Emissions data: Climate TRACE (CC BY 4.0) in a corner. Then run it.
What does this prompt ask Claude to do?
- The script reuses load_ranked_nearby() so the map follows the same 50 km filter and emissions ranking as your table.
- The home marker and boundary circle make your search area visible.
- The plant circles scale with annual emissions, which makes the largest local emitter stand out.
- The credit records the source and licence for the emissions data.
- Approve creation of make_map.py.
- Use the file permission request shown in Claude Code to approve this action.
- Approve the local run of make_map.py.
- Use the command permission request shown after Claude finishes writing the file.
You should see Claude report that map.html was saved with the number of ranked plants.
Before you open the map, which plant do you expect to have the largest circle?
macOS
- Open map.html in your default browser by running this command:
open map.html
What does this command do?
The open command sends map.html to the default app for HTML files. Your browser then loads the interactive map.
Windows
- Open map.html in your default browser by running this command:
start map.html
What does this command do?
The start command opens map.html with its associated app. Your browser then loads the interactive map.
You should see your home marker inside a blue 50 km boundary. The nearby plants should appear as red circles with the rank-1 plant shown as the largest circle.
Map not opening?
- Confirm Claude finished running make_map.py and reported that map.html was saved.
- Confirm your terminal still points to the my-carbon-neighbours folder before running the browser command.
Help me diagnose why my generated map is not opening.
Compare the map with the live Explore view
Your table and map both call load_ranked_nearby(). That shared function keeps the distance filter and emissions ranking consistent across both views.
- Return to the terminal output from near_me.py.
- Record the rank-1 plant name here: your rank-1 plant name.
- Return to map.html in your browser.
- Open the rank-1 plant popup.
- Select the largest red plant circle to open its popup.
- Confirm the popup name matches your rank-1 plant name.
- Compare a closer lower-ranked plant's circle with the rank-1 circle.
You should see the closer lower-ranked plant remain smaller because circle size follows annual emissions instead of distance.
One Ranking Across Every View
Distance decides which plants enter the 50 km result. Annual emissions decide their rank and circle size.
- Open Climate TRACE Explore in your browser.
- Set the visible map year to 2025.
- Use the year control currently shown in the Explore interface.
- Set the visible sector to power.
- Use the sector control currently shown in the Explore interface.
- Set the visible subsector to electricity generation.
- Use the subsector control currently shown in the Explore interface.
- Find your rank-1 plant name on the Explore map.
- Use the visible search or map controls to locate the plant by name.
You should find the same top-ranked plant represented in the live Climate TRACE view.
Check metadata and print monthly emissions
The metadata endpoint returns JSON describing the current data release. Its temporalCoverage.end value gives you a live freshness checkpoint for the monthly series.
- Ask Claude Code to inspect the live metadata by pasting this exact message:
Call https://api.climatetrace.org/v7/metadata and tell me the data version, the release date and the last month of data.
What does this request check?
Claude reads the current data version and release date from the metadata response. The last month comes from temporalCoverage.end, which lets you test the monthly output against live coverage.
- Approve the read-only metadata request.
- Use the network permission request shown in Claude Code to approve this action.
Claude should report the current data version, the release date, and the final month covered by the dataset.
- Record the reported temporalCoverage.end value here: the temporalCoverage.end month.
The next script reuses the first item from your emissions-ranked nearby list. This keeps the monthly lookup tied to the same plant shown at rank 1 in your table and map.
- Ask Claude Code to create the monthly lookup by pasting this exact message:
Write plant_months.py. Take the id of the top plant in my table and call https://api.climatetrace.org/v7/sources/{id} with start=2025, end=2026 and timeGranularity=month. Print the plant name and its monthly emissions through the latest available month. Then run it.
What does this prompt ask Claude to do?
- The script takes nearby[0] as the top annual emitter inside the 50 km filter.
- It requests monthly source details for that plant across 2025 and 2026.
- It sorts the monthly rows chronologically before printing them.
- Approve creation of plant_months.py.
- Use the file permission request shown in Claude Code to approve this action.
- Approve the read-only Climate TRACE source request.
- Use the network permission request shown after Claude identifies the top plant.
- Approve the local run of plant_months.py.
You should see the top plant's name followed by monthly emissions rows in chronological order.
- Return to map.html in your browser.
- Confirm the largest plant circle still matches your rank-1 plant name.
Before you run the final check, do you expect the last printed month to match the live metadata coverage?
macOS
- Run the monthly lookup again by using this command:
python3 plant_months.py
What does this command do?
Python runs plant_months.py inside your active virtual environment. The script requests and prints the top nearby plant's monthly series.
Windows
- Run the monthly lookup again by using this command:
python plant_months.py
What does this command do?
Python runs plant_months.py inside your active virtual environment. The script requests and prints the top nearby plant's monthly series.
You should see the monthly rows end at the temporalCoverage.end month.
Final Months Do Not Match?
- Ask Claude to inspect the source response before making a freshness claim.
- Check that months is sorted by year and month before it is printed.
Help me compare my source response with the live metadata coverage.
✔️ Awesome, I've got everything!
Great. Confirm that make_map.py and plant_months.py are saved inside my-carbon-neighbours.
ⓧ I'd like to double check the full code
- Compare find_me.py with this complete reference:
import json
import pycountry
import requests
GEOCODING_URL = "https://geocoding-api.open-meteo.com/v1/search"
def main():
town = input("Town or place name: ").strip()
if not town:
raise SystemExit("Enter a town or place name.")
response = requests.get(
GEOCODING_URL,
params={"name": town, "count": 5, "language": "en", "format": "json"},
timeout=30,
)
response.raise_for_status()
results = response.json().get("results") or []
if not results:
raise SystemExit("No matches found. Try Town, Country.")
for index, result in enumerate(results, start=1):
country = result.get("country", "Unknown country")
admin1 = result.get("admin1")
region = f", {admin1}" if admin1 else ""
print(f"{index}. {result['name']}{region}, {country}")
while True:
try:
choice = int(input(f"Choose 1-{len(results)}: "))
selected = results[choice - 1]
break
except (ValueError, IndexError):
print("Choose one of the listed numbers.")
country = pycountry.countries.get(alpha_2=selected["country_code"])
if country is None:
raise SystemExit("Could not convert the two-letter country code.")
home = {
"name": selected["name"],
"country": selected.get("country", country.name),
"latitude": selected["latitude"],
"longitude": selected["longitude"],
"country_code": country.alpha_3,
}
with open("home.json", "w", encoding="utf-8") as file:
json.dump(home, file, indent=2, ensure_ascii=False)
print(
f"Saved {home['name']}, {home['country']} "
f"({home['latitude']}, {home['longitude']}) as {home['country_code']}."
)
if __name__ == "__main__":
main()
What Should This File Contain?
This reference contains the completed location search and ISO country-code conversion from earlier. It remains unchanged in this step.
- Compare get_plants.py with this complete reference:
import json
import requests
SOURCES_URL = "https://api.climatetrace.org/v7/sources"
def main():
with open("home.json", encoding="utf-8") as file:
home = json.load(file)
response = requests.get(
SOURCES_URL,
params={
"year": 2025,
"gadmId": home["country_code"],
"sectors": "power",
"subsectors": "electricity-generation",
"limit": 1000,
},
timeout=30,
)
response.raise_for_status()
plants = response.json() or []
if not isinstance(plants, list):
raise SystemExit("Climate TRACE returned an unexpected response.")
plants.sort(key=lambda plant: plant.get("emissionsQuantity") or 0, reverse=True)
with open("plants.json", "w", encoding="utf-8") as file:
json.dump(plants, file, indent=2, ensure_ascii=False)
print(f"Saved {len(plants)} plants to plants.json.")
print("Three largest 2025 emitters:")
for rank, plant in enumerate(plants[:3], start=1):
tonnes = plant.get("emissionsQuantity") or 0
print(f"{rank}. {plant.get('name', 'Unknown')}: {tonnes:,.0f} tonnes")
if __name__ == "__main__":
main()
What Should This File Contain?
This reference contains the completed national source request and descending emissions sort. It remains unchanged in this step.
- Compare near_me.py with this complete reference:
import json
from math import asin, cos, radians, sin, sqrt
RADIUS_KM = 50
EARTH_RADIUS_KM = 6371.0
def haversine_km(latitude1, longitude1, latitude2, longitude2):
lat1 = radians(latitude1)
lon1 = radians(longitude1)
lat2 = radians(latitude2)
lon2 = radians(longitude2)
delta_lat = lat2 - lat1
delta_lon = lon2 - lon1
value = (
sin(delta_lat / 2) ** 2
+ cos(lat1) * cos(lat2) * sin(delta_lon / 2) ** 2
)
return 2 * EARTH_RADIUS_KM * asin(sqrt(value))
def load_ranked_nearby():
with open("home.json", encoding="utf-8") as file:
home = json.load(file)
with open("plants.json", encoding="utf-8") as file:
plants = json.load(file)
nearby = []
for plant in plants:
centroid = plant.get("centroid") or {}
latitude = centroid.get("latitude")
longitude = centroid.get("longitude")
if latitude is None or longitude is None:
continue
distance = haversine_km(
home["latitude"],
home["longitude"],
latitude,
longitude,
)
if distance <= RADIUS_KM:
ranked_plant = dict(plant)
ranked_plant["distanceKm"] = distance
nearby.append(ranked_plant)
nearby.sort(
key=lambda plant: plant.get("emissionsQuantity") or 0,
reverse=True,
)
return home, nearby
def main():
home, nearby = load_ranked_nearby()
print(f"Power plants within {RADIUS_KM} km of {home['name']}: {len(nearby)}")
print(f"{'Rank':<5} {'Plant':<40} {'Fuel':<22} {'Tonnes':>14} {'Km':>8}")
print("-" * 95)
for rank, plant in enumerate(nearby, start=1):
name = plant.get("name", "Unknown")[:40]
fuel = (plant.get("assetType") or "unknown")[:22]
tonnes = plant.get("emissionsQuantity") or 0
distance = plant["distanceKm"]
print(f"{rank:<5} {name:<40} {fuel:<22} {tonnes:>14,.0f} {distance:>8.1f}")
if __name__ == "__main__":
main()
What Should This File Contain?
This reference contains the trusted 50 km filter and descending emissions ranking. The two new scripts import its shared result instead of rebuilding the calculation.
- Compare make_map.py with this complete reference:
from html import escape
from math import sqrt
import folium
from near_me import RADIUS_KM, load_ranked_nearby
def main():
home, nearby = load_ranked_nearby()
if not nearby:
raise SystemExit("No power plants were found within 50 km.")
location = [home["latitude"], home["longitude"]]
map_ = folium.Map(location=location, zoom_start=9, control_scale=True)
folium.Marker(
location=location,
tooltip="Home",
popup=f"{escape(home['name'])}, {escape(home['country'])}",
).add_to(map_)
folium.Circle(
location=location,
radius=RADIUS_KM * 1000,
color="#2563eb",
weight=2,
fill=False,
tooltip="50 km boundary",
).add_to(map_)
maximum = max(plant.get("emissionsQuantity") or 0 for plant in nearby) or 1
for rank, plant in enumerate(nearby, start=1):
tonnes = plant.get("emissionsQuantity") or 0
marker_radius = 5 + 20 * sqrt(tonnes / maximum)
centroid = plant["centroid"]
popup = (
f"<b>Rank {rank}: {escape(plant.get('name', 'Unknown'))}</b><br>"
f"Fuel: {escape(plant.get('assetType') or 'unknown')}<br>"
f"Annual emissions: {tonnes:,.0f} tonnes CO2e<br>"
f"Distance: {plant['distanceKm']:.1f} km"
)
folium.CircleMarker(
location=[centroid["latitude"], centroid["longitude"]],
radius=marker_radius,
color="#991b1b",
weight=1,
fill=True,
fill_color="#dc2626",
fill_opacity=0.65,
tooltip=f"#{rank} {plant.get('name', 'Unknown')}",
popup=popup,
).add_to(map_)
credit_html = """
<div style="position: fixed; bottom: 28px; left: 8px; z-index: 9999;
background: white; padding: 4px 7px; border: 1px solid #777;
border-radius: 3px; font-size: 11px;">
Emissions data: <a href="https://climatetrace.org/terms" target="_blank">Climate TRACE</a> (CC BY 4.0)
</div>
"""
map_.get_root().html.add_child(folium.Element(credit_html))
map_.save("map.html")
print(f"Saved map.html with {len(nearby)} ranked plants.")
if __name__ == "__main__":
main()
What Should This File Contain?
This reference contains the home marker, 50 km boundary, proportional plant symbols, popup details, and Climate TRACE credit. The largest annual emitter receives the largest plant circle.
- Compare plant_months.py with this complete reference:
import requests
from near_me import load_ranked_nearby
SOURCE_URL = "https://api.climatetrace.org/v7/sources/{id}"
def main():
_, nearby = load_ranked_nearby()
if not nearby:
raise SystemExit("No nearby plant is available for the monthly lookup.")
top_plant = nearby[0]
response = requests.get(
SOURCE_URL.format(id=top_plant["id"]),
params={
"start": 2025,
"end": 2026,
"timeGranularity": "month",
"gas": "co2e_100yr",
},
timeout=30,
)
response.raise_for_status()
details = response.json()
months = details.get("emissions") or []
months.sort(key=lambda row: (row["year"], row.get("month") or 0))
print(f"Monthly emissions for {details.get('name', top_plant['name'])}:")
for row in months:
tonnes = row.get("emissionsQuantity") or 0
print(f"{row['year']}-{row['month']:02d}: {tonnes:,.0f} tonnes CO2e")
if __name__ == "__main__":
main()
What Should This File Contain?
This reference selects the top nearby plant, requests its monthly details, sorts the rows chronologically, and prints each available month.
Secret mission
Fix the Cross-Border Blind Spot
Your 50 km circle can cross a national border even when your source data stops at that border. Extend the retrieval logic so every requested country is paginated before the local distance filter decides which plants belong on your map.
Clean Up Your Resources
Clean Up Your Resources
Your carbon-neighbour finder runs entirely on your computer. The public API calls created no paid resources or cloud infrastructure.
Choose whether to keep your files, pause the two active sessions, or delete the whole folder.
Resources you used:
- The local my-carbon-neighbours folder.
- The .venv Python virtual environment inside the project folder.
- Five Python scripts: find_me.py, get_plants.py, near_me.py, make_map.py, and plant_months.py.
- Three generated artifacts: home.json, plants.json, and map.html.
Keep everything running
No action needed. Choose this if you plan to refresh the emissions data or experiment with the ranking later.
- Leave your Claude Code session open while you continue working.
- Keep .venv active while you rerun the scripts.
- Leave my-carbon-neighbours in place so the scripts and generated map remain available.
Pause - I'll come back to this later
Close Claude Code to pause your work. Leave the virtual environment to return your terminal to its normal state.
- Leave Claude Code by entering this command:
exit
What does this command do?
The exit command closes the current Claude Code session. Your files remain unchanged.
- Leave .venv by entering this command:
deactivate
What does this command do?
The deactivate command leaves the active virtual environment. It keeps .venv and its installed packages available for later.
You return to your normal terminal prompt. Every file inside my-carbon-neighbours remains available.
Delete - I don't want to use this again
Remove every local project resource by deleting my-carbon-neighbours. Your public API requests created no remote resources that need separate deletion.
- Leave Claude Code by entering this command:
exit
What does this command do?
The exit command returns you to the terminal. Your .venv environment remains active.
- Leave .venv by entering this command:
deactivate
What does this command do?
The deactivate command ends the active virtual environment session. The .venv folder remains in place until you delete the project.
- Move to the parent directory that contains my-carbon-neighbours in your terminal.
- Confirm the folder name is exactly my-carbon-neighbours.
macOS
Deleting the folder is permanent, so take a moment to confirm its name before you run the removal command.
- Delete my-carbon-neighbours by running this command:
rm -rf my-carbon-neighbours
What does this command do?
This command recursively removes my-carbon-neighbours. It deletes .venv with all five scripts and the three generated artifacts.
You should return to the terminal prompt without an error. The complete my-carbon-neighbours folder is removed.
Still See the Folder?
- Return to the directory that contains my-carbon-neighbours.
- Check that the folder name matches the command exactly.
Help me safely check why my project folder remains.
Windows
Deleting the folder is permanent, so take a moment to confirm its name before you run the removal command.
- Delete my-carbon-neighbours by running this command:
Remove-Item -Recurse -Force my-carbon-neighbours
What does this command do?
This command recursively removes my-carbon-neighbours. It deletes .venv with all five scripts and the three generated artifacts.
You should return to the PowerShell prompt without an error. The complete my-carbon-neighbours folder is removed.
Still See the Folder?
- Return to the directory that contains my-carbon-neighbours.
- Close any app that still has a project file open.
Help me safely check why my project folder remains.
Nice Work!
Nice Work!
You did it! Your Claude Code project now ranks the biggest power-plant emitters within 50 km of your chosen town.
You've learned how to:
- Build a town picker backed by the Open-Meteo Geocoding API. Save the chosen coordinates plus an ISO alpha-3 country code in home.json.
- Retrieve 2025 power-plant emissions from the Climate TRACE API as JSON. Use Haversine distance to keep plants within 50 km. Rank those local records by annual emissions.
- Generate an interactive map with proportional symbols that reveal the emissions ranking. Check temporal coverage before interpreting the top plant's monthly emissions series.
- Complete the optional Secret Mission by adding cross-border retrieval for neighboring countries. Use pagination with limit=1000 plus increasing offset values for every requested country. De-duplicate merged sources by id before the unchanged 50 km filter runs.
Ready to quiz yourself?