LoginSignup
0
0

More than 1 year has passed since last update.

GeolocationAPIが止まらなくて困った話

Posted at

やりたかったこと

Vue.jsでGeolocationAPIを使って現在地を取得したい。

実行環境

Laravel:7.20.0
Vue.js:3.2.37
docker:3

初期のコード

LocationSerach.vue
<script>
export default {
    methods: {
        getCurrentLocation: function () {
            console.log("処理開始");
            return navigator.geolocation.getCurrentPosition((position) => {
                console.log("処理中だよ!");
                let coords = position.coords;
                let current = {
                    latitude: coords.latitude,
                    longitude: coords.longitude,
                };
                console.log("処理終了");
            });
        },
    },
    mounted() {
        let currentLocation = this.getCurrentLocation();
        console.log(currentLocation);
        console.log("処理終わってる?");
    },
};
</script>
# 期待する結果
処理開始
処理中だよ!
処理終了
{latitude: xxx, longitude: yyy}
処理終わってる?

実際の結果↓
スクリーンショット 2022-06-20 19.38.05.png
実行結果から、関数の処理より先にログ出力の処理がされている。

何が起こっているのか?

どうやら、navigator.geolocation.getCurrentPositionは非同期処理で動いているようです。
geoloctionAPIの使い方についての記事を調べると、この関数をそのまま使っている記事もあったので、もしかしてVue.jsで使うと挙動が違うのかな?
と思いましたが、codePenで挙動を確認したところそんなことはありませんでした。
スクリーンショット 2022-06-20 20.24.26.png

完成形

async/awaitで処理を待ってもらうように実装しました。
mountedにasyncをつけられるのがわからず、無名関数をでやろうとして詰まってました(汗

LocationSerach.vue
<script>
export default {
    methods: {
        getCurrentLocation: function () {
            return await new Promise((resolve, reject) => {
                navigator.geolocation.getCurrentPosition((position) => {
                    let coords = position.coords;
                    let current = {
                        latitude: coords.latitude,
                        longitude: coords.longitude,
                    };
                    resolve(current);
                });
            });
        },
    },
    async mounted() {
        let currentLocation = await this.getCurrentLocation();
        console.log(currentLocation);
    },
};
</script>

最後に

今回Promiseやasync/awaitを使ったのが初めてだったので、書き方が拙いところがあるかもしらません。
もし、同じように悩んでいる方が居たら少しでも助けになればと思います。

参考

0
0
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
0
0