【cordova】cordovaのプラグインで天気予報を取得する方法

コルドバプラグインの中でも比較的メジャーなプラグインの一つであるcordova-plugin-geolocationですが、

このプラグイン使えば使うほど汎用性の高いプラグインだとじわじわ思い知らされます。

例えば、今いる自分の位置情報を取ってきたり、店舗や施設の位置情報を取って更に機能を展開したりと

短いコードですぐ取得できるので初心者にも易しい取説となっております。

これだけでも便利なのですが、オプションを変更するだけで天気予報も取得できることを知って自分の中で

更に評価が上がっております。

これが使えば天気予報を教えてくれたりその天気の情報によって振る舞いを変える機能を作ったりと

多岐に渡る活躍が期待できそうです。

サンプルコードですが、数十行で事足りるのでこれから実装したいと考えている方は参考にしてみてください。

</pre>
// Success callback for get geo coordinates

var onWeatherSuccess = function (position) {

Latitude = position.coords.latitude;
Longitude = position.coords.longitude;

getWeather(Latitude, Longitude);
}

// Get weather by using coordinates

function getWeather(latitude, longitude) {

// Get a free key at http://openweathermap.org/. Replace the "Your_Key_Here" string with that key.
var OpenWeatherAppKey = "Your_Key_Here";

var queryString =
'http://api.openweathermap.org/data/2.5/weather?lat='
+ latitude + '&lon=' + longitude + '&appid=' + OpenWeatherAppKey + '&units=imperial';

$.getJSON(queryString, function (results) {

if (results.weather.length) {

$.getJSON(queryString, function (results) {

if (results.weather.length) {

$('#description').text(results.name);
$('#temp').text(results.main.temp);
$('#wind').text(results.wind.speed);
$('#humidity').text(results.main.humidity);
$('#visibility').text(results.weather[0].main);

var sunriseDate = new Date(results.sys.sunrise);
$('#sunrise').text(sunriseDate.toLocaleTimeString());

var sunsetDate = new Date(results.sys.sunrise);
$('#sunset').text(sunsetDate.toLocaleTimeString());
}

});
}
}).fail(function () {
console.log("error getting location");
});
}

// Error callback

function onWeatherError(error) {
console.log('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
<pre>
>株式会社シーポイントラボ

株式会社シーポイントラボ

TEL:053-543-9889
営業時間:9:00~18:00(月〜金)
住所:〒432-8003
   静岡県浜松市中央区和地山3-1-7
   浜松イノベーションキューブ 315
※ご来社の際はインターホンで「316」をお呼びください

CTR IMG