使用Vue.js和Firestore进行地理位置定位

时间:2018-08-02 09:00:20

标签: firebase vue.js google-cloud-firestore

我想将地理位置点(纬度和经度)存储在Firestore数据库中。 因此,我在acctPosition中创建了一个名为vueJs的新对象,将几何点存储在此处,然后我console.log将其取出并出现错误:

Cannot read property 'acctPosition' of null at eval (Geolocation.vue?dc3a:148)

第148行是var acctPos = this.acctPosition.push(pos)

地理位置组件:

    ...

    data () {
       ... 
       coords: {
         latitude: null,
         longitude: null
       },
       acctPosition: [],
       ... 
    }

    mounted () {
    ...

    var self = this;

    // Try HTML5 geolocation.
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
          var pos = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
          };
          console.log(pos)
          map.setCenter(pos);
          var acctPos = self.acctPosition.push(pos)
          console.log(acctPos)
        }
      } else {
        // Browser doesn't support Geolocation
      }


      let docId = `${this.currentUser.uid}`

      // store geoData to currentUser in firebase firestore
      fb.usersCollection.doc(docId).set({
        acctPosition: this.acctPosition
      }).then(ref => {
        console.log('work')
      }).catch(err => {
        console.log(err)
      })


   },
   ...

此后,我编写了将其存储在firebase中的代码,但得到了null

1 个答案:

答案 0 :(得分:0)

里面的

this不是Vue实例。您可以通过分配self = this或使用箭头功能来完成技巧:

   mounted () {
    ...
     var self = this;
    // Try HTML5 geolocation.
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
          var pos = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
          };
          console.log(pos)
          map.setCenter(pos);
          var acctPos = self.acctPosition.push(pos)
          console.log(acctPos)

          let docId = `${self.currentUser.uid}`

          // store geoData to currentUser in firebase firestore
          fb.usersCollection.doc(docId).set({
            acctPosition: self.acctPosition
          }).then(ref => {
            console.log('work')
          }).catch(err => {
            console.log(err)
          })
        }
      } else {
        // Browser doesn't support Geolocation
      }
}