やりたかったこと
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}
処理終わってる?
実際の結果↓
実行結果から、関数の処理より先にログ出力の処理がされている。
何が起こっているのか?
どうやら、navigator.geolocation.getCurrentPositionは非同期処理で動いているようです。
geoloctionAPIの使い方についての記事を調べると、この関数をそのまま使っている記事もあったので、もしかしてVue.jsで使うと挙動が違うのかな?
と思いましたが、codePenで挙動を確認したところそんなことはありませんでした。
完成形
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を使ったのが初めてだったので、書き方が拙いところがあるかもしらません。
もし、同じように悩んでいる方が居たら少しでも助けになればと思います。
参考