Giter Site home page Giter Site logo

openweathermap's Introduction

OpenWeatherMap Go API

GoDoc Build Status Coverage Status

Go (golang) package for use with openweathermap.org's API.

For more detail about the library and its features, reference your local godoc once installed.

Website!

To use the OpenweatherMap API, you need to obtain an API key. Sign up here. Once you have your key, create an environment variable called OWM_API_KEY. Start coding!

Slack Channel

Contributions welcome!

Features

Current Weather Conditions

  • By City
  • By City,St (State)
  • By City,Co (Country)
  • By City ID
  • By Zip,Co (Country)
  • By Longitude and Latitude

Forecast

Get the weather conditions for a given number of days.

  • By City
  • By City,St (State)
  • By City,Co (Country)
  • By City ID
  • By Longitude and Latitude

Access to Condition Codes and Icons

Gain access to OpenWeatherMap icons and condition codes.

  • Thunderstorms
  • Drizzle
  • Rain
  • Snow
  • Atmosphere
  • Clouds
  • Extreme
  • Additional

Data Available in Multiple Measurement Systems

  • Fahrenheit (OpenWeatherMap API - imperial)
  • Celsius (OpenWeatherMap API - metric)
  • Kelvin (OpenWeatherMap API - internal)

UV Index Data

  • Current
  • Historical

Pollution Data

  • Current

Historical Conditions

  • By Name
  • By ID
  • By Coordinates

Supported Languages

English - en, Russian - ru, Italian - it, Spanish - es (or sp), Ukrainian - uk (or ua), German - de, Portuguese - pt, Romanian - ro, Polish - pl, Finnish - fi, Dutch - nl, French - fr, Bulgarian - bg, Swedish - sv (or se), Chinese Traditional - zh_tw, Chinese Simplified - zh (or zh_cn), Turkish - tr, Croatian - hr, Catalan - ca

Installation

go get github.com/briandowns/openweathermap

Examples

There are a few full examples in the examples directory that can be referenced. 1 is a command line application and 1 is a simple web application.

package main

import (
	"log"
	"fmt"
	"os"

	// Shortening the import reference name seems to make it a bit easier
	owm "github.com/briandowns/openweathermap"
)

var apiKey = os.Getenv("OWM_API_KEY")

func main() {
	w, err := owm.NewCurrent("F", "ru", apiKey) // fahrenheit (imperial) with Russian output
	if err != nil {
		log.Fatalln(err)
	}

	w.CurrentByName("Phoenix")
	fmt.Println(w)
}

Current Conditions by location name

func main() {
    w, err := owm.NewCurrent("K", "EN", apiKey) // (internal - OpenWeatherMap reference for kelvin) with English output
    if err != nil {
        log.Fatalln(err)
    }

    w.CurrentByName("Phoenix,AZ")
    fmt.Println(w)
}

Forecast Conditions in imperial (fahrenheit) by coordinates

func main() {
    w, err := owm.NewForecast("5", "F", "FI", apiKey) // valid options for first parameter are "5" and "16"
    if err != nil {
        log.Fatalln(err)
    }

    w.DailyByCoordinates(
        &owm.Coordinates{
                Longitude: -112.07,
                Latitude: 33.45,
        },
        5 // five days forecast
    )
    fmt.Println(w)
}

Current conditions in metric (celsius) by location ID

func main() {
    w, err := owm.NewCurrent("C", "PL", apiKey)
    if err != nil {
        log.Fatalln(err)
    }

    w.CurrentByID(2172797)
    fmt.Println(w)
}

Current conditions by zip code. 2 character country code required

func main() {
    w, err := owm.NewCurrent("F", "EN", apiKey)
    if err != nil {
        log.Fatalln(err)
    }

    w.CurrentByZip(19125, "US")
    fmt.Println(w)
}

Configure http client

func main() {
    client := &http.Client{}
    w, err := owm.NewCurrent("F", "EN", apiKey, owm.WithHttpClient(client))
    if err != nil {
        log.Fatalln(err)
    }
}

