Page 1 of 1

OpenWeatherMap API

Posted: Wed Sep 02, 2015 12:11 am
by Flype
Hi, here is a Module for OpenWeatherMap API

http://openweathermap.org/api

EDIT: updated on 2015-09-04.

Code: Select all

;=======================================================
;== Module OpenWeatherMap
;=======================================================
;== Compiler:  PureBasic 5.31 (x64)
;== Tested on: Linux XUbuntu
;== Author:    flype, 2015
;== Version:   1.3 (2015-09-04)
;== Source:    GitHub link (soon)
;=======================================================

; http://openweathermap.org/api
; http://openweathermap.org/api_station
; http://openweathermap.org/current
; http://openweathermap.org/forecast5
; http://openweathermap.org/forecast16
; http://openweathermap.org/weather-data
; http://openweathermap.org/weather-conditions
; http://openweathermap.org/img/w/{weather.icon}.png

;=======================================================
;== Module Http
;=======================================================

DeclareModule Http
  
  ;----------------------------------------
  ;-- Functions
  ;----------------------------------------
  
  Declare   GetData  (url.s, bufSize.i = 65536)
  Declare   GetImage (url.s, bufSize.i = 65536)
  Declare.s GetString(url.s, bufSize.i = 65536)
  
EndDeclareModule

