LoginSignup
13
5

More than 3 years have passed since last update.

Vue.jsにてGeolocation APIで取得した値をdataプロパティに設定する

Posted at

概要

端末の現在地を取得するGeolocation APIをVueで使用してみたのですが、dataプロパティに取得した結果がセットされなかったので、その時の対応を記載。

前提

Geolocation APIについては、@akkey2475さんのGeolocation APIでPCやスマホの位置情報を取得するにまとめられています。このJavaScriptのコードで、Vueにおいて位置データを取得します。

前提

取得したデータをdataプロパティにセットする際、成功時の関数に「this」をbindします。参考記事はVue method not working from inside other methodになります。

サンプルソース

現在地を取得して、緯度・経度を表示するサンプルソースです。

SamleComponemt.vue
<template>
  <div>
    <div>
      {{latitude}}{{longitude}}
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      latitude: 0,
      longitude: 0
    }
  },
  mounted() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        function(position){
          let coords = position.coords;
          // 緯度経度だけ取得
          this.latitude = coords.latitude;
          this.longitude = coords.longitude;
        }.bind(this),
        function(error) {
          // エラー処理を書く
        }
      );
    } else {
      // エラー処理を書く
    }
  }
}
</script>
13
5
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
13
5