Current UV conditions

func main() {
    uv, err := owm.NewUV(apiKey)
    if err != nil {
        log.Fatalln(err)
    }

    coord := &owm.Coordinates{
        Longitude: 53.343497,
        Latitude:  -6.288379,
    }

    if err := uv.Current(coord); err != nil {
        log.Fatalln(err)
    }
    
    fmt.Println(coord)
}

Historical UV conditions

func main() {
    uv, err := owm.NewUV(apiKey)
    if err != nil {
        log.Fatalln(err)
    }

    coord := &owm.Coordinates{
        Longitude: 54.995656,
        Latitude:  -7.326834,
    }

    end := time.Now().UTC()
    start := time.Now().UTC().Add(-time.Hour * time.Duration(24))

    if err := uv.Historical(coord, start, end); err != nil {
        log.Fatalln(err)
    }
}

UV Information

func main() {
    uv, err := owm.NewUV(apiKey)
    if err != nil {
        log.Fatalln(err)
    }
    
    coord := &owm.Coordinates{
    	Longitude: 53.343497,
    	Latitude:  -6.288379,
    }
    
    if err := uv.Current(coord); err != nil {
    	log.Fatalln(err)
    }

    info, err := uv.UVInformation()
    if err != nil {
        log.Fatalln(err)
    }
    
    fmt.Println(info)
}

Pollution Information

func main() {
    pollution, err := owm.NewPollution(apiKey)
    if err != nil {
        log.Fatalln(err)
    }

    params := &owm.PollutionParameters{
        Location: owm.Coordinates{
            Latitude:  0.0,
            Longitude: 10.0,
        },
        Datetime: "current",
    }

    if err := pollution.PollutionByParams(params); err != nil {
        log.Fatalln(err)
    }
}

One Call Information

func main() {
	// Possibility to exclude information. For example exclude daily information []string{ExcludeDaily}
	w, err := owm.NewOneCall("F", "EN", apiKey, []string{})
	if err != nil {
		log.Fatalln(err)
	}

	err = w.OneCallByCoordinates(
		&Coordinates{
			Longitude: -112.07,
			Latitude:  33.45,
		},
	)
	if err != nil {
		t.Error(err)
	}

	fmt.Println(w)
}

openweathermap's People

Contributors

0ry0n avatar almogbaku avatar armon avatar billykwooten avatar bl4ckcontact avatar briandowns avatar bruston avatar clinyong avatar davidprogers avatar donatj avatar gendonl avatar ilmanzo avatar jimmykuo avatar mikmuellerdev avatar nevkontakte avatar partyzanex avatar penguwin avatar tksmaru avatar vpenso avatar wing924 avatar yorugac avatar zachfi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

openweathermap's Issues

Correctly Populate Unit field with DataUnit Value

A data unit ("C", "F", "K") is required when creating new objects which is then validated as a usable unit. If that passes, the appropriate value is assigned to obj.Unit for later use in GET requests to the API. This is functionality isn't quite working.

Inalid API key

I've got 50 characters API key from openweather API (X-RapidAPI-Key), but your applications checks if it is 32 characters long so I can't even use NewCurrent method.

Web Site for the Project

I started the gh-pages branch awhile ago and haven't gotten any time to put towards it. Mainly due to wanting to make the API as feature-rich as possible and because my UI skills are sub par. That being the case, I'll gladly take any suggestions or help on getting a basic static content site going in the gh-pages branch. Thanks!

not enough arguments in call to openweathermap.NewForecast

The example seems to be incorrect. Using:

 w, err := owm.NewForecast("F", "EN")

I get the following compile error:

./main.go:16:27: not enough arguments in call to openweathermap.NewForecast
        have (string, string)
        want (string, string, string, string, ...openweathermap.Option)

add context when log.Fatalln is called?

Hi, thank you for the work you've done on this library!

