Weather triggers
Содержание:
Google Weather-Based Campaign Management with OpenWeatherMap API
Demand for certain products and services varies greatly depending on the weather. For example, users are much more likely to search for information on amusement parks on a hot, sunny day than if it’s cold and raining. An amusement park company may want to increase their bids when the weather is nice, but doing so every day would require a lot of manual work. With AdWords scripts, however, it’s possible to programmatically fetch weather information and adjust bids in a matter of minutes.
This script uses Google Spreadsheets to store the list of campaigns and their associated locations. A call to the OpenWeatherMap API is made for each location and weather conditions are calculated using some basic rules. If a rule evaluates to true, then a corresponding location bid multiplier is applied to the location targeting for the campaign.
Подробная информация о погоде
| Атмосферные явления температура °C | Ощущается как °C | Вероятностьосадков % | Давлениемм.рт.ст. | Скоростьветра м/с | Влажностьвоздуха | Температураводы °C |
|---|---|---|---|---|---|---|
|
среда, 02 сентября |
||||||
|
Утро
+22° |
+25° | 69% | 764 |
6 |
80% | +23° |
| Местами дождь | ||||||
|
День
+24° |
+26° | 75% | 762 |
5 |
72% | +25° |
| Местами дождь | ||||||
|
Вечер
+23° |
+25° | 79% | 762 |
5 |
78% | +24° |
| Местами дождь | ||||||
|
Ночь
+22° |
+25° | 74% | 764 |
6 |
77% | +22° |
| Моросящий дождь |
| Атмосферные явления температура °C | Ощущается как °C | Вероятностьосадков % | Давлениемм.рт.ст. | Скоростьветра м/с | Влажностьвоздуха | Температураводы °C |
|---|---|---|---|---|---|---|
|
четверг, 03 сентября |
||||||
|
Утро
+22° |
+25° | 0% | 762 |
2 |
79% | +23° |
| Переменная облачность | ||||||
|
День
+23° |
+25° | 74% | 762 |
4 |
76% | +23° |
| Моросящий дождь | ||||||
|
Вечер
+22° |
+25° | 82% | 762 |
6 |
66% | +22° |
| Местами дождь | ||||||
|
Ночь
+23° |
+25° | 65% | 762 |
3 |
80% | +23° |
| Местами дождь |
| Атмосферные явления температура °C | Ощущается как °C | Вероятностьосадков % | Давлениемм.рт.ст. | Скоростьветра м/с | Влажностьвоздуха | Температураводы °C |
|---|---|---|---|---|---|---|
|
пятница, 04 сентября |
||||||
|
Утро
+20° |
+20° | 0% | 762 |
6 |
70% | +21° |
| Ясно | ||||||
|
День
+23° |
+25° | 79% | 761 |
7 |
66% | +23° |
| Местами дождь | ||||||
|
Вечер
+22° |
+22° | 0% | 761 |
7 |
69% | +22° |
| Переменная облачность | ||||||
|
Ночь
+20° |
+20° | 0% | 762 |
5 |
73% | +20° |
| Переменная облачность |
| Атмосферные явления температура °C | Ощущается как °C | Вероятностьосадков % | Давлениемм.рт.ст. | Скоростьветра м/с | Влажностьвоздуха | Температураводы °C |
|---|---|---|---|---|---|---|
|
суббота, 05 сентября |
||||||
|
Утро
+21° |
+21° | 61% | 761 |
7 |
76% | +22° |
| Местами дождь | ||||||
|
День
+23° |
+25° | 59% | 761 |
6 |
68% | +23° |
| Местами дождь | ||||||
|
Вечер
+22° |
+22° | 0% | 761 |
7 |
71% | +22° |
| Переменная облачность | ||||||
|
Ночь
+21° |
+21° | 64% | 762 |
6 |
73% | +21° |
| Местами дождь |
| Атмосферные явления температура °C | Ощущается как °C | Вероятностьосадков % | Давлениемм.рт.ст. | Скоростьветра м/с | Влажностьвоздуха | Температураводы °C |
|---|---|---|---|---|---|---|
|
воскресенье, 06 сентября |
||||||
|
Утро
+22° |
+22° | 62% | 762 |
8 |
74% | +23° |
| Местами дождь | ||||||
|
День
+23° |
+25° | 0% | 763 |
7 |
71% | +23° |
| Переменная облачность | ||||||
|
Вечер
+23° |
+25° | 0% | 764 |
8 |
78% | +22° |
| Переменная облачность | ||||||
|
Ночь
+22° |
+22° | 55% | 762 |
9 |
77% | +21° |
| Местами дождь |
| Атмосферные явления температура °C | Ощущается как °C | Вероятностьосадков % | Давлениемм.рт.ст. | Скоростьветра м/с | Влажностьвоздуха | Температураводы °C |
|---|---|---|---|---|---|---|
|
понедельник, 07 сентября |
||||||
|
Утро
+23° |
+25° | 88% | 764 |
10 |
81% | +22° |
| Умеренный или сильный ливень | ||||||
|
День
+24° |
+26° | 77% | 764 |
9 |
77% | +22° |
| Моросящий дождь | ||||||
|
Вечер
+23° |
+25° | 70% | 765 |
9 |
79% | +22° |
| Местами дождь | ||||||
|
Ночь
+23° |
+25° | 81% | 764 |
7 |
82% | +24° |
| Местами дождь |
Libraries to connect weather layers
Open Layers
The following functions are available for the OpenLayers library:
- Classes of weather layer and weather stations layer
- Possibility to set your own style
- Classes with clustered markers
- Support of marker server clustering
Leaflet
The OpenWeatherMap javascript library is designed to work with the Leaflet mapping service. The current version of the library allows the following:
- Embedding of layer with current weather in cities
- Embedding of layer with weather stations
- The library supports customer clustering
Leaflet library
Another implementation of map based on Leaflet technology supports OWM’s TileLayers and current city/station data. It is configurable with many options. For current city/station data the library supports refreshing the data in intervals, some types of client-side clustering (show only the station/city with the highest rank for a defined pixel square), custom image set (if you provide one), different languages («en», «de», «ru», «fr», but translation is incomplete), minZoom and others.
Source and documentation (README.md) is available on GitHub https://github.com/buche/leaflet-openweathermap
Example of weather map: https://github.com/owm-inc/VANE-intro/tree/master/apps
Коды
""" w_currents.py
Returns current conditions, forecast and alerts for a given zipcode from WeatherUnderground.com.
Usage: python wonderground.py
Options:
-h, --help Show this help
-l, --location City,State to use
-z, --zip Zipcode to use as location
Examples:
w_currents.py -h (shows this help information)
w_currents.py -z 80013 (uses the zip code 80013 as location)
"""
class CurrentInfo:
"""
This routine retrieves the current condition xml data from WeatherUnderground.com
based off of the zip code or Airport Code...
currently tested only with Zip Code and Airport code
For location,
if zip code use something like 80013 (no quotes)
if airport use something like "KDEN" (use double-quotes)
if city/state (US) use something like "Aurora,%20CO" or “Aurora,CO” (use double-quotes)
if city/country, use something like "London,%20England" (use double-quotes)
"""
def getCurrents(self,debuglevel,Location):
pass
def output(self):
pass
def DoIt(self,Location):
pass
#=========================================
# END OF CLASS CurrentInfo()
#=========================================
def usage():
print __doc__
def main(argv):
location = 80013
try:
opts, args = getopt.getopt(argv, "hz:l:", )
except getopt.GetoptError:
usage()
sys.exit(2)
for opt, arg in opts:
if opt in ("-h", "--help"):
usage()
sys.exit()
elif opt in ("-l", "--location"):
location = arg
elif opt in ("-z", "--zip"):
location = arg
print "Location = %s" % location
currents = CurrentInfo()
currents.DoIt(location)
#============================================
# Main loop
#============================================
if __name__ == "__main__":
main(sys.argv)
def getCurrents(self,debuglevel,Location):
if debuglevel > 0:
print "Location = %s" % Location
try:
CurrentConditions = 'http://api.wunderground.com/auto/wui/geo/WXCurrentObXML/index.xml?query=%s' % Location
urllib.socket.setdefaulttimeout(8)
usock = urllib.urlopen(CurrentConditions)
tree = ET.parse(usock)
usock.close()
except:
print 'ERROR - Current Conditions - Could not get information from server...'
if debuglevel > 0:
print Location
sys.exit(2)
# Get Display Location
for loc in tree.findall("//full"):
self.location = loc.text
# Get Observation time
for tim in tree.findall("//observation_time"):
self.obtime = tim.text
# Get Current conditions
for weather in tree.findall("//weather"):
self.we = weather.text
# Get Temp
for TempF in tree.findall("//temperature_string"):
self.tmpB = TempF.text
#Get Humidity
for hum in tree.findall("//relative_humidity"):
self.relhum = hum.text
# Get Wind info
for windstring in tree.findall("//wind_string"):
self.winds = windstring.text
# Get Barometric Pressure
for pressure in tree.findall("//pressure_string"):
self.baroB = pressure.text
<display_location>
<full>Aurora, CO</full>
<city>Aurora</city>
<state>CO</state>
<state_name>Colorado</state_name>
<country>US</country>
<country_iso3166>US</country_iso3166>
<zip>80013</zip>
<latitude>39.65906525</latitude>
<longitude>-104.78105927</longitude>
<elevation>1706.00000000 ft</elevation>
</display_location>
def output(self):
print 'Weather Information From Wunderground.com'
print 'Weather info for %s ' % self.location
print self.obtime
print 'Current Weather - %s' % self.we
print 'Current Temp - %s' % self.tmpB
print 'Barometric Pressure - %s' % self.baroB
print 'Relative Humidity - %s' % self.relhum
print 'Winds %s' % self.winds
Location = 80013
Weather Information From Wunderground.com
Weather info for Aurora, Colorado
Last Updated on May 3, 11:55 AM MDT
Current Weather - Partly Cloudy
Current Temp - 57 F (14 C)
Barometric Pressure - 29.92 in (1013 mb)
Relative Humidity - 25%
Winds From the WNW at 10 MPH
Script terminated.
How to get current, forecast and historical weather maps using only ‘Date’ parameter?
To get current, forecast or historical weather maps you just need to change only parameter in the URL request:
1. Current weather maps. Specify the current date and time and to get Current weather map. The date and time specified in the request will be rounded to the previous 3-hour interval.
2. Forecast weather maps. You can specify any date and time within the next 10 days to get the Forecast weather maps for the specified time. If you do not specify any date and time, you will get Current weather map.
Not available for and layers.
3. Historical weather maps. If you specify any date and time since 18 March 2019, you will receive Historical weather maps for the selected date and time. If you do not specify any date and time, you will get Current weather map.
Conclusion
In this article, we showed how to quickly and easily embed a weather API in our applications (Open Weather Map API in particular) and also explained when it might be useful.
Of course, the capabilities of a weather API are not limited to our example. By collecting the history of weather changes and using the power of machine learning, we can predict the weather on our own. The ability to make our own predictions using machine learning models will be useful in those cases when there is no data available for classical models, and will also enable us to predict the weather not just at the city level, but at the street or even at home level. All we need is historical weather data that can be collected using a lot of weather APIs. But this is a topic for another article.
Historical weather data collection
Historical Weather API
- Through our API we provide city historical weather data for 63,000+ cities
- Historical data is available for 1 month back in Starter account,
for 1 year back in Medium accounts - JSON format
- More opportunities for agriculture in our Agricultural API
Statistical Weather Data API
- Statistical data by main weather parameters for each day and month of the year
- Based on our Historical weather data
- JSON format
- The frequency of weather data update is 1 hour
- Available for Medium and Advanced accounts
- Accumulated temperature and accumulated precipitation
- Accumulated parameters are available for 1 month back in Starter account,
for 1 year back in Medium accounts - JSON format
- More opportunities for agriculture in our Agricultural API
Последние проблемы
animebest.org
(1 ч. 25 м. 56 с. назад)
rutube.ru
(7 ч. 46 м. 56 с. назад)
hydraruzxpnew4af.onion
(8 ч. 9 м. 47 с. назад)
hm.com
(8 ч. 17 м. 21 с. назад)
bestchange.ru
(8 ч. 35 м. 8 с. назад)
perekrestok.ru
(8 ч. 47 м. 31 с. назад)
rzd.ru
(9 ч. 41 м. 5 с. назад)
hydraruzxpnew4af.onion
(10 ч. 37 м. 11 с. назад)
baza-knig.ru
(10 ч. 55 м. 49 с. назад)
baza-knig.ru
(10 ч. 59 м. 18 с. назад)
baza-knig.ru
(11 ч. 27 м. 54 с. назад)
zagonka.tv
(11 ч. 33 м. 6 с. назад)
nvuti.live
(11 ч. 51 м. 35 с. назад)
vip.zagonka.tv
(11 ч. 54 м. 15 с. назад)
loveread.ec
(11 ч. 57 м. 51 с. назад)
vip.zagonka.tv
(12 ч. 11 м. 48 с. назад)
kontur.ru
(12 ч. 17 м. 32 с. назад)
zagonka.tv
(13 ч. 8 м. 28 с. назад)
sdo.rzd.ru
(13 ч. 9 м. 48 с. назад)
vip.zagonka.tv
(13 ч. 23 м. 59 с. назад)
pleer.ru
(13 ч. 29 м. 22 с. назад)
pristavam.net
(13 ч. 30 м. 58 с. назад)
zagonka.tv
(14 ч. 16 м. 3 с. назад)
citilink.ru
(14 ч. 21 м. 30 с. назад)
a22.baza-knig.ru
(14 ч. 22 м. 28 с. назад)
API
OpenWeatherMap использует платный API (есть функционально ограниченный бесплатный доступ), чтобы предоставить данные текущей погоды, прогноза и карт с погодными явлениями, такими как облака, ветер, давление и осадки. Все погодные данные могут быть получены в форматах JSON, XML или HTML.
Текущие погодные данные
Текущие погодные данные могут быть найдены по городу (более 200.000 доступных городов) или географическими координатам. Данные обновляются каждые 10 минут.
Прогнозы
Прогнозы могут быть найдены по городу (более 200.000 доступных городов) или географическими координатам.
OpenWeatherMap предоставляет следующие виды прогнозных данных:
- Минутный прогноз на 1 час
- Часовой прогноз на 4 дня
- Дневной прогноз на 16 дней
- Климатический прогноз на 30 дней
Поиск
Система геокодирования OpenWeatherMap позволяет найти города по названию, стране, почтовому индексу или географическим координатам. Поиск возможен по части имени города. Для того, чтобы результаты поиска были более точными, название города и страны должны быть разделены запятой.
Погодные карты
OpenWeatherMap предоставляет множество карт погоды, включая карты осадков, облачности, атмосферного давления, температуры, ветра и многие другие. Карты могут быть подключены к мобильным приложениям и веб-сайтам. Погодные карты могут быть подключены в качестве слоев для многих поставщиков карт, в том числе статичных тайлов, WMS, OpenLayers, Leaflet, карт Google, и Яндекс карт. Сервис использует карты OpenStreetMap для построения погодных карт.
Meteorological technologies
Meteorological models
VANE platform collects processed weather forecast data. Calculation of the global forecasts require incredible
computing power, and unfortunately we don’t have an IBM Watson (yet). Fortunately many meteorological services
share our love of free data and as a result their data is freely available. We mostly use data from NOAA
GFS model and Environment Canada. These models are global and they see their mission in not a prediction
of specific weather situation at a certain point of land but in determining of the total atmospheric dynamics on the whole planet.
They have a large grid size — about 50 km and longer ranged forecast — 5-7 days. Then, they calculate more
detailed models for specific regions. We combine data of multi-scaled forecasts, from the average and global
to local and more accurate. That is why OWM interactive maps are very convenient.
You can use global forecasts for large scale, and you can get more and more detailed data just by zooming.
More about meteorological models >>
Weather calculation models
We are collecting data from weather stations and forecasts of meteorological services and research laboratories,
combining long-term and short-term forecasts with real-time data from weather stations,
processing them and immediately updating current weather and forecasts in our API.
Data is stored in the VANE database and processing with our unique algorithms to create interpolated data of
current weather conditions anywhere in the world, as well as into a variety of weather maps. Finally,
OWM provides our API which allows access to all the weather data including a variety of maps.
Sensors and other data sources
OpenWeatherMap service collects data from professional and private weather stations.
Today we have more than 40,000 weather stations. Most of them are professional stations which are installed in airports,
large cities etc. But it is also important for OpenWeatherMap to collect weather data from non-professional
stations that are assembled and installed by fans and weather enthusiasts.
OpenWeatherMap APIs wouldn’t be available without meteorologists sharing share our love of free software.
Many models that we use are OpenSource — WRF model, for example.
NOAA http://www.noaa.gov/
Environment Canada http://www.weatheroffice.gc.ca
European Centre for Medium-Range Weather Forecasts (ECMWF) http://www.ecmwf.int/
気象庁 Japan Meteorological Agency http://www.jma.go.jp
METAR data from airports http://en.wikipedia.org/wiki/METAR
APRS network http://www.aprs-is.net/
Other weather API’s collection
Weather Stations
API doc
Subscribe
- API for managing your personal weather stations
- Creation of the station and measurements transfer
- Receiving the aggregated measurements from the station
- Available for both Free and paid subscriptions
Weather Triggers
API doc
Subscribe
- Simple syntax to create triggers which will be working upon the occurrence of specified weather conditions (temperature, humidity, pressure, etc.) in a certain period of time.
- The alerts will be generated in our service after performing conditions of the trigger.
- Available for both Free and paid subscriptions
UV Index
API doc
Subscribe
- Current UV index (Clear Sky), forecast and historical data are available for any geo location (lat/lon)
- Interpreting of the UV Index and recommended protection are provided
- JSON format
How to Build a Weather App in Python
In this quick tutorial, we’ll show you how to build an app to estimate weather conditions by travel destination (using OpenWeatherMap API Example).
Best Travel Destination Estimation (by Weather Conditions) App
In order to demonstrate the capabilities of the OpenWeatherMap API, we will write a small Python application that can help us with choosing the best city for the next trip. At the input, it will receive a list of several cities, and at the output, it will show the rating of the best cities for travel (assessing each city by the number of predicted cloudless days in the near future and by the future average temperature).
Step 1. Import weather data into a Python program
Imagine that we choose between three cities: London, Porto, and Paris. City names along with country codes will be stored in cities list.
Also, note that we have slightly altered the Python snippet that generates the RapidAPI service for accessing the endpoint. We replaced the Python module unirest with requests since unirest is not fully supported in Python 3.
As we are predicting the weather for several cities, we will create function, which will receive the name of the city and using Forecast Weather Data endpoint return the dictionary with the weather forecast for this city. When calling endpoint, we will specify the necessary parameters (in our case, these are our credentials and the “q” parameter, into which we will enter the country code and the name of the city for which we want to see future weather).
Credentials will be stored in credentials.py file. RapidAPI credentials can be obtained in the My Apps section of the RapidAPI service by creating a new app or copying them from the “Security” subsection of one of the already created apps.
We will keep weather predictions for cities in .
import requests
import credentials
import re
cities =
weather_dict = {}
def city_forecast(city):
response = requests.get(
"https://community-open-weather-map.p.rapidapi.com/forecast?q="+city,
headers={
"X-RapidAPI-Host": "community-open-weather-map.p.rapidapi.com",
"X-RapidAPI-Key": credentials.rapidapi_key
},
)
return response.json()
for city in cities:
weather_dict = city_forecast(city)
Step 2. Prepare data for estimation
Weather forecast for each city for the next five days is available now in the dictionary. The forecast is divided into three hours blocks, and each block indicates the time (for example, 21:00:00) for which the prediction is made. Since we are interested in the average daily temperature, we need blocks with a specified time from 10:00:00 to 19:00:00. To select predictions for daytime only, we use regular expressions.
We will create function that will return True if the forecast time is between 10:00:00 and 19:00:00. After that, we put it in the filter function, select the predictions of only the day temperature and save them in dictionary.
def get_day_weather(pred):
pattern = re.compile("s(?P<hour>dd):dd:dd")
t = pattern.search(pred)
if int(t.group('hour')) >= 10 and int(t.group('hour')) <= 19:
return True
return False
day_weather = {}
for city in weather_dict.keys():
day_weather = list(filter(get_day_weather, weather_dict))
CMS
Drupal OpenLayers Open Weather Map
Provides default OpenWeatherMap layers and a new layer type to display weather forecast and weather stations all around the globe.
WordPress Awesome Weather Widget
This plugin allows you to easily add super clean (and awesome) weather widgets to your site. The weather data is provided for free by http://openweathermap.org
WordPress HD Weather Widget by The Waypoint
This plugin uses HD 331dpi images, in beautiful responsive cirlces, to display weather for your location. Images included in this package now.
The plugin parses data from the OWM api to display information. The HD background image changes, based on the ‘condition’ outside, better named here, the «Feels». We have provided one Feel in the initial v.1. Use the documentation to xref the api condition statements, against file names. The images get loaded via css, so they don’t interfere with layered objects on the site.
WordPress WPCloudy Plugin
WP Cloudy is a powerful weather plugin for WordPress, based on OpenWeatherMap API, using Custom Post Types and shortcodes, and much more.
Parameters of API respond for 16 day / daily forecast
Example of API repond:
{"cod":"200","message":0.0032,
"city":{"id":1851632,"name":"Shuzenji",
"coord":{"lon":138.933334,"lat":34.966671},
"country":"JP"},
"cnt":10,
"list":,}
]}
Parameters:
| Parameter | Description | Standard | Metric | Imperial |
|---|---|---|---|---|
| city | ||||
| id | City identification | — | — | — |
| name | City name | — | — | — |
| country | Country code (GB, JP etc.) | — | — | — |
| coord | ||||
| lat | City geo location, latitude | — | — | — |
| lon | City geo location, longitude | — | — | — |
| cnt | Number of lines returned by this API call | — | — | — |
| dt | Data receiving time | unix, UTC | unix, UTC | unix, UTC |
| temp | ||||
| day | Day temperature | Kelvin | Celsius | Fahrenheit |
| min | Min daily temperature | Kelvin | Celsius | Fahrenheit |
| max | Max daily temperature | Kelvin | Celsius | Fahrenheit |
| night | Night temperature | Kelvin | Celsius | Fahrenheit |
| eve | Evening temperature | Kelvin | Celsius | Fahrenheit |
| morn | Morning temperature | Kelvin | Celsius | Fahrenheit |
| humidity | Humidity | % | % | % |
| pressure | Atmospheric pressure (on the sea level, if there is no sea_level or grnd_level data) | hPa | hPa | hPa |
| wind | ||||
| speed | Wind speed | meter/sec | meter/sec | miles/hour |
| deg | Wind direction | degrees (meteorological) | degrees (meteorological) | degrees (meteorological) |
| gust | Wind gust | meter/sec | meter/sec | miles/hour |
| clouds | ||||
| all | Cloudiness | % | % | % |
| weather (more info Weather condition codes) | ||||
| id | Weather condition id | — | — | — |
| main | Group of weather parameters (Rain, Snow, Extreme etc.) | — | — | — |
| description | Weather condition within the group | — | — | — |
| icon | Weather icon id | — | — | — |
| rain | Precipitation volume | mm | mm | mm |
| snow | Snow volume | mm | mm | mm |
Работа с API погоды в PHP:
Теперь перейдём к работе с OpenWeatherMap API, суть работы будет в том, что мы отправляем GET запрос и в качестве ответа получаем JSON данные, но перед этим нужно настроить ссылку с запросом.
PHP
|
1 2 3 4 5 6 |
// API ключ $apiKey=»fe57b721fd47b8600afac45a7829c1ea»; // Город погода которого нужна $city=»Moscow»; // Ссылка для отправки $url=»http://api.openweathermap.org/data/2.5/weather?q=».$city.»&lang=ru&units=metric&appid=».$apiKey; |
Теперь разберём этот код, что тут, сначала мы создаём переменную , который хранить в себе ключ для работы с API, дальше название города, который нам нужен.
Потом создаём URL с GET запросами, вот их и надо рассмотреть.
- q — Название города, у которого нужно получить погоду;
- lang — Язык данных;
- units — Тип градусов;
- appid — API ключ;
Это в целом всё что вам нужно, самое главное, не забудьте задать значение , иначе у вас погода будет не в цельсиях а в фаренгейтах.
Если вам что то не понятно, то рекомендую прочитать часть учебника: PHP работа с формой.
Теперь перейдём к отправке запроса, для этого будем использовать стандартную библиотек PHP.
PHP
|
1 2 3 4 5 6 7 8 9 10 11 12 |
// Создаём запрос $ch=curl_init(); curl_setopt($ch,CURLOPT_RETURNTRANSFER,true); curl_setopt($ch,CURLOPT_URL,$url); $data=json_decode(curl_exec($ch)); curl_close($ch); |
Тут в целом не чего сложного нет, сначала создаёте запрос и потом настраиваете его, если вам не понятно настройка, то зайдите по этой ссылке.
После этого отправляем запрос и сразу же получаем JSON ответ и декодируем его в обычный PHP объект, с помощью json_decode, закрываем запрос.
Выводим на экран данные о погоде.
PHP
|
1 2 3 4 5 6 |
<div class=»weather»> <h2>Погодавгороде<?phpecho$data->name;?><h2> <p>Погода<?phpecho$data->main->temp_min;?>°C<p> <p>Влажность<?phpecho$data->main->humidity;?>%<p> <p>Ветер<?phpecho$data->wind->speed;?>кмч<p> <div> |
Вот какой результат получился.

Как видите всё работает, таким образом вы можете получать данные из любого города, только нужно писать их название на английском, хотя я слушал что можно и на русском.