cordova-plugin-geolocation

Android Testsuite Chrome Testsuite iOS Testsuite Lint Test

このプラグインは、緯度や経度などのデバイスの位置に関する情報を提供します。

位置情報の一般的なソースには、Global Positioning System (GPS) や、IP アドレス、RFID、WiFi および Bluetooth MAC アドレス、GSM/CDMA セル ID などのネットワーク信号から推測される位置情報が含まれます。API がデバイスの実際の位置を返すという保証はありません。

いくつかのアイデアを得るには、このページの下部にある サンプル を確認するか、リファレンス コンテンツに直接進んでください。

この API は、W3C Geolocation API 仕様 に基づいています。

警告: 位置情報データの収集と使用は、重要なプライバシーの問題を引き起こします。アプリのプライバシーポリシーでは、アプリがどのように位置情報データを使用するか、他の当事者と共有するかどうか、およびデータの精度レベル(例えば、粗い、細かい、郵便番号レベルなど)について説明する必要があります。位置情報データは、ユーザーの居場所や、保存されている場合は移動履歴を明らかにする可能性があるため、一般的に機密性が高いとみなされます。したがって、アプリのプライバシーポリシーに加えて、アプリが位置情報データにアクセスする前に、ジャストインタイムの通知を提供することを強く検討する必要があります(デバイスのオペレーティングシステムがすでにそうでない場合)。その通知には、上記と同じ情報を提供し、ユーザーの許可を得る必要があります(例えば、OKいいえ の選択肢を提示することにより)。詳細については、プライバシーガイド を参照してください。

このプラグインは、グローバルな navigator.geolocation オブジェクトを定義します(それ以外の場合は欠落しているプラットフォームの場合)。

オブジェクトはグローバルスコープにありますが、このプラグインによって提供される機能は、deviceready イベントの後まで使用できません。


    document.addEventListener("deviceready", onDeviceReady, false);
    function onDeviceReady() {
        console.log("navigator.geolocation works well");
    }

インストール

これには cordova 5.0+ (現在の安定版 1.0.0) が必要です

cordova plugin add cordova-plugin-geolocation

古いバージョンの cordova は、非推奨の ID (古い 0.3.12) を介してインストールできます

cordova plugin add org.apache.cordova.geolocation

リポジトリ URL を直接使用してインストールすることも可能です(不安定)

cordova plugin add https://github.com/apache/cordova-plugin-geolocation.git

サポートされているプラットフォーム

  • Android
  • iOS
  • Windows

メソッド

  • navigator.geolocation.getCurrentPosition
  • navigator.geolocation.watchPosition
  • navigator.geolocation.clearWatch

オブジェクト (読み取り専用)

  • Position
  • PositionError
  • Coordinates

navigator.geolocation.getCurrentPosition

デバイスの現在の位置を、パラメータとして Position オブジェクトを使用して geolocationSuccess コールバックに返します。エラーがある場合、geolocationError コールバックに PositionError オブジェクトが渡されます。

navigator.geolocation.getCurrentPosition(geolocationSuccess,
                                         [geolocationError],
                                         [geolocationOptions]);

パラメータ

  • geolocationSuccess: 現在の位置が渡されるコールバック。

  • geolocationError: (オプション) エラーが発生した場合に実行されるコールバック。

  • geolocationOptions: (オプション) 位置情報オプション。


    // onSuccess Callback
    // This method accepts a Position object, which contains the
    // current GPS coordinates
    //
    var onSuccess = function(position) {
        alert('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');
    };

    // onError Callback receives a PositionError object
    //
    function onError(error) {
        alert('code: '    + error.code    + '\n' +
              'message: ' + error.message + '\n');
    }

    navigator.geolocation.getCurrentPosition(onSuccess, onError);

iOS の特異性