I noticed that your code is used in some other projects. What would you think about adding some context before calling log.Fatalln ? For example, sometimes, the code just stops executing because an api key is not provided, as in this line. For users of this package, maybe it would be more useful, if the errors package would be integrated? The following snippet gives a nice example of providing a stack trace:

type stackTracer interface {
    StackTrace() errors.StackTrace
}

err, ok := errors.Cause(fn()).(stackTracer)
if !ok {
    panic("oops, err does not implement stackTracer")
}

st := err.StackTrace()
fmt.Printf("%+v", st[0:2]) // top two frames

// Example output:
// github.com/pkg/errors_test.fn
//	/home/dfc/src/github.com/pkg/errors/example_test.go:47
// github.com/pkg/errors_test.Example_stackTrace
//	/home/dfc/src/github.com/pkg/errors/example_test.go:127

I debugged some code unexpectedly stopping with a message saying that the api key was not provided, and after bisecting the code, I identified the above mentioned log.Fatalln. Alternatively, perhaps making the setKey part of a constructor that returns an err as well?

Thanks!

Escape locations with spaces

This was taken from a comment on the post on Reddit. reddit - @Kealper

The only small issue I've seen so far is that it doesn't make use of net/url's QueryEscape function on the locations, it seems. I actually assumed net/http's client request functions would do this automatically but I guess they must not. For example, this will work fine: w.CurrentByName(url.QueryEscape("Port Huron, MI")) However, doing just this will not: w.CurrentByName("Port Huron, MI") Interestingly, it seems like OWM's API does make some exceptions on requiring escaping for more popular city queries such as "San Francisco, CA" or "San Antonio, TX".

Semantic versioning format is incorrect

Hi 👋,

I just noticed that in the current version, an extra period has slipped into the version number v.0.17.0. This extra period between v and 0 breaks the semantic versioning format required by go mod (e.g. causing to download v0.16.0 as @latest).
For reference the same thing has occurred in #83

Forecast doesn't compile a correct URL

Throws an error:

err="invalid character '<' looking for beginning of value"

Compile a wrong URL:

http://api.openweathermap.org/data/2.5/forecast/daily?appid=lat=%f&lon=%f&units=%s&%!s(MISSING)=%!s(MISSING)&mode=json&units=%!s(MISSING)&lang=%!s(MISSING)&cnt=%!d(MISSING)

There is an error message of {"cod":"400","message":"wrong latitude"}

Networking _networking = Networking();
const apiKey = '***********************************';

getWeatherData() async {
var latitude = await _networking.latitude;
var longitude = await _networking.latitude;

Response response = await http.get(
Uri.parse(
'http://api.openweathermap.org/data/2.5/weather?lat={$latitude}&lon={$longitude}&exclude=hourly,daily&appid=$apiKey'),
);
print(response.statusCode);
print(response.body);
}

The networking class does it job at return my current lattitude and longitude

versioning is not correct for go mod

Hello! So as of go 1.13 go mod requires semantic versioning for all it's modules including the v in front of the version.

I noticed that the versions released with this are v.0.15.0 for example, with an extra period in-between the v and the semantic version. This breaks go mod completely when trying to pull the required version.

Chiese language support error

The API about Multilingual support write: Chinese Simplified - zh (or zh_cn);but it return English when I use zh_cn:
qq 20170217131502

But it return right result when use zh:
11111

Add One Call API

Hi,

thanks a lot for providing this library. Openweathermap has introduced a free "one call API" that I'd like to use.
If that would fit in here, I'd be happy to give this a try and create a PR.

However, I'm currently running into errors when trying to execute the library tests. HTTP requests always return with an "EOF" error but calls to the very same URL from a separate small program are working fine. I noticed that the test execution on Travis seems to have the same issue. Could I get a pointer to what the issue might be and how these tests are intended to be used? Thanks!

Forecast API

Currently openweathermap has two API calls for forecasts:

