LoginSignup
5
4

More than 5 years have passed since last update.

Geolocation APIをPromiseでラップして扱う(TypeScript)

Last updated at Posted at 2018-11-26

Geolocation APIを扱う場合、awaitを使えた方が便利なことが多いので
Promiseでラップするようにしました。

sample.ts
  // API呼び出し
  getCurrentPosition() {
    return new Promise(
      (
        resolve: (value?: Position) => void,
        reject: (reason?: PositionError) => void
      ) => {
        navigator.geolocation.getCurrentPosition(resolve, reject);
      }
    );
  }

  // 使う場合はこんな感じで
  async foo() {
    const s = await this.getCurrent();
    console.log(s.coords);
    // 結果(例)
    // Coordinates {latitude: 35.681167, longitude: 139.767052,
    // altitude: null, accuracy: 40, altitudeAccuracy: null, …}
  }

何かの役に立てば幸いです。

5
4
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
5
4