iOS 10 以降では、プライバシーに関わるデータにアクセスしようとする場合、info.plist に使用目的の説明を提供することが必須になりました。システムがユーザーにアクセスを許可するように促すと、この使用目的の説明文字列が許可ダイアログボックスの一部として表示されますが、使用目的の説明を提供しなかった場合、ダイアログを表示する前にアプリがクラッシュします。また、Apple はプライベートデータにアクセスするが使用目的の説明を提供しないアプリを拒否します。

このプラグインには、次の使用目的の説明が必要です

  • NSLocationWhenInUseUsageDescription は、アプリがユーザーの位置情報にアクセスする理由を説明します。これはアプリがフォアグラウンドで実行されているときに使用されます。
  • NSLocationAlwaysAndWhenInUseUsageDescription は、アプリが常にユーザーの位置情報へのアクセスを要求する理由を説明します。iOS アプリがバックグラウンドおよびフォアグラウンドで実行中に位置情報にアクセスする場合は、このキーを使用します。
  • NSLocationAlwaysUsageDescription は、アプリが常にユーザーの位置情報へのアクセスを要求する理由を説明します。アプリがバックグラウンドで位置情報にアクセスし、iOS 11 より前のターゲットにデプロイする場合は、このキーを使用します。iOS 11 以降の場合は、NSLocationAlwaysUsageDescriptionNSLocationAlwaysAndWhenInUseUsageDescription の両方を、同じメッセージでアプリの Info.plist ファイルに追加します。

これらのエントリを info.plist に追加するには、config.xmledit-config タグをこのように使用できます

<edit-config target="NSLocationWhenInUseUsageDescription" file="*-Info.plist" mode="merge">
    <string>need location access to find things nearby</string>
</edit-config>
<edit-config target="NSLocationAlwaysAndWhenInUseUsageDescription" file="*-Info.plist" mode="merge">
    <string>need location access to find things nearby</string>
</edit-config>
<edit-config target="NSLocationAlwaysUsageDescription" file="*-Info.plist" mode="merge">
    <string>need location access to find things nearby</string>
</edit-config>

Android の特異性

歴史的な理由から、このプラグインは Android デバイスで GPS ハードウェアを必要とするため、ハードウェアがないデバイスではアプリを実行できません。アプリでこのプラグインを使用したいが、デバイスで実際の GPS ハードウェアを必要としない場合は、変数 *GPS_REQUIRED* を false に設定してプラグインをインストールしてください

cordova plugin add cordova-plugin-geolocation --variable GPS_REQUIRED="false"

位置情報サービスがオフになっている場合、onError コールバックは timeout 間隔(指定されている場合)の後に呼び出されます。timeout パラメータが指定されていない場合、コールバックは呼び出されません。

navigator.geolocation.watchPosition

位置の変更が検出されたときに、デバイスの現在の位置を返します。デバイスが新しい位置を取得すると、geolocationSuccess コールバックはパラメータとして Position オブジェクトを使用して実行されます。エラーがある場合、geolocationError コールバックはパラメータとして PositionError オブジェクトを使用して実行されます。

var watchId = navigator.geolocation.watchPosition(geolocationSuccess,
                                                  [geolocationError],
                                                  [geolocationOptions]);

パラメータ

  • geolocationSuccess: 現在の位置が渡されるコールバック。

  • geolocationError: (オプション) エラーが発生した場合に実行されるコールバック。

  • geolocationOptions: (オプション) 位置情報オプション。

戻り値

  • String: 位置の監視間隔を参照する監視 ID を返します。監視 ID は、位置の変更の監視を停止するために navigator.geolocation.clearWatch で使用する必要があります。


    // onSuccess Callback
    //   This method accepts a `Position` object, which contains
    //   the current GPS coordinates
    //
    function onSuccess(position) {
        var element = document.getElementById('geolocation');
        element.innerHTML = 'Latitude: '  + position.coords.latitude      + '<br />' +
                            'Longitude: ' + position.coords.longitude     + '<br />' +
                            '<hr />'      + element.innerHTML;
    }

    // onError Callback receives a PositionError object
    //
    function onError(error) {
        alert('code: '    + error.code    + '\n' +
              'message: ' + error.message + '\n');
    }

    // Options: throw an error if no update is received every 30 seconds.
    //
    var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 30000 });

