tombdev
tombdev

Reputation: 25

How can i use city name instead of lat and log in OpenWeather API?

Good evening!

So basically I want to get weather data from OpenWeather API. Previously I used a different API from this site and there I could use city name to get weather data. Now I want to use a more attractive API from this site where is hourly, daily weather info so this is 100% what I want in my weather app but here I can't use city name? I need to place lat and long inside URL. So how can I do that?

import React from "react";

const KEY = "SECRET";
const city = "London";
const exclude = "daily";

const App = () => {
  const fetchData = async () => {
    const response = await fetch(
      `https://api.openweathermap.org/data/2.5/onecall?q=${city}&exclude=${exclude}&appid=${KEY}`
    );
    const data = await response.json();
    console.log(data);
  };
  return (
    <div>
      <h1>Weather App</h1>
      <button onClick={fetchData}>FETCH</button>
    </div>
  );
};

export default App;

Upvotes: 2

Views: 18690

Answers (2)

Deepak Kadarivel
Deepak Kadarivel

Reputation: 189

That is how One Call API is built.

7 days or n days forecast is not directly available for city[name / id]. You have to use lat and lon query params.


Solution:

You will need to make 2 API calls. Use the lat, lon value from the first API to call the second API.

Step 1: ref: Link

https://api.openweathermap.org/data/2.5/weather?q={city name}&appid={API key}

This will return current weather data for the city with lat, lon values.

Step 2: ref Link

https://api.openweathermap.org/data/2.5/onecall?lat={lat}&lon={lon}&exclude={part}&appid={API key}

This will give the hourly forecast for the previous 5 days and the next 7 days.


Limitation:

  1. You call 2 API's
  2. One Call API returns an hourly forecast for the first 48 hours only.

Alternative

There is a forecast API.

  1. Hourly forecast for 4 days. Link
  2. 3 Hour forecast for 5 days. Link

Upvotes: 3

bog
bog

Reputation: 59

OpenWeather has access to data by name and/or geographic coordinates (lat/lon):

name:

api.openweathermap.org/data/2.5/weather?q={city name}&appid={API key}

geo:

api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={API key}

You can find the docs here

Upvotes: 2

Related Questions