Here is a simple Python program using the OpenWeatherMap API to check the current weather of a city:
```
import requests
import json
def get_weather(city, api_key):
base_url = "http://api.openweathermap.org/data/2.5/weather"
params = {
"q": city,
"units": "metric",
"appid": api_key
}
response = requests.get(base_url, params=params)
weather_data = response.json()
return weather_data
def print_weather(weather_data):
city = weather_data["name"]
country = weather_data["sys"]["country"]
temperature = weather_data["main"]["temp"]
humidity = weather_data["main"]["humidity"]
weather_description = weather_data["weather"][0]["description"]
print(f"Weather in {city}, {country}:")
print(f"Temperature: {temperature}°C")
print(f"Humidity: {humidity}%")
print(f"Weather: {weather_description}")
def main():
api_key = "YOUR_OPENWEATHERMAP_API_KEY"
city = input("Enter the city name: ")
weather_data = get_weather(city, api_key)
print_weather(weather_data)
if __name__ == "__main__":
main()
```
To use this program, you need to:
1. Get an API key from OpenWeatherMap (https://home.openweathermap.org/users/sign_up)
2. Replace `YOUR_OPENWEATHERMAP_API_KEY` with your actual API key
3. Run the program and enter the city name when prompted
Note: This program uses the metric system for temperature. If you prefer Fahrenheit, change the `"units"` parameter in the `get_weather` function to `"imperial"`.
For mobile devices, you can create a mobile app using a framework like React Native or Flutter, and use the same API to fetch the weather data.
To get the current location of the device, you can use the Geolocation API (https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API) in JavaScript or the equivalent API in your chosen mobile app framework.
Here's an example of how to use the Geolocation API to get the current location:
```
navigator.geolocation.getCurrentPosition(position => {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
// Use the latitude and longitude to fetch the weather data
});
```
No comments:
Post a Comment