geolocationOptions

位置情報の Position の取得をカスタマイズするためのオプションのパラメータ。

{ maximumAge: 3000, timeout: 5000, enableHighAccuracy: true };

オプション

  • enableHighAccuracy: アプリケーションが可能な限り最良の結果を必要とするヒントを提供します。デフォルトでは、デバイスはネットワークベースの方法を使用して Position を取得しようとします。このプロパティを true に設定すると、フレームワークは衛星測位などのより正確な方法を使用するように指示されます。(Boolean)

  • timeout: navigator.geolocation.getCurrentPosition または geolocation.watchPosition の呼び出しから対応する geolocationSuccess コールバックが実行されるまでに許可される最大時間 (ミリ秒)。geolocationSuccess コールバックがこの時間内に呼び出されない場合、geolocationError コールバックに PositionError.TIMEOUT エラーコードが渡されます。(geolocation.watchPosition と組み合わせて使用する場合、geolocationError コールバックは timeout ミリ秒ごとに間隔で呼び出される可能性があることに注意してください!)(Number)

  • maximumAge: 指定された時間(ミリ秒)を超えないキャッシュされた位置を受け入れます。(Number)

Android の特異性

位置情報サービスがオフになっている場合、onError コールバックは timeout 間隔(指定されている場合)の後に呼び出されます。timeout パラメータが指定されていない場合、コールバックは呼び出されません。

navigator.geolocation.clearWatch

watchID パラメータで参照されるデバイスの位置の変更の監視を停止します。

navigator.geolocation.clearWatch(watchID);

パラメータ

  • watchID: クリアする watchPosition 間隔の ID。(String)


    // Options: watch for changes in position, and use the most
    // accurate position acquisition method available.
    //
    var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { enableHighAccuracy: true });

    // ...later on...

    navigator.geolocation.clearWatch(watchID);

Position

位置情報 API によって作成された Position の座標とタイムスタンプが含まれています。

プロパティ

  • coords: 地理座標のセット。(Coordinates)

  • timestamp: coords の作成タイムスタンプ。(DOMTimeStamp)

Coordinates

Coordinates オブジェクトは、現在の位置のリクエストでコールバック関数で使用できる Position オブジェクトに添付されています。これには、位置の地理座標を記述する一連のプロパティが含まれています。

プロパティ

  • latitude: 10進数度の緯度。(Number)

  • longitude: 10進数度の経度。(Number)

  • altitude: 楕円体より上の位置の高さ(メートル単位)。(Number)

  • accuracy: 緯度および経度座標の精度レベル(メートル単位)。(Number)

  • altitudeAccuracy: 高度座標の精度レベル(メートル単位)。(Number)

  • heading: 真北を基準に時計回りに度で指定された移動方向。(Number)

  • speed: デバイスの現在の対地速度(メートル/秒単位)。(Number)

Android の特異性

altitudeAccuracy: Android デバイスではサポートされておらず、null を返します。

PositionError

PositionError オブジェクトは、navigator.geolocation でエラーが発生した場合に geolocationError コールバック関数に渡されます。

プロパティ

  • code: 以下にリストされている定義済みのエラーコードのいずれか。

  • message: 発生したエラーの詳細を説明するエラーメッセージ。

定数

  • PositionError.PERMISSION_DENIED
    • ユーザーがアプリによる位置情報の取得を許可しない場合に返されます。これはプラットフォームに依存します。
  • PositionError.POSITION_UNAVAILABLE
    • デバイスが位置を取得できない場合に返されます。一般的に、これはデバイスがネットワークに接続されていないか、衛星からの測位ができないことを意味します。
  • PositionError.TIMEOUT
    • デバイスが geolocationOptions に含まれる timeout で指定された時間内に位置を取得できない場合に返されます。navigator.geolocation.watchPosition と共に使用する場合、このエラーは timeout ミリ秒ごとに geolocationError コールバックに繰り返し渡される可能性があります。

