Open weather API

随声附和 提交于 2019-12-07 12:55:47

问题


So, I'm making a bunch of webpages for different communities, and on each I want to have a little weather box that I can customize, just with the name of the town, the current temperature, and the current weather condition. I want to be able to style it all exactly how I want. I found this site called Open Weather Map that seems to do exactly what I want. The problem is that I don't know how to use JSON. It's probably easy, but I seem to have gotten lost on any online tutorials I've tried.

This is an example of a URL for the page, that loads some JSON. http://api.openweathermap.org/data/2.5/weather?q=London,uk

I could just include this in my file and dynamically change the city and the country code to get the city I want. But how do I load this into my weather box? Let's say this is what I have:

<div class="weatherbox">

  <strong class="city>{CITY NAME HERE}</strong>
  <span class="temperature">{X} °C</span>
  <p class="weatherdescription>{WEATHER DESCRIPTION HERE}</p>

</div>

Then how do I access the data from the JSON? I want it to be done as simply as possible. Do I include the file like this to have access to the object, or is it more complicated?

<script type="javascript" src="http://api.openweathermap.org/data/2.5/weather?q=London,uk"></script>

回答1:


from your line of code:

<script type="javascript" src="http://api.openweathermap.org/data/2.5/weather?q=London,uk"></script>

this is incorrect, the api is returning JSON, it is not a javascript file so you don't access it in such a manner. Note that their API appears to take the city and country as a part of the URL parameters, so this you will need to plug in for the appropriate city/country.

For your specific question you could do something like:

var jsonData;

$(document).ready(function ()
{
    $.getJSON('http://api.openweathermap.org/data/2.5/weather?q=London,uk', function(data) {
        jsonData = data;
        $('.city').text(jsonData.name);
        // etc
    });
});

See http://jsfiddle.net/jsxm7j3n/1/ for it in action.

Note in order to understand the JSON, you can run it through a JSON parser such as the one at http://json.parser.online.fr/ - this will allow you to better understand the make up of what you're receiving back, and how to parse it.

Double note: forgot to mention this solution uses JQuery - i believe there are purely javascript ways to pull it off, but it will be much more verbose and (in my opinion) harder to understand.




回答2:


Assuming jQuery:

<script>
// Load the data through ajax, not by including it like a script:

$.get('http://api.openweathermap.org/data/2.5/weather?q=London,uk', function(data) {
    $('.weatherbox .temperature').text(data.main.temp);
});

</script>

When you look at the response headers from the URL to the API, it is sending 2 important headers:

Content-Type: application/json; charset=utf-8
Access-Control-Allow-Origin: *

This means:

  1. Return JSON object, not just a file. You don't have to use JSON.parse() or $.getJSON then.
  2. Allow anyone to request it via ajax (security aspect of Ajax).

Because Ajax by default is async, (that's what the A stands for), you need to wrap your assignment into a function, which is executed after the request has finished.




回答3:


The following Code runs. You must only change the Api Key

A full Tutorial: https://www.revilodesign.de/blog/sonstiges/wetterdaten-mit-openweathermap-api-in-eigene-webseite-einbinden/

// API URL
var apiUrl				=	'https://api.openweathermap.org/data/2.5/weather?q=London,uk&units=metric&APPID=YOUR_API_KEY';

// AJAX
jQuery.ajax ({
	url: apiUrl,
	type: 'GET',
	dataType: 'jsonp',
	success: function(data) {

		console.log(data);

		// COORDINATES
		var coordLat			=	data.coord.lat;
		var coordLng			=	data.coord.lon;
		
		// WEATHER
		var weatherId			=	data.weather[0].id;
		var weatherMain			=	data.weather[0].main;
		var weatherDesc			=	data.weather[0].description;
		var weatherIcon			=	'<img src="https://openweathermap.org/img/w/' + data.weather[0].icon + '.png" />';
		var weatherBg			=	data.weather[0].icon;
		
		// BASE
		var baseData			=	data.base;
		
		// TEMP
		var mainTemp			=	data.main.temp;
		var mainPressure		=	data.main.pressure;
		var mainHumidity		=	data.main.humidity;
		var mainTempMin			=	data.main.temp_min;
		var mainTempMax			=	data.main.temp_max;
		
		// VISIBILITY
		var visibility			=	data.visibility;
		
		// WIND
		var windSpeed			=	data.wind.speed;
		var windDeg				=	data.wind.deg;
		
		// CLOUDS
		var clouds				=	data.clouds.all;
		
		// DT
		var dt					=	data.dt;
		
		// SYS
		var sysType				=	data.sys.type;
		var sysId				=	data.sys.id;
		var sysMessage			=	data.sys.message;
		var sysCountry			=	data.sys.country;
		var sysSunrise			=	data.sys.sunrise;
		var sysSunset			=	data.sys.sunset;
		
		// ID
		var id					=	data.id;
		
		// NAME
		var name				=	data.name;
		
		// COD
		var cod					=	data.cod;
					
		jQuery('#city').html( name );
		jQuery('#temp').html( mainTemp + '° C' );
		jQuery('#desc').html( weatherDesc );
	}
	
});
#weatherbox {
  width: 200px;
  height: 20px;
  background: #b4ecff;
  border-radius: 8px;
  display: table;
  margin: 20px auto;
  text-align: center;
  font-size: 14px;
  line-height: 20px;
  overflow:hidden;
  padding: 0 0 10px 0;
}
strong,
span {
  width: 100%;
  display: inline-block;
  padding: 10px 0;
  margin: 0;
}
p {
  padding: 0;
  margin: 0
}
strong {
  background: #00769d;
  color: #fff;
  text-transform: uppercase;
  letter-spacing: 1px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="weatherbox">

  <strong id="city"></strong>
  <span id="temp"></span>
  <p id="desc"></p>

</div>


来源:https://stackoverflow.com/questions/27639668/open-weather-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!