Help us understand the problem. What is going on with this article?

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

概要

端末の現在地を取得する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>
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away