0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Vue】Geolocation APIで現在地情報を取得する

Last updated at Posted at 2022-12-06

実装

JSのGeolocation API を使用することで簡単にユーザーの位置情報を取得することができます。
今回はVue3のcomposition api の中で使用しています。

import { ref, onBeforeMount} from 'vue'
import VueGeolocation from 'vue3-geolocation'

//現在地情報を取得する関数を用意
const current = ref({
        position: undefined,
        lat: undefined,
        lng: undefined,
        getLocation: () => {
            VueGeolocation.getLocation()
                .then((coordinates) => {
                    current.value.position = coordinates
                    current.value.lat = coordinates.lat  //緯度
                    current.value.lng = coordinates.lng  //経度
                })
                .catch((error) => {
                    console.log(error)
                })
        },
    })


//ページが読み込まれると同時に関数を呼び出す
    onBeforeMount(() => {
        current.value.getLocation()
    })

あとは使いたい場所でcurrentの値を呼び出してあげれば、位置情報を使うことができます。

cosole.log(current.value.position)
cosole.log(current.value.lat)
cosole.log(current.value.lng)
0
0
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?