【问题标题】:Geolocation with vuejs and firestore使用 vuejs 和 firestore 进行地理定位
【发布时间】:2018-08-02 09:00:20
【问题描述】:

我想将地理位置点(纬度和经度)存储在 Firestore 数据库中。 所以我在vueJs 中创建了一个名为acctPosition 的新对象来存储地理点,然后我将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

【问题讨论】:

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


    【解决方案1】:

    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
          }
    }
    

    【讨论】:

    • 但是上传到firestore不行,怎么办?
    • 所以我的意思是上传工作正常,但除了 acctPosition 的空数组之外什么都没有存储
    • 我已经更新了答案。 Javascript 是异步的,所以fb.usersCollection.doc(docId).set()getCurrentPosition 完成之前执行。
    猜你喜欢
    • 2012-01-04
    • 2010-11-12
    • 2011-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多