Skip to main content

Use geographic coordinates

Querying OpenWeatherMap endpoints with lat and lon eliminates duplicate-city ambiguity and uses OpenWeatherMap's primary coordinate lookup path instead of legacy name matching.

Resolve a city name to coordinates​

When a user searches for a city, resolve the text query to coordinates with Geocoding API 1.0 (/geo/1.0/direct) first, validate the response, and pass lat and lon to /data/2.5/weather:

Always check both the HTTP status code and whether the parsed JSON body is a non-empty array before reading geoData[0]:

  • An invalid API key returns HTTP 401 with a JSON object ({"cod": 401, ...}), where geoData.length is undefined.
  • An unrecognized place name returns HTTP 200 with an empty JSON array ([]).
# Step 1: Resolve "Paris,FR" to latitude and longitude
curl --get "https://api.openweathermap.org/geo/1.0/direct" \
--data-urlencode "q=Paris,FR" \
--data-urlencode "limit=1" \
--data-urlencode "appid=$OPENWEATHER_API_KEY"

# Step 2: Query current weather with the returned coordinates
curl --get "https://api.openweathermap.org/data/2.5/weather" \
--data-urlencode "lat=48.8588897" \
--data-urlencode "lon=2.3200410217200766" \
--data-urlencode "units=metric" \
--data-urlencode "appid=$OPENWEATHER_API_KEY"
Cache resolved coordinates aggressively

City coordinates don't change. Cache /geo/1.0/direct lookups by normalized query string for days or weeks so repeat searches consume only a single weather API call.

Convert coordinates to a place name​

When your application starts from raw GPS or map-pin coordinates and needs a human-readable locality label, query the reverse geocoding endpoint (/geo/1.0/reverse) with lat, lon, and limit=1:

curl --get "https://api.openweathermap.org/geo/1.0/reverse" \
--data-urlencode "lat=35.6895" \
--data-urlencode "lon=139.6917" \
--data-urlencode "limit=1" \
--data-urlencode "appid=$OPENWEATHER_API_KEY"

Pass browser coordinates through your backend​

In web applications, you can read the user's coordinates from the browser Geolocation API (navigator.geolocation.getCurrentPosition) without asking them to type a city name.

Keep your API key on the server

Never call api.openweathermap.org directly from client-side browser code. Any key bundled into frontend JavaScript or sent from browser network requests is visible to every visitor. Send lat and lon to your own backend endpoint, and attach OPENWEATHER_API_KEY on the server.

Capture coordinates in the browser and forward them to your own backend route (/api/weather):

function loadLocalWeather(onSuccess, onFallbackRequired) {
if (!('geolocation' in navigator)) {
onFallbackRequired('Browser geolocation is unavailable.');
return;
}

navigator.geolocation.getCurrentPosition(
async (position) => {
try {
const params = new URLSearchParams({
lat: position.coords.latitude.toFixed(4),
lon: position.coords.longitude.toFixed(4),
});

// Send coordinates to your own backend proxy rather than OpenWeatherMap directly
const response = await fetch(`/api/weather?${params}`, {
signal: AbortSignal.timeout(10000),
});

if (!response.ok) {
throw new Error(`Backend weather route returned HTTP ${response.status}`);
}

const weather = await response.json();
onSuccess(weather);
} catch (error) {
onFallbackRequired(error.message);
}
},
(geoError) => {
onFallbackRequired(`Location permission declined or timed out (${geoError.message}).`);
},
{ enableHighAccuracy: false, timeout: 8000, maximumAge: 600000 }
);
}

Rounding latitude and longitude to 2–4 decimal places before calling /api/weather improves privacy and increases cache hit rates across nearby users. To build the /api/weather server route with bounded caching, see Set up rate limiting and caching.

Provide a manual search fallback

Users frequently decline browser location prompts. Pair geolocation with a city-search input backed by /geo/1.0/direct on your server so users can always select a location manually.