Only the first one is available for all types of accounts. The second one is available only for paid accounts.

Implementation in forecast.go is meant for the paid call, which won't be available for everyone. @briandowns what do you think about changing it to a free call? Alternatively, both calls can be supported as forecast5.go and forecast16.go.

example for daily forecast

Hi, is it possible to have an example of usage about getting the forecast for the next day ? It's not totally clear to me how to retrieve the values from the returned *ForecastWeatherData after calling DailyByID.

Many Thanks

OpenWeather 3.0 API

It looks like OW stopped supporting 2.5 APIs for new users. As a result, when testing billykwooten/openweather-exporter/issues/39, I was getting invalid apis. Through debugging, I found that this library is limited to 2.5.

I'm not a GO developer. Wondering if this is something that's on the roadmap? In the mean time, I will try to convert my branch of this.

Thank you!

README example bugs

the examples in the README use only one argument in the NewCurrent function

Error upon non-existing places are unintuitive

Consider the following example;

package main

import (
	owm "github.com/briandowns/openweathermap"
	"log"
)

func main() {
	w, err := owm.NewCurrent("C", "en", "<redacted>")
	if err != nil {
		log.Fatal(err)
	}

	err = w.CurrentByName("St Petersburg")
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("Temperature in %s: %.1f °C\n", w.Name, w.Main.Temp)

	err = w.CurrentByName("fff")
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("Temperature in %s: %.1f °C\n", w.Name, w.Main.Temp)
}

This outputs json: cannot unmarshal string into Go struct field CurrentWeatherData.cod of type int as an error for the second CurrentByName call.
Perhaps a more descriptive error message could be used here?

no data returned

when running the cli example I'm not getting any data:
go run weather.go -l=EN -u=C -w=Bonn

Current weather for :
    Conditions:
    Now:         0 metric
    High:        0 metric
    Low:         0 metric

since 3 days ago this worked perfectly

Forecast datetime should be parsed

JsonUnixTime helper for that matter:

type JsonUnixTime time.Time
func (t JsonUnixTime) MarshalJSON() ([]byte, error) {
    return strconv.AppendInt(nil, time.Time(t).Unix(), 10), nil
}
func (t *JsonUnixTime) UnmarshalJSON(data []byte) (err error) {
    // Fractional seconds are handled implicitly by Parse.
    unixTime, err := strconv.ParseInt(string(data), 10, 64)
    *t = JsonUnixTime(time.Unix(unixTime, 0))
    return nil
}

Will work on a PR later

Rain and snow data missing from current?

I'm seeing rain data in the json payload with some sample code that I've got, but the data doesn't seem to make it into the struct. Wondering if this is just me, or if perhaps there's a a bug here. I looked briefly at the code, and it all looks like it should work, so not sure what I'm missing here.

	c, err := owm.NewCurrent("C", "EN", apiKey)
	if err != nil {
		return err
	}

	err = c.CurrentByCoordinates(coord)
	if err != nil {
		return err
	}

From the above c.Rain.ThreeH should contain something, but is 0.

Please, change var iconUrl to "http://openweathermap.org/img/wn/%s"

iconURL = "http://openweathermap.org/img/w/%s"

On the page https://openweathermap.org/weather-conditions recomended to use URL like http://openweathermap.org/img/wn/[email protected]
With this URL you can get image with different sizes by adding postfix "@nx" to file name, where N can be 2 or 4:
"50d.png" - defaul size 50x50px,
"[email protected]" - x2 size 100x100px,
"[email protected]" - x4 size 200x200px.

Example:
owm.RetrieveIcon(".", w.Weather[0].Icon+"@4x.png")

And change var iconUrl to var IconUrl to make it changeable. In this case users can change URL to different icon set.

Project being abandoned or no longer actively maintained?

It looks like maybe the project is not actively maintained any longer. It would be useful to know if this is so. Perhaps a new maintainer could be considered? It is a great project and it would be wonderful to keep it active and supported.