サンプル: 天気を取得し、店舗を見つけ、Geolocation を使用して近くのものの写真を表示する

このプラグインを使用して、ユーザーが近くにある Groupon のお得な情報、売り出し中の家、上映中の映画、スポーツやエンターテイメントイベントなどを見つけるのを支援します。

ここでは、アプリ開発を始めるための「レシピ集」のようなアイデアをご紹介します。以下のスニペットでは、これらの機能をアプリに追加する基本的な方法をいくつか示します。

現在地の地理座標を取得する


function getWeatherLocation() {

    navigator.geolocation.getCurrentPosition
    (onWeatherSuccess, onWeatherError, { enableHighAccuracy: true });
}

天気予報を取得する


// 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');
}

移動中に更新された天気予報を受信する


// Watch your changing position

function watchWeatherPosition() {

    return navigator.geolocation.watchPosition
    (onWeatherWatchSuccess, onWeatherError, { enableHighAccuracy: true });
}

// Success callback for watching your changing position

var onWeatherWatchSuccess = function (position) {

    var updatedLatitude = position.coords.latitude;
    var updatedLongitude = position.coords.longitude;

    if (updatedLatitude != Latitude && updatedLongitude != Longitude) {

        Latitude = updatedLatitude;
        Longitude = updatedLongitude;

        // Calls function we defined earlier.
        getWeather(updatedLatitude, updatedLongitude);
    }
}

地図上で現在地を確認する

BingとGoogleの両方が地図サービスを提供しています。ここではGoogleのサービスを使用します。キーが必要ですが、試用するだけであれば無料です。

mapsサービスへの参照を追加します。


 <script src="https://maps.googleapis.com/maps/api/js?key=Your_API_Key"></script>

次に、それを使用するコードを追加します。


var Latitude = undefined;
var Longitude = undefined;

// Get geo coordinates

function getMapLocation() {

    navigator.geolocation.getCurrentPosition
    (onMapSuccess, onMapError, { enableHighAccuracy: true });
}

// Success callback for get geo coordinates

var onMapSuccess = function (position) {

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

    getMap(Latitude, Longitude);

}

// Get map by using coordinates

