Geolocation: getCurrentPosition() メソッド

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

安全なコンテキスト用: この機能は一部またはすべての対応しているブラウザーにおいて、安全なコンテキスト (HTTPS) でのみ利用できます。

Geolocation.getCurrentPosition() メソッドは、端末の現在位置を取得するために使われます。

構文

js
getCurrentPosition(success)
getCurrentPosition(success, error)
getCurrentPosition(success, error, options)

引数

success

コールバック関数で、 GeolocationPosition オブジェクトを唯一の入力引数として受け取ります。

error 省略可

オプションのコールバック関数で、 GeolocationPositionError オブジェクトを唯一の入力引数として受け取ります。

options 省略可

オプションのオブジェクトで、以下の引数を含みます。

maximumAge

正の long 値で、キャッシュされた位置を返すことが可能な最大時間をミリ秒単位で表します。 0 に設定した場合、端末はキャッシュされた位置を使用できず、実際の現在位置を取得する必要があることを意味します。 Infinity に設定した場合、端末はキャッシュされた位置をその古さに関係なく返さなければなりません。既定値は 0 です。

timeout

正の long 値で、端末が位置を返すために掛けることができる最大時間をミリ秒単位で表します。既定値は Infinity で、 getCurrentPosition() は位置を取得できるまで返さないという意味です。

enableHighAccuracy

論理値で、アプリケーションが可能な限り正確な結果を受け取ることを望んでいることを示します。もし true で、端末がより正確な位置を提供できる場合は、そのようにします。この場合、応答時間が遅くなったり、消費電力が増加したりすることに注意してください(たとえば、モバイル端末の GPS チップを使用する場合など)。一方、 false の場合、端末はより速く反応したり、より少ない電力を使用することで、リソースを節約することができます。既定値は false です。

返値

なし (undefined)。

js
const options = {
  enableHighAccuracy: true,
  timeout: 5000,
  maximumAge: 0,
};

function success(pos) {
  const crd = pos.coords;

  console.log("Your current position is:");
  console.log(`Latitude : ${crd.latitude}`);
  console.log(`Longitude: ${crd.longitude}`);
  console.log(`More or less ${crd.accuracy} meters.`);
}

function error(err) {
  console.warn(`ERROR(${err.code}): ${err.message}`);
}

navigator.geolocation.getCurrentPosition(success, error, options);

仕様書

Specification
Geolocation
# getcurrentposition-method

ブラウザーの互換性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
getCurrentPosition

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

関連情報