Invalid data type of cod and message

Hi,

I am using the 16 days weather forecast but I get the error "json: cannot unmarshal number into Go value of type string".
The issue occurs because the struct is defined as:

type Forecast16WeatherData struct {
	COD     int                     `json:"cod"`
	Message string                  `json:"message"`
	City    City                    `json:"city"`
	Cnt     int                     `json:"cnt"`
	List    []Forecast16WeatherList `json:"list"`
}

But the json response looks like:

{
...
"cod":"200",
"message":0.9065923,
...
}

The following solutions fix this issue:

  1. You can either define COD as string and Message as type float64
  2. Comment out both fields

Looking at the examples in docs of OWM the COD should be int. So your model is correct but the actually json response differs...so I would prefer solution 2 until the staff of OWM has fixed it or at least adjust the examples ;)

Btw. solution 2 was already implemented in forecast5.go

*byzip should not use int as datatype

The ByZip functions require an int as argument, this is an issue with German zip codes since they can start with a 0, for example Chemnitz (Saxony) has the zip acode 09123

Examples of functions affected:

  • func (w *CurrentWeatherData) CurrentByZip(zip int, countryCode string) error (current.go)
  • func (f *ForecastWeatherData) DailyByZip(zip int, countryCode string, days int) (forecast.go)

I suggest passing this as string

Forcast5 not returning 5 day forcast

Using the example provided in the repo requesting forcast data only returns 5 3 hour forcast datapoints rather than 5 days worth of data points.

go run ./weather.go -w Chattanooga -u f -l en -t forcast
Weather Forecast for Chattanooga:
Date & Time: 2020-06-15 18:00:00 +0000 UTC
Conditions:  Clouds scattered clouds
Temp:        75.43 
High:        78.39 
Low:         75.43

Date & Time: 2020-06-15 21:00:00 +0000 UTC
Conditions:  Clouds broken clouds
Temp:        75.7 
High:        76.55 
Low:         75.7

Date & Time: 2020-06-16 00:00:00 +0000 UTC
Conditions:  Clouds scattered clouds
Temp:        71.44 
High:        71.44 
Low:         71.37

Date & Time: 2020-06-16 03:00:00 +0000 UTC
Conditions:  Clear clear sky
Temp:        61.21 
High:        61.21 
Low:         61.12

Date & Time: 2020-06-16 06:00:00 +0000 UTC
Conditions:  Clear clear sky
Temp:        58.37 
High:        58.37 
Low:         58.37
```i
Is there a way to actually get the full 3 hour x 5 day dataset rather than just the next 15 hours?

[ISSUE] Error Marshaling Json Response

On the following code snippet, I get the error
json: cannot unmarshal string into Go struct field CurrentWeatherData.cod of type int on some locations (e.g. Canais) but others (e.g. Toronto, China) work.
Code:

w, err := owm.NewCurrent("C", "EN", OPEN_WEATHER_API_KEY)
if err != nil {
	return nil, err
}

if err := w.CurrentByName(location); err != nil {
		return nil, err
}

I have tested the api response and it appears to be correct. The most confusing thing is that the "cod" field in the Json response does have an int.

Requests still return invalid API key with code 401

When trying to get forecast for 5 days, I always get invalid API key, even if more than 2 hours are passed from the creation of the account+API key.

Here is the code:

package main

import(
    "log"
    owm "github.com/briandowns/openweathermap"
    "fmt"
)

var apiKey="DEFAULT KEY PROVIDED BY OPENWEATHER"

func main() {

    
    w, err := owm.NewForecast("5", "C", "IT", apiKey) // valid options for first parameter are "5" and "16"
    if err != nil {
        log.Fatalln(err)
    }
    
    //w.DailyByName("Locorotondo", 7)
    w.DailyByCoordinates(&owm.Coordinates{Longitude: -112.07,Latitude: 33.45,}, 5)
	fmt.Println(w)
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.