Web APIとは
WebサイトやWebサービスには、サイトにある便利な機能などが、使えるように公開されています。
例えば、Googleの地図やヤフーの口コミなどです。
そこで、そのような便利なアプリをプログラム上で利用します。
Ajaxを使って、リクエストを送り、データを受け取るまでの流れです。
APIを利用するためには、APIキーというものが必要です。またそのAPIキーがどのような目的で使うのか、どこのサイトで使うのかをきかれます。
それから、API使用権が与えられます。
①位置情報の取得
index.js
navigator.geolocation.getCurrentPosition(success, fail);
function success(pos) {
ajaxRequest(pos.coords.latitude, pos.coords.longitude);
}
② リクエスト
index.js
function ajaxRequest(lat, long) {
const url = 'https://api.openweathermap.org/data/2.5/forecast';
const appId = '保存しておいたAPI Key';
latには緯度、longには軽度が入ります。
定数urlにリクエスト先のURLを保存、APIidに保存したAPIキーを保存。
index.js
$.ajax({
url: url,
data: {
appid: appId,
lat: lat,
lon: long,
units: 'metric',
lang: 'ja'
}
})
ajaxメソッドを使って、データリクエストを送ります。
データの中はオブジェクトにします。
appid: APIキー
lat: 緯度
lon: 経度
units: データの単位
lang: 言語
③データを受け取ったとき
index.js
.done(function(data) {
// 都市名、国名
$('#place').text(data.city.name + ', ' + data.city.country);
// 天気予報データ
data.list.forEach(function(forecast, index) {
const dateTime = new Date(utcToJSTime(forecast.dt));
const month = dateTime.getMonth() + 1;
const date = dateTime.getDate();
const hours = dateTime.getHours();
const min = String(dateTime.getMinutes()).padStart(2, '0');
const temperature = Math.round(forecast.main.temp);
const description = forecast.weather[0].description;
const iconPath = `images/${forecast.weather[0].icon}.svg`;
// 現在の天気とそれ以外で出力を変える
if(index === 0) {
const currentWeather = `
<div class="icon"><img src="${iconPath}"></div>
<div class="info">
<p>
<span class="description">現在の天気:${description}</span>
<span class="temp">${temperature}</span>°C
</p>
</div>`;
$('#weather').html(currentWeather);
} else {
const tableRow = `
<tr>
<td class="info">
${month}/${date} ${hours}:${min}
</td>
<td class="icon"><img src="${iconPath}"></td>
<td><span class="description">${description}</span></td>
<td><span class="temp">${temperature}°C</span></td>
</tr>`;
$('#forecast').append(tableRow);
}
});
})
データはファンクションのパラメータに保存されています。
天気予報データdata.listに含まれていて、値は配列になっているので、foeEachで一つ一つを読み取ります。
リストの各項目がforecastに書き加えて行きます。
index.js
if(index === 0) {
const currentWeather = `
<div class="icon"><img src="${iconPath}"></div>
<div class="info">
<p>
<span class="description">現在の天気:${description}</span>
<span class="temp">${temperature}</span>°C
</p>
</div>`;
$('#weather').html(currentWeather);
} else {
const tableRow = `
<tr>
<td class="info">
${month}/${date} ${hours}:${min}
</td>
<td class="icon"><img src="${iconPath}"></td>
<td><span class="description">${description}</span></td>
<td><span class="temp">${temperature}°C</span></td>
</tr>`;
$('#forecast').append(tableRow);
}
取得した要素の書き換え
$('セレクタ').html(書き換えるHTML);
天気予報の処理
取得した要素の中の書き換え
$('セレクタ').append(挿入するHTML)