LoginSignup
0
0

More than 5 years have passed since last update.

cordovaプラグインとOpenWeatherMapで天気予報

Last updated at Posted at 2018-11-20

1.Pluginインストール

$ cordova plugin add cordova-plugin-geolocation

2.Plugin動作確認

var onSuccess = function(position){
console.log
             ('Latitude: '          + position.coords.latitude          + '\n' +
              'Longitude: '         + position.coords.longitude         + '\n' +
              'Altitude: '          + position.coords.altitude          + '\n' +
              'Accuracy: '          + position.coords.accuracy          + '\n' +
              'Altitude Accuracy: ' + position.coords.altitudeAccuracy  + '\n' +
              'Heading: '           + position.coords.heading           + '\n' +
              'Speed: '             + position.coords.speed             + '\n' +
              'Timestamp: '         + position.timestamp                + '\n');
};

スクリーンショット 2018-11-20 20.39.27.png
成功例です(RHEMS技研での座標)

   項目     意味
Latitude 緯度
Longitude 経度
Altitude 高度
Accuracy 正確さ
Timestamp UNIX時刻

*UNIX時刻は1970年1月1日0時0分からの経過時間

3.OpenWeatherMap

OpenWeatherMapは、開発者向けにAPIを無料で提供しているサイトです(有料プランあり)
今回は無料プランをつかってやっていきます

4.実際に使ってみる

$(function(){
        var apikey = '**************';
        var lon = position.coords.longitude ;
        var lat = position.coords.latitude ;
        var url = `https://api.openweathermap.org/data/2.5/weather?lon=` + lon + `&lat=` + lat + `&units=metric&APPID=` + apikey;
        $.ajax({
            url: url,
            dataType:`json`,
            type: `GET`,
        })
        .done(function(data){
            console.log(data)

        })
        .fail(function(data){   
            console.log("failed");
        });
    });

成功例

スクリーンショット 2018-11-20 20.55.29.png

説明

スマホやPCで位置情報を取り、APIkeyと一緒にOpenWeatherMapに渡して、JSONで取得するという流れです
units=metricは温度の単位をケルビンから摂氏に変えるものです
Ajaxを使うときは下の一行をheadに追加しましょう

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

console.logのvisibilityは視界(単位はメートル、何メートル先まで見えるかみたいな)

今回はCordovaのプラグインを使ったので座標を指定して使ったが、都市の名前を使って天気予報を受け取る事もできる

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0