How to Find the Nearest Port to Any Coastal Place
On this page
Problem statement
How far is a city from the sea, measured to its nearest port? With the World Port Index's 3,807 positions and Natural Earth's 7,342 populated places, the answer for every place is one nearest-neighbour query on the sphere. Distances between latitude-longitude points need the haversine metric, not planar distance in degrees, and a straight line to the nearest port is not a route by sea or road. This page computes great-circle distances with a BallTree, finds the large cities farthest from any port, measures how much of the world's urban population lives near one, and compares the nearest port with the nearest large one.
Quick answer
Build a BallTree on the ports in radians with the haversine metric and query every place:
from sklearn.neighbors import BallTree
places = gpd.read_file("data/ne_10m_populated_places_simple.zip")[["name", "adm0name", "pop_max", "latitude", "longitude"]]
tree = BallTree(np.radians(ports[["Latitude", "Longitude"]].values), metric="haversine")
dist, idx = tree.query(np.radians(places[["latitude", "longitude"]].values), k=1)
places["km"] = dist[:, 0] * 6371.0088
places["port"] = ports["Main Port Name"].values[idx[:, 0]]
print(f"places: {len(places):,}; median distance to the nearest port {places.km.median():.0f} km")
print(places.nlargest(3, "pop_max")[["name", "adm0name", "pop_max", "port", "km"]].round(1).to_string(index=False))
places: 7,342; median distance to the nearest port 190 km
name adm0name pop_max port km
Tokyo Japan 35676000 Tokyo Ko 2.3
New York United States of America 19040000 Hoboken 2.9
Mexico City Mexico 19028000 Tuxpan 246.4
Across the 7,342 places the median distance to the nearest port is 190 km. The largest cities are on the water: Tokyo is 2.3 km from Tokyo Ko and New York 2.9 km from Hoboken. Mexico City, the third largest place in the file, is 246.4 km from Tuxpan, on the Gulf coast.
Far cities, near people and large ports
1. The largest cities far from a port
big = places[places.pop_max >= 1_000_000]
print(big.nlargest(6, "km")[["name", "adm0name", "pop_max", "port", "km"]].round(0).to_string(index=False))
name adm0name pop_max port km
Ürümqi China 3575000 Calcutta 2365.0
Almaty Kazakhstan 1209000 Muhamamad Bin Qasim 2240.0
Tashkent Uzbekistan 2184000 Muhamamad Bin Qasim 1849.0
Omsk Russia 1135000 Igarka 1548.0
Dushanbe Tajikistan 1086244 Muhamamad Bin Qasim 1540.0
Chelyabinsk Russia 1091000 Mezen 1507.0
Among cities of a million people or more, Ürümqi in western China is the farthest from any port, 2,365 km, with Calcutta its nearest, then Almaty, Tashkent, Omsk, Dushanbe and Chelyabinsk, all over 1,500 km. Central Asia is the most landlocked part of the world, and the nearest port for several of its capitals is Muhammad Bin Qasim near Karachi, spelled "Muhamamad" in the index.
2. People by distance to a port
band = pd.cut(places.km, [0, 25, 100, 500, 1000, 5000])
print((places.groupby(band).pop_max.sum() / places.pop_max.sum()).round(3).to_string())
km
(0, 25] 0.384
(25, 100] 0.131
(100, 500] 0.313
(500, 1000] 0.117
(1000, 5000] 0.055
Weighted by each place's population, 38.4% of the people in Natural Earth's places live within 25 km of a port and another 13.1% within 100 km. 31.3% live between 100 and 500 km away, and 5.5% more than 1,000 km. Half the urban world is within 100 km of a port in the index.
3. Only ports that can take large ships
lg = ports[ports["Harbor Size"].isin(["Large", "Medium"])].reset_index(drop=True)
t2 = BallTree(np.radians(lg[["Latitude", "Longitude"]].values), metric="haversine")
d2, i2 = t2.query(np.radians(places[["latitude", "longitude"]].values), k=1)
places["km_large"] = d2[:, 0] * 6371.0088
print(f"median distance to a medium or large port: {places.km_large.median():.0f} km; to any port: {places.km.median():.0f} km")
median distance to a medium or large port: 377 km; to any port: 190 km
Counting only medium and large ports, the median distance doubles, from 190 km to 377 km. A small fishing harbour is near almost everywhere on a coast; a port that can take ocean freight is not.
A straight line is not a sea route
The data used on this page
The US National Geospatial-Intelligence Agency's World Port Index (Pub. 150), the CSV served by its Maritime Safety Information site, downloaded on 28 October 2026 and saved on this site, because NGA revises the index as port information changes. A US government publication, free to use. Depths and lengths are in metres. Countries, land and populated places are Natural Earth's, public domain.
from pathlib import Path
import zipfile
import geopandas as gpd
import numpy as np
import pandas as pd
import requests
Path("data").mkdir(exist_ok=True)
# NGA's World Port Index (Pub. 150) as CSV, with Natural Earth's populated places, countries and land. Saved
# 28 October 2026: NGA revises the index as port information changes.
# Live: https://msi.nga.mil/api/publications/download?type=view&key=16920959/SFH00000/UpdatedPub150.csv
ARCHIVE = "nga-world-port-index-2026-10-28.zip"
if not Path(f"data/{ARCHIVE}").exists():
Path(f"data/{ARCHIVE}").write_bytes(requests.get(f"https://data.spatialworkflow.io/{ARCHIVE}", timeout=600).content)
Z = zipfile.ZipFile(f"data/{ARCHIVE}")
for f in ["ne_10m_populated_places_simple.zip", "ne_110m_admin_0_countries.zip", "ne_50m_land.zip"]:
Path(f"data/{f}").write_bytes(Z.read(f))
wpi = pd.read_csv(Z.open("UpdatedPub150.csv"), encoding="utf-8-sig")
wpi = wpi.replace(r"^\s*$", np.nan, regex=True) # blank cells are a single space
DEPTHS = [c for c in wpi.columns if c.endswith("(m)")]
wpi[DEPTHS] = wpi[DEPTHS].where(wpi[DEPTHS] > 0) # 0 means not recorded
ports = gpd.GeoDataFrame(wpi, geometry=gpd.points_from_xy(wpi.Longitude, wpi.Latitude), crs=4326)
print(f"World Port Index: {len(ports):,} ports in {ports['Country Code'].nunique()} countries and territories")
World Port Index: 3,807 ports in 195 countries and territories
Example 1: a straight line is not a sea route
x = places[places.name.isin(["Chicago", "Denver", "Kampala", "Kabul", "Ulaanbaatar"])]
print(x[["name", "port", "km", "km_large"]].round(0).to_string(index=False))
name port km km_large
Kampala Kilifi 921.0 926.0
Ulaanbaatar Dagu Tanggu 1318.0 1327.0
Denver Tri-City Port 1277.0 1277.0
Chicago Chicago 14.0 14.0
Kabul Muhamamad Bin Qasim 1099.0 1103.0
The nearest port by straight line can be absurd. Chicago's nearest is Chicago, 14 km away, but that is a Great Lakes port reached by the St. Lawrence Seaway. Denver's nearest is a river port 1,277 km away, Kampala's is Kilifi on the Kenyan coast at 921 km, Kabul's is near Karachi at 1,099 km, and Ulaanbaatar's is Tianjin's Dagu Tanggu at 1,318 km. For trade, the question is the route, by rail or road, which a straight-line distance cannot answer.
Internal links
- Find the nearest coordinates with a BallTree — the method in general
- Ports by country — the ports themselves
- Distance to the nearest hospital — the same question on land
- Haversine distance — why distances on the sphere need it