function getMap(latitude, longitude) {

    var mapOptions = {
        center: new google.maps.LatLng(0, 0),
        zoom: 1,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map
    (document.getElementById("map"), mapOptions);


    var latLong = new google.maps.LatLng(latitude, longitude);

    var marker = new google.maps.Marker({
        position: latLong
    });

    marker.setMap(map);
    map.setZoom(15);
    map.setCenter(marker.getPosition());
}

// Success callback for watching your changing position

var onMapWatchSuccess = function (position) {

    var updatedLatitude = position.coords.latitude;
    var updatedLongitude = position.coords.longitude;

    if (updatedLatitude != Latitude && updatedLongitude != Longitude) {

        Latitude = updatedLatitude;
        Longitude = updatedLongitude;

        getMap(updatedLatitude, updatedLongitude);
    }
}

// Error callback

function onMapError(error) {
    console.log('code: ' + error.code + '\n' +
        'message: ' + error.message + '\n');
}

// Watch your changing position

function watchMapPosition() {

    return navigator.geolocation.watchPosition
    (onMapWatchSuccess, onMapError, { enableHighAccuracy: true });
}

近くの店舗を検索する

これにも同じGoogleキーを使用できます。

placesサービスへの参照を追加します。


<script src=
"https://maps.googleapis.com/maps/api/js?key=Your_API_Key&libraries=places">
</script>

次に、それを使用するコードを追加します。


var Map;
var Infowindow;
var Latitude = undefined;
var Longitude = undefined;

// Get geo coordinates

function getPlacesLocation() {
    navigator.geolocation.getCurrentPosition
    (onPlacesSuccess, onPlacesError, { enableHighAccuracy: true });
}

// Success callback for get geo coordinates

var onPlacesSuccess = function (position) {

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

    getPlaces(Latitude, Longitude);

}

// Get places by using coordinates

function getPlaces(latitude, longitude) {

    var latLong = new google.maps.LatLng(latitude, longitude);

    var mapOptions = {

        center: new google.maps.LatLng(latitude, longitude),
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP

    };

    Map = new google.maps.Map(document.getElementById("places"), mapOptions);

    Infowindow = new google.maps.InfoWindow();

    var service = new google.maps.places.PlacesService(Map);
    service.nearbySearch({

        location: latLong,
        radius: 500,
        type: ['store']
    }, foundStoresCallback);

}

// Success callback for watching your changing position

var onPlacesWatchSuccess = function (position) {

    var updatedLatitude = position.coords.latitude;
    var updatedLongitude = position.coords.longitude;

    if (updatedLatitude != Latitude && updatedLongitude != Longitude) {

        Latitude = updatedLatitude;
        Longitude = updatedLongitude;

        getPlaces(updatedLatitude, updatedLongitude);
    }
}

// Success callback for locating stores in the area

function foundStoresCallback(results, status) {

    if (status === google.maps.places.PlacesServiceStatus.OK) {

        for (var i = 0; i < results.length; i++) {

            createMarker(results[i]);

        }
    }
}

// Place a pin for each store on the map

function createMarker(place) {

    var placeLoc = place.geometry.location;

    var marker = new google.maps.Marker({
        map: Map,
        position: place.geometry.location
    });

    google.maps.event.addListener(marker, 'click', function () {

        Infowindow.setContent(place.name);
        Infowindow.open(Map, this);

    });
}

// Error callback

function onPlacesError(error) {
    console.log('code: ' + error.code + '\n' +
        'message: ' + error.message + '\n');
}

// Watch your changing position

function watchPlacesPosition() {

    return navigator.geolocation.watchPosition
    (onPlacesWatchSuccess, onPlacesError, { enableHighAccuracy: true });
}

周辺のものの写真を見る

デジタル写真には、写真が撮影された場所を特定する地理座標が含まれている場合があります。

Flickr APIを使用して、近くで撮影された写真を探します。Googleサービスと同様に、キーが必要ですが、試用するだけであれば無料です。


var Latitude = undefined;
var Longitude = undefined;

// Get geo coordinates

function getPicturesLocation() {

    navigator.geolocation.getCurrentPosition
    (onPicturesSuccess, onPicturesError, { enableHighAccuracy: true });

}

// Success callback for get geo coordinates

var onPicturesSuccess = function (position) {

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

    getPictures(Latitude, Longitude);
}

// Get pictures by using coordinates

function getPictures(latitude, longitude) {

    $('#pictures').empty();

    var queryString =
    "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=Your_API_Key&lat="
    + latitude + "&lon=" + longitude + "&format=json&jsoncallback=?";

    $.getJSON(queryString, function (results) {
        $.each(results.photos.photo, function (index, item) {

            var photoURL = "http://farm" + item.farm + ".static.flickr.com/" +
                item.server + "/" + item.id + "_" + item.secret + "_m.jpg";

            $('#pictures').append($("<img />").attr("src", photoURL));

           });
        }
    );
}

// Success callback for watching your changing position

var onPicturesWatchSuccess = function (position) {

    var updatedLatitude = position.coords.latitude;
    var updatedLongitude = position.coords.longitude;

    if (updatedLatitude != Latitude && updatedLongitude != Longitude) {

        Latitude = updatedLatitude;
        Longitude = updatedLongitude;

        getPictures(updatedLatitude, updatedLongitude);
    }
}

// Error callback

function onPicturesError(error) {

    console.log('code: ' + error.code + '\n' +
        'message: ' + error.message + '\n');
}

// Watch your changing position

function watchPicturePosition() {

    return navigator.geolocation.watchPosition
    (onPicturesWatchSuccess, onPicturesError, { enableHighAccuracy: true });
}