使用したもの(環境)
- cordova
- visualStudioCode
- windows10
- Android
チュートリアルを訳しながらやってみる
チュートリアルのページは下記。
Module 12: Using the Location API
前回のチュートリアル。
環境構築については別途まとめてあるので下記参照。
cordova&VSCodeで環境を構築するまでの右往左往メモ。
Module 12: Using the Location API
ロケーションAPIの利用
In this section, we add the ability to tag an employee with his/her location information.
このセクションでは、従業員の位置情報をタグ付けする機能追加します。
In this sample application, we display the raw information (longitude/latitude) in an alert.
このサンプルアプリケーションでは、生の情報(緯度/経度)をアラートで表示します。
In a real-life application, we would typically save the location in the database as part of the employee information and show it on a map.
実際のアプリケーションでは、通常、従業員情報の一部としてデータベース内の位置情報を保存し、マップ上で表示します。
以下のコードはデバイス上でCordovaアプリケーションとしてアプリケーションを実行する際に機能します。
また、ページがhttp://プロトコルで提供されている場合は、Desktop上のChromeで同機能が提供されます。
Firefoxの場合、プロトコルにかかわらず提供されます。
1. geolocatonプラグインをプロジェクトに追加します。
cordova plugin add cordova-plugin-geolocation
2. index.htmlのemployee-tplテンプレートに下記を追加します。
<li class="table-view-cell media">
<a hre="#" class="push-right add-location-btn">
<span class="media-object pull-left"></span>
<div class="media-body">
Add location
</div>
</a>
</li>
3. EmployeeViewのinitializeメソッドでAdd Locationのクリックイベントを登録します。
this.$el.on('click', '.add-location-btn', this.addLocation);
4. EmployeeViewにaddLocation event handlerを定義します。
this.addLocation = function(event) {
event.preventDefault();
navigator.geolocation.getCurrentPosition(
function(position) {
alert(position.coords.latitude + ',' + position.coords.longitude);
},
function() {
alert('Error getting location');
});
return false;
};
5. アプリケーションをテストします。
位置情報をマスクした画像貼ってもあんまり意味ないので画像は割愛。
ちなみに、ChromeでもFireFoxでもfile:///からのアクセスで動作しました。