Module Http
  
  EnableExplicit
  
  ;----------------------------------------
  ;-- Publics
  ;----------------------------------------
  
  Procedure GetData(url.s, bufSize = 65536)
    
    Protected connection, exit, count, total, *buf1, *buf2
    
    url = URLEncoder(url)
    connection = OpenNetworkConnection(GetURLPart(url, #PB_URL_Site), 80, #PB_Network_TCP)
    If connection
      If SendNetworkString(connection, "GET " + url + #CRLF$, #PB_UTF8)
        Repeat
          Select NetworkClientEvent(connection)
            Case #PB_NetworkEvent_None: Delay(10)
            Case #PB_NetworkEvent_Disconnect: exit = #True
            Case #PB_NetworkEvent_Data
              *buf1 = AllocateMemory(bufSize)
              If *buf1 <> #Null
                *buf2 = *buf1
                Repeat
                  count = ReceiveNetworkData(connection, *buf2, 1024)
                  If count > 0
                    *buf2 + count : total + count
                  EndIf
                Until count = 0
                *buf1 = ReAllocateMemory(*buf1, total)
              EndIf
              exit = #True
          EndSelect
        Until exit
      EndIf
      CloseNetworkConnection(connection)
    EndIf
    
    ProcedureReturn *buf1
    
  EndProcedure

  Procedure GetImage(url.s, bufSize = 65536)
    
    Protected result, *buf = Http::GetData(url, bufSize)
    
    If *buf
      result = CatchImage(#PB_Any, *buf, MemorySize(*buf))
      FreeMemory(*buf)
    EndIf
    
    ProcedureReturn result
    
  EndProcedure
  
  Procedure.s GetString(url.s, bufSize = 65536)
    
    Protected result.s, *buf = Http::GetData(url, bufSize)
    
    If *buf
      result = PeekS(*buf, -1, #PB_UTF8)
      FreeMemory(*buf)
    EndIf
    
    ProcedureReturn result
    
  EndProcedure
  
EndModule

;=======================================================
;== Module OpenWeatherMap
;=======================================================

DeclareModule OpenWeatherMap
  
  ;----------------------------------------
  ;-- Constants
  ;----------------------------------------
  
  #OWM_API_ICON    = "http://openweathermap.org/img/w/"
  #OWM_API_ROOT    = "http://api.openweathermap.org/data/2.5/"
  
  #OWM_API_FIND    = "http://api.openweathermap.org/data/2.5/find"
  #OWM_API_GROUP   = "http://api.openweathermap.org/data/2.5/group"
  #OWM_API_WEATHER = "http://api.openweathermap.org/data/2.5/weather"
  #OWM_API_BOX     = "http://api.openweathermap.org/data/2.5/box/city"
  
  #OWM_MODE_HTML = "html"
  #OWM_MODE_JSON = "json"
  #OWM_MODE_XML  = "xml"
  
  #OWM_TYPE_ACCURATE = "accurate"
  #OWM_TYPE_LIKE     = "like"
  
  #OWM_UNIT_Imperial = "imperial"
  #OWM_UNIT_Metric   = "metric"
  
  #OWM_LANG_Bulgarian  = "bg"
  #OWM_LANG_Catalan    = "ca"
  #OWM_LANG_Chinese_Traditional = "zh_tw"
  #OWM_LANG_Chinese_Simplified  = "zh" ; or "zh_cn"
  #OWM_LANG_Croatian   = "hr"
  #OWM_LANG_Dutch      = "nl"
  #OWM_LANG_English    = "en"
  #OWM_LANG_Finnish    = "fi"
  #OWM_LANG_French     = "fr"
  #OWM_LANG_German     = "de"
  #OWM_LANG_Italian    = "it"
  #OWM_LANG_Polish     = "pl"
  #OWM_LANG_Portuguese = "pt"
  #OWM_LANG_Romanian   = "ro"
  #OWM_LANG_Russian    = "ru"
  #OWM_LANG_Spanish    = "es" ; or "sp"
  #OWM_LANG_Swedish    = "sv" ; or "se"
  #OWM_LANG_Turkish    = "tr"
  #OWM_LANG_Ukrainian  = "uk" ; or "ua"
  
  ;----------------------------------------
  ;-- Structures
  ;----------------------------------------
  
  Structure OWM_Clouds
    all.l ; Cloudiness, %
  EndStructure
  
  Structure OWM_Coord
    lon.d ; City geo location, latitude
    lat.d ; City geo location, longitude
  EndStructure
  
  Structure OWM_Error
    cod.s     ; Error code
    message.s ; Error message
  EndStructure
  
  Structure OWM_Main
    temp.d       ; Temperature. Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit. 
    pressure.l   ; Atmospheric pressure (on the sea level, if there is no sea_level or grnd_level data), hPa
    humidity.l   ; Humidity, %
    temp_min.d   ; Minimum temperature at the moment. 
                 ; This is deviation from current temp that is possible for large cities 
                 ; and megalopolises geographically expanded (use these parameter optionally). 
                 ; Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.
    temp_max.d   ; Maximum temperature at the moment. 
                 ; This is deviation from current temp that is possible for large cities 
                 ; and megalopolises geographically expanded (use these parameter optionally). 
                 ; Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.
    sea_level.l  ; Atmospheric pressure on the sea level, hPa
    grnd_level.l ; Atmospheric pressure on the ground level, hPa
  EndStructure
  
  Structure OWM_Rain
    h3.l ; Rain volume for the last 3 hours
         ; Remark: original property is '3h'
  EndStructure
  
  Structure OWM_Snow
    h3.l ; Snow volume for the last 3 hours
         ; Remark: original property is '3h'
  EndStructure
  
  Structure OWM_Sys
    type.l    ; Internal parameter
    id.l      ; Internal parameter
    message.d ; Internal parameter
    country.s ; Country code (GB, JP etc.)
    sunrise.l ; Sunrise time, unix, UTC
    sunset.l  ; Sunset time, unix, UTC
  EndStructure
  
  Structure OWM_Weather
    id.l          ; Weather condition id
    main.s        ; Group of weather parameters (Rain, Snow, Extreme etc.)
    description.s ; Weather condition within the group
    icon.s        ; Weather icon id
  EndStructure
  
  Structure OWM_Wind
    speed.d ; Wind speed. Unit Default: meter/sec, Metric: meter/sec, Imperial: miles/hour.
    deg.l   ; Wind direction, degrees (meteorological)
  EndStructure
  
  Structure OWM_Item
    cod.l             ; Internal parameter
    base.s            ; Internal parameter
    id.l              ; City ID
    name.s            ; City name
    visibility.l      ; Visibility
    dt.l              ; Time of data calculation, unix, UTC
    coord.OWM_Coord   ; Coord object
    clouds.OWM_Clouds ; Clouds object
    error.OWM_Error   ; Error object
    main.OWM_Main     ; Main object
    rain.OWM_Rain     ; Rain object
    sys.OWM_Sys       ; Sys object
    snow.OWM_Snow     ; Snow object
    wind.OWM_Wind     ; Wind object
    List weather.OWM_Weather() ; Weather objects
  EndStructure
  
  Structure OWM_Group
    message.s             ; Message
    cod.s                 ; Code
    calctime.d            ; Processing server time
    count.l               ; Number of items
    List items.OWM_Item() ; Items list
    error.OWM_Error       ; Error object
  EndStructure
  
  ;----------------------------------------
  ;-- Functions
  ;----------------------------------------
  
  Declare OWM_GetCitiesInIDs(*object.OWM_Group, cityIDs.s)
  Declare OWM_GetCitiesInCircle(*object.OWM_Group, lat.d, lon.d, count.i = 10)
  Declare OWM_GetCitiesInRect(*object.OWM_Group, lat1.d, lon1.d, lat2.d, lon2.d, mapZoom.d)
  
  Declare OWM_GetWeatherByGeoCoord(*object.OWM_Item, lat.d, lon.d)
  Declare OWM_GetWeatherByCityID(*object.OWM_Item, cityID.s)
  Declare OWM_GetWeatherByCityName(*object.OWM_Item, cityName.s)
  Declare OWM_GetWeatherByZipCode(*object.OWM_Item, zip.s)
  Declare OWM_GetWeatherIcon(*object.OWM_Weather)
  
  Declare OWM_SetDefaultAPIKey(key.s)
  Declare OWM_SetDefaultLang(lang.s)
  Declare OWM_SetDefaultUnits(units.s)
  
EndDeclareModule

Module OpenWeatherMap
  
  EnableExplicit
  
  ;-----------------------------------------------------
  ;-- Privates
  ;-----------------------------------------------------
  
  Enumeration
    #OWM_FIND
    #OWM_ITEM
    #OWM_GROUP
  EndEnumeration
  
  Global defaultAPIKey.s
  Global defaultLang.s
  Global defaultUnits.s
  
  Procedure.s PrepareJSON(json.s)
    
    ; Rename "3h" member of OWM_Rain and OWM_Snow objects to "h3"
    json = ReplaceString(json, #DQUOTE$ + "3h" + #DQUOTE$, #DQUOTE$ + "h3" + #DQUOTE$)
    
    ; Rename "list" member of OWM_Group object to "items"
    json = ReplaceString(json, #DQUOTE$ + "list" + #DQUOTE$, #DQUOTE$ + "items" + #DQUOTE$)
    
    ; Rename "cnt" member of OWM_Group object to "count" (for standardized use)
    json = ReplaceString(json, #DQUOTE$ + "cnt" + #DQUOTE$, #DQUOTE$ + "count" + #DQUOTE$)
    
    ProcedureReturn json
    
  EndProcedure
  
  Procedure GetJSON(*object, service.s, params.s)
    
    Protected id, success, json.s
    
    params + "&mode=" + #OWM_MODE_JSON
    
    If defaultUnits <> #NULL$
      params + "&units=" + defaultUnits
    EndIf
    
    If defaultLang <> #NULL$
      params + "&lang="  + defaultLang
    EndIf
    
    If defaultAPIKey <> #NULL$
      params + "&APPID="  + defaultAPIKey
    EndIf
    
    json = Http::GetString(#OWM_API_ROOT + service + params)
    
    ;Debug "OpenWeatherMap::GetJSON()"
    ;Debug #OWM_API_ROOT + service + params
    ;Debug json
    
    If json <> #NULL$
      id = ParseJSON(#PB_Any, PrepareJSON(json))
      If id
        Select service
          Case "weather"
            Protected *item.OWM_Item = *object
            ExtractJSONStructure(JSONValue(id), *item,       OWM_Item)
            ExtractJSONStructure(JSONValue(id), *item\error, OWM_Error)
            success = #True
          Case "box/city", "find", "group"
            Protected *group.OWM_Group = *object
            ExtractJSONStructure(JSONValue(id), *group,       OWM_Group)
            ExtractJSONStructure(JSONValue(id), *group\error, OWM_Error)
            success = #True
        EndSelect
        FreeJSON(id)
      EndIf
    EndIf
    
    ProcedureReturn success
    
  EndProcedure
  
  ;-----------------------------------------------------
  ;-- Publics Getters
  ;-----------------------------------------------------
  
  Procedure OWM_GetCitiesInIDs(*object.OWM_Group, cityIDs.s)
    ProcedureReturn GetJSON(*object, "group", "?id=" + cityIDs)
  EndProcedure
  
  Procedure OWM_GetCitiesInCircle(*object.OWM_Group, lat.d, lon.d, count.i = 10)
    ProcedureReturn GetJSON(*object, "find", "?lat=" + lat + "&lon=" + lon + "&cnt=" + count)
  EndProcedure
  
  Procedure OWM_GetCitiesInRect(*object.OWM_Group, lat1.d, lon1.d, lat2.d, lon2.d, mapZoom.d)
    ProcedureReturn GetJSON(*object, "box/city", "?bbox=" + lat1.d + "," + lon1.d + "," + lat2.d + "," + lon2 + "," + mapZoom)
  EndProcedure
  
  Procedure OWM_GetWeatherByGeoCoord(*object.OWM_Item, lat.d, lon.d)
    ProcedureReturn GetJSON(*object, "weather", "?lat=" + lat + "&lon=" + lon)
  EndProcedure
  
  Procedure OWM_GetWeatherByCityID(*object.OWM_Item, cityID.s)
    ProcedureReturn GetJSON(*object, "weather", "?id=" + cityID)
  EndProcedure
  
  Procedure OWM_GetWeatherByCityName(*object.OWM_Item, cityName.s)
    ProcedureReturn GetJSON(*object, "weather", "?q=" + cityName)
  EndProcedure
  
  Procedure OWM_GetWeatherByZipCode(*object.OWM_Item, zipCode.s)
    ProcedureReturn GetJSON(*object, "weather", "?zip=" + zipCode)
  EndProcedure
  
  Procedure OWM_GetWeatherIcon(*object.OWM_Weather)
    ProcedureReturn Http::GetImage(#OWM_API_ICON + *object\icon + ".png")
  EndProcedure
  
  ;-----------------------------------------------------
  ;-- Publics Setters
  ;-----------------------------------------------------
  
  Procedure OWM_SetDefaultAPIKey(key.s)
    defaultAPIKey = key
  EndProcedure
  
  Procedure OWM_SetDefaultLang(lang.s)
    defaultLang = lang
  EndProcedure
  
  Procedure OWM_SetDefaultUnits(units.s)
    defaultUnits = units
  EndProcedure
  
EndModule

;=======================================================
;== End of include
;=======================================================

Re: OpenWeatherMap API

Posted: Wed Sep 02, 2015 12:12 am
by Flype
Small example

EDIT: updated.

Code: Select all

;==========================================
;== OpenWeatherMap Test 1
;==========================================

InitNetwork()

IncludeFile "OpenWeatherMap.pbi"

UseModule OpenWeatherMap

; Optional API Key - Obtain a free one here :
; http://openweathermap.org/appid

;OWM_SetDefaultAPIKey("your_api_key_here")
OWM_SetDefaultLang(#OWM_LANG_English)
OWM_SetDefaultUnits(#OWM_UNIT_Metric)

Define x.OWM_Item, result, mask.s = "%dd/%mm/%yyyy %hh:%ii:%ss"

;result = OWM_GetWeatherByCityName(x, "Saint Etienne,fr")
;result = OWM_GetWeatherByCityName(x, "Paris,fr")
result = OWM_GetWeatherByCityName(x, "Roma,it")
;result = OWM_GetWeatherByCityName(x, "London,uk")
;result = OWM_GetWeatherByZipCode(x, "29000,fr")
;result = OWM_GetWeatherByZipCode(x, "94040,us")
;result = OWM_GetWeatherByGeoCoord(x, -0.13, 51.51)

If result
  Debug "name: "          + x\name
  Debug "dt: "            + FormatDate(mask, x\dt)
  Debug "cloud.all: "     + x\clouds\all + "%"
  Debug "coord.lon: "     + x\coord\lon
  Debug "coord.lat: "     + x\coord\lat
  Debug "main.temp: "     + x\main\temp + "°C"
  Debug "main.pressure: " + x\main\pressure + " hPA"
  Debug "main.humidity: " + x\main\humidity + "%"
  Debug "main.temp_min: " + x\main\temp_min + "°C"
  Debug "main.temp_max: " + x\main\temp_max + "°C"
  Debug "sys.country: "   + x\sys\country
  Debug "sys.sunrise: "   + FormatDate(mask, x\sys\sunrise)
  Debug "sys.sunset: "    + FormatDate(mask, x\sys\sunset)
  Debug "rain.3h: "       + x\rain\h3
  Debug "snow.3h: "       + x\snow\h3
  Debug "wind.speed: "    + x\wind\speed + "m/s"
  Debug "wind.deg: "      + x\wind\deg + "°"
  ForEach x\weather()
    Debug "weather.main: "        + x\weather()\main
    Debug "weather.description: " + x\weather()\description
    Debug "weather.icon: "        + x\weather()\icon
  Next
Else
  Debug "code: "    + x\error\cod
  Debug "message: " + x\error\message
EndIf

;==========================================

Re: OpenWeatherMap API

Posted: Wed Sep 02, 2015 12:14 am
by Flype
2nd example

EDIT: updated.

Code: Select all

;==========================================
;== OpenWeatherMap Test 2
;==========================================

InitNetwork()

UsePNGImageDecoder()

IncludeFile "OpenWeatherMap.pbi"

UseModule OpenWeatherMap

If OpenWindow(0, #PB_Ignore, #PB_Ignore, 400, 200, "OpenWeatherMap", #PB_Window_ScreenCentered)
  
  TextGadget(0, 10, 10, 380, 20, "")
  ImageGadget(1, 10, 40, 50, 50, 0, #PB_Image_Border)
  
  Define x.OWM_Item
  
  OWM_SetDefaultLang(#OWM_LANG_French)
  OWM_SetDefaultUnits(#OWM_UNIT_Metric)
  
  If OWM_GetWeatherByCityName(x, "manchester,uk")
    If FirstElement(x\weather())
      Define imgID = OWM_GetWeatherIcon(x\weather())
      SetGadgetText(0, x\weather()\description)
      SetGadgetState(1, ImageID(imgID))
    EndIf
  EndIf
  
  Repeat
    Delay(1)
  Until WaitWindowEvent() = #PB_Event_CloseWindow
  
EndIf

;==========================================
EDIT: added on 2015-09-04.

Another example illustrating Group list type results
OWM_GetCitiesInIDs()
OWM_GetCitiesInRect()
OWM_GetCitiesInCircle()

Code: Select all

;==========================================
;== OpenWeatherMap Test 3
;==========================================

InitNetwork()

IncludeFile "OpenWeatherMap.pbi"

UseModule OpenWeatherMap

;OWM_SetDefaultAPIKey("__your_api_key__")
OWM_SetDefaultLang(#OWM_LANG_French)
OWM_SetDefaultUnits(#OWM_UNIT_Metric)

Define x.OWM_Group, result.i

result = OWM_GetCitiesInIDs(x, "524901,703448,2643743")
;result = OWM_GetCitiesInRect(x, 12, 32, 15, 37, 7)
;result = OWM_GetCitiesInCircle(x, 45.5, 47.5, 100)

If result
  Debug "count: " + x\count
  ForEach x\items()
    Debug "============"
    Debug "name: "     + x\items()\name
    Debug "temp: "     + x\items()\main\temp     + "°C"
    Debug "pressure: " + x\items()\main\pressure + " hPA"
    Debug "humidity: " + x\items()\main\humidity + "%"
    Debug "wind: "     + x\items()\wind\speed    + "m/s"
    ForEach x\items()\weather()
      Debug "weather: " + x\items()\weather()\description
    Next
  Next
Else
  Debug "code: "    + x\error\cod
  Debug "message: " + x\error\message
EndIf

;==========================================

Re: OpenWeatherMap API

Posted: Wed Sep 02, 2015 5:15 am
by VB6_to_PBx
all your Weather Code examples work great !!!

thanks for sharing this !

Re: OpenWeatherMap API

Posted: Wed Sep 02, 2015 6:12 am
by Keya
I was scratching my head wondering why Demo1 worked but Demo2 didnt, until i remembered i hadnt turned Unicode off in Demo2 -- now they both work fine :)
which is why you should include that check in the source code rather than comments for the user (which often aren't saved along with the code) - even highlighting it red wasn't enough! ;)

Code: Select all

CompilerIf #PB_Compiler_Unicode = 1
  CompilerError "Turn unicode off"
CompilerEndIf

Im using 5.40 B1 so im not sure if its just an issue with that (there's some issue with bad parameters)
but I had to comment-out ", #PB_String_InPlace" in the PrepareJSON routine:

Code: Select all

Procedure.s PrepareJSON(json.s)
    ; Rename '3h' members to 'h3'
    ProcedureReturn ReplaceString(json, "3h", "h3")  ;, #PB_String_InPlace)
EndProcedure
ps. I thought when using the #PB_String_InPlace flag that it doesn't actually return a string, it just modifies the string you give it? (like "Procedure" and not "Procedure.s")
the help for ReplaceString suggests to "ignore the result", so you might want to double-check that :)

Re: OpenWeatherMap API

Posted: Wed Sep 02, 2015 6:53 am
by Flype
Thank you Keya for the good advices.
My purebasic skill is maybe a bit rusty :) I will correct it.

I guess also that with lastest pb beta, the new http commands should help to minimize the code even more.

Re: OpenWeatherMap API

Posted: Wed Sep 02, 2015 6:54 am
by infratec
Hi,

to work also in unicode:

Code: Select all

Procedure.s HttpGetString(url.s, bufferSize = 65536)
   
    Protected connection, exit, request.s, *buffer, result.s, Count.i
    connection = OpenNetworkConnection(GetURLPart(url, #PB_URL_Site), 80, #PB_Network_TCP)
    If connection
      request = "GET " + url + #CRLF$
      If SendNetworkString(connection, request, #PB_UTF8)
        Repeat
          Select NetworkClientEvent(connection)
            Case #PB_NetworkEvent_None
              Delay(10)
            Case #PB_NetworkEvent_Disconnect
              exit = #True
            Case #PB_NetworkEvent_Data
              *buffer = AllocateMemory(bufferSize)
              If *buffer
                Repeat
                  Count = ReceiveNetworkData(connection, *buffer, bufferSize)
                  If Count
                    result + PeekS(*buffer, Count, #PB_UTF8)
                  Else
                    exit = #True
                  EndIf
                Until exit
                FreeMemory(*buffer)
              EndIf
          EndSelect
        Until exit
      EndIf
      CloseNetworkConnection(connection)
    EndIf
   
    ProcedureReturn result
   
  EndProcedure
Bernd

Re: OpenWeatherMap API

Posted: Wed Sep 02, 2015 6:59 am
by infratec
Ups, I also changed the picture stuff a bit:


SendNetworkString() instead of SendNetworkData(),
#PB_Any @ CatchImage(), because 0 maybe already available.

Code: Select all

Procedure HttpGetImage(url.s)
    Debug url
    Protected connection, exit, request.s, *buf, bufSize = 65536
    connection = OpenNetworkConnection(GetURLPart(url, #PB_URL_Site), 80, #PB_Network_TCP)
    If connection
      request = "GET " + url + #CRLF$
      If SendNetworkString(connection, request, #PB_UTF8)
        Repeat
          Select NetworkClientEvent(connection)
            Case #PB_NetworkEvent_None
              Delay(10)
            Case #PB_NetworkEvent_Disconnect
              exit = #True
            Case #PB_NetworkEvent_Data
              *buf = AllocateMemory(bufSize)
              If *buf
                bufSize = ReceiveNetworkData(connection, *buf, bufSize)
                If bufSize > 0
                  ;Debug PeekS(*buf, 4, #PB_UTF8)
                  image = CatchImage(#PB_Any, *buf)
                EndIf
                exit = #True
                FreeMemory(*buf)
              EndIf
          EndSelect
        Until exit
      EndIf
      CloseNetworkConnection(connection)
    EndIf
   
    ProcedureReturn image
   
  EndProcedure

Then you need to change the example with the picture:

Code: Select all

InitNetwork()

UsePNGImageDecoder()

IncludeFile "OpenWeatherMap.pbi"

UseModule OpenWeatherMap

Define x.OWM_Item, img.i

If OpenWindow(0, #PB_Ignore, #PB_Ignore, 400, 200, "OpenWeatherMap", #PB_Window_ScreenCentered|#PB_Window_SystemMenu)
 
  TextGadget(0, 10, 10, 380, 20, "")
  ImageGadget(1, 10, 40, 100, 100, 0, #PB_Canvas_Border)
 
  
 
  If OWM_GetWeatherByCityName(x, "manchester,uk")
    If FirstElement(x\weather())
      img = OWM_GetWeatherIcon(x\weather())
      SetGadgetText(0, x\weather()\description)
      SetGadgetState(1, ImageID(img))
    EndIf
  EndIf
  
  Repeat
  Until WaitWindowEvent() = #PB_Event_CloseWindow
 
EndIf
Your example was only working by luck, since ImageID() have to be used

Bernd

Re: OpenWeatherMap API

Posted: Wed Sep 02, 2015 8:26 pm
by Flype
Hi skilled guys :P thanks a lot for all the remarks and fixes...

I'm looking at all your posts and will update the code tonight.

Re: OpenWeatherMap API

Posted: Wed Sep 02, 2015 11:38 pm
by Flype
I have updated first post and examples thank to your comments.

- Unicode Compatible (infratec) : Use now PeekS(*buf, -1, #PB_UTF8).
- Spaces in parameter (%20) fixed (Spoke) : Use now URLEncoder().
- SendNetworkString instead of SendNetworkData (infratec).
- ReplaceString modified (infratec).
- HTTP functions moved in another module.
- Some other optimizations, shorter code.
- Added OWM_SetDefaultAPIKey("your_api_key") :

Last is the optional API Key you can freely obtain here :
http://openweathermap.org/appid

You can check the limits of the free service, which is however enough for most usages.
http://openweathermap.org/price
http://openweathermap.org/price_detailes

Small question about Http::GetData() (see first post)
How would you do a Loop of ReceiveNetworkData() until no more data and return a full new filled buffer (without size limit) ?
I might do a NewList of packets() of 65536 bytes per packet, allocate mem for packet at each iteration,
fill it, and at end of loop, fill a new allocated memory. Better solution :?:

Re: OpenWeatherMap API

Posted: Thu Sep 03, 2015 8:27 am
by RSBasic
Thank you for your code. :)

Re: OpenWeatherMap API

Posted: Thu Sep 03, 2015 9:08 am
by Rings
thx a lot for sharing

Re: OpenWeatherMap API

Posted: Fri Sep 04, 2015 5:44 pm
by Flype
You're welcome guys :wink:

I've updated the module - v1.3

See 1rst Post for the module update
http://www.purebasic.fr/english/viewtop ... 09#p470209

See 3rd Post for an illustration of code
http://www.purebasic.fr/english/viewtop ... 11#p470211

Updates :

- Http::GetData() refactored (Loop of ReceiveNetworkData much better in case of bigger data received)
- Added: OWM_GetCitiesInIDs(*object.OWM_Group, cityIDs.s)
- Added: OWM_GetCitiesInCircle(*object.OWM_Group, lat.d, lon.d, count.i = 10)
- Added: OWM_GetCitiesInRect(*object.OWM_Group, lat1.d, lon1.d, lat2.d, lon2.d, mapZoom.d)
- Optimized code.

Re: OpenWeatherMap API

Posted: Fri Sep 04, 2015 10:35 pm
by Andre
Cool, thanks a lot! :mrgreen:

Works very well on MacOS 10.5.8 too... :D

Re: OpenWeatherMap API

Posted: Sun Nov 08, 2020 10:55 am
by l1marik
Dear Flype, how to use map layers from OpenWeatherMap?

THX
Flype wrote:You're welcome guys :wink:

I've updated the module - v1.3

See 1rst Post for the module update
http://www.purebasic.fr/english/viewtop ... 09#p470209

See 3rd Post for an illustration of code
http://www.purebasic.fr/english/viewtop ... 11#p470211

Updates :

- Http::GetData() refactored (Loop of ReceiveNetworkData much better in case of bigger data received)
- Added: OWM_GetCitiesInIDs(*object.OWM_Group, cityIDs.s)
- Added: OWM_GetCitiesInCircle(*object.OWM_Group, lat.d, lon.d, count.i = 10)
- Added: OWM_GetCitiesInRect(*object.OWM_Group, lat1.d, lon1.d, lat2.d, lon2.d, mapZoom.d)
- Optimized code.