2015年2月7日土曜日

[自作アプリ/Cordova]GPSスピードメーター制作(3) --- jQuery Rotateで速度に合わせて指針を回転させる

前回の「[自作アプリ/Cordova]GPSスピードメーター制作(2) --- Photoshopでメーターをデザインする」はメーターのデザインでしたが、それだけではメーターの針は動きません。

今回はjQuery Rotateを使ってメーターの指針を動かすようにします!


↓こんな感じ




まずはjQuery本体とjQuery Rotateをダウンロード、Cordovaプロジェクトフォルダの"/assets/www/"にコピーしておきます。

jQuery:

jQuery Rotate:

前回作ったメーターと指針の透過PNG画像を同じく"/assets/www/"にコピーします。

index.htmlでjQueryとjQuery Rotateをインポートします。

html:css,javascriptインポート

<title>Speed Meter</title>
<link href="jquery.mobile-1.4.5.min.css" rel="stylesheet"></link>
<script charset="utf-8" src="jquery-1.11.1.min.js" type="text/javascript"></script>
<script charset="utf-8" src="jquery.mobile-1.4.5.min.js" type="text/javascript"></script>
<script charset="utf-8" src="jQueryRotateCompressed.js" type="text/javascript"></script>


javascriptでは速度に合わせて指針をどのくらい回転させるかを計算させます。 今回は1メモリあたり9°で5km/hにしているので、
速度[km/h] * 1.8[deg]
で計算しています。
ちなみに速度はm/sからkm/hに変換、小数点以下を四捨五入しています! あとはGeolocationAPIの速度を取得する部分に$().rotateを挿入するだけです!

javascript:

// 移動速度
var speed = position.coords.speed;
$('#speed').html(Math.round(speed * 3.6));
$('#pin').rotate(Math.round(speed * 6.48)); // 3.6[km/h] * 1.8[deg]


html:メーター表示

<div class="ui-content" id="main" role="main">
<img id="meter" src="meter.png" />
<img id="pin" src="pin.png" />
<div id="speed"></div>
</div>


これで完成です!

めちゃくちゃ簡単ですよね?え、面倒くさい?(´・ω・`)そんなー


ちなみにjavascriptのところをこんな感じにすると速度がnullだったときに0km/hを表示してくれます。
// 移動速度
var speed = position.coords.speed;
if (speed == null){
 speed = 0;
 $('#speed').html("0");
 $('#pin').rotate(0);
}else{
 $('#speed').html(Math.round(speed * 3.6));
 $('#pin').rotate(Math.round(speed * 6.48)); // 3.6[km/h] * 1.8[deg]
}
にほんブログ村 スマホ・携帯ブログへにほんブログ村 IT技術ブログ Androidアプリ開発へにほんブログ村 IT技術ブログへ

0 件のコメント:

コメントを投稿