Issues with Firebase Firestore and Vuejs Integration

I'm having trouble storing my geopoints to the firestore database. I made an array named acctPosition to hold the geopoints, but when I check Firebase, it seems like nothing is being stored.

How can I properly store the geopoints?

The result:

https://i.sstatic.net/OHmaE.png

The Geolocation component:

    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)
          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.acctPos
      }).then(ref => {
        console.log('work')
      }).catch(err => {
        console.log(err)
      })
    }

Answer №1

One thing to keep in mind is that JavaScript operates asynchronously, meaning that

fb.usersCollection.doc(docId).set()
may execute before getCurrentPosition completes its task.

To ensure that the data is pushed to Firebase only after getCurrentPosition has finished, you can make use of the following code snippet:

mounted () {
    ...
     var self = this;
    // Utilize HTML5 geolocation feature.
      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 once geolocation is obtained
          fb.usersCollection.doc(docId).set({
            acctPosition: self.acctPosition
          }).then(ref => {
            console.log('work')
          }).catch(err => {
            console.log(err)
          })
        }
      } else {
        // Geolocation is not supported by the browser
      }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Add some TD(s) after the td element

The HTML code I currently have is as follows: <tr> <td class="success" rowspan="1">Viability</td> <td data-rowh="-Checksum">Viability-Checksum</td> </tr> <tr> ...

Unable to retrieve data function properties within Vue.Js Component methods

Looking for some help with setting up a welcome message using an input field in Vue.js. I am trying to store the username in a data property called username: ''. However, when I attempt to access it within the methods, I receive an error stating ...

Acquire JSON data structures using Node.js

I've been struggling to find a solution using just keywords - endless scrolling, yet all I can find are tutorials on getting data from JSON structure, rather than getting data structure from JSON. If you're unsure what my end goal is, here are s ...

Adding several lines of HTML content from an object using jQuery's append method

Currently, this is what I have: $(document).ready(function() { $.ajax({ type:"GET" , url:'{{url("/api/getcart")}}' , dataType:"json", success: function(data){ $('#price').append(data.cartitems[1].product.pr ...

How to update an Array<Object> State in ReactJS without causing mutation

In my program, I store an array of objects containing meta information. This is the format for each object. this.state.slotData [{ availability: boolean, id: number, car: { RegistrationNumber : string, ...

Nuxt js is throwing an error stating that it is unable to locate the pages directory

I have made changes to the folder structure of my Nuxt.js project. I am encountering an issue: Error - Couldn't find a pages directory in D:\sample. How can I access the pages? .nuxt, app, node_modules, server, .eslintrc, package, package-lock ...

Retrieve the Checked Value of a Checkbox Using Ajax Post in MVC

Can anyone provide assistance? This is the code I am working with: Index.cshtml <!DOCTYPE html> <html> <head> <title>jQuery With Example</title> @Scripts.Render("~/bundles/jquery") <script type="text/javascri ...

What's the best way to align three images in a row?

I am having trouble centering three social media icons next to each other. I can't seem to figure out the proper way to do it. https://i.stack.imgur.com/Zf5p9.png <div class="maintext flipInX animated"> <div class="socials wow bounce an ...

What is the process for changing the name of a key in a MongoDB response

I am reviewing the following code snippet: // retrieve a specific question app.get('/:id', (req, res) => { Question.findById(req.params.id, function(err, response){ if (err) { return res.status(404).send(); } ...

Tips for utilizing the useContext hook in Next.js

I'm facing an issue with persisting information between different pages using nextjs and the useContext hook. Despite changing a variable in one page, it reverts back to its default value when navigating to another page. Below is a glimpse of the dir ...

Walls that collide in three.js

I am currently developing a game using three.js and despite being new to this field, I have extensively studied collision documentation. To handle collisions between my boat (inside a cube) and the islands (contained in cubes), I implemented raycasting. He ...

Adjust the height of a div based on the font size and number of lines

I'm trying to create a function that automatically sets the height of a div by counting lines. I managed to get it partially working, but then it stopped. Can someone please help me with this? function set_height() { var div_obj=document.getEleme ...

Only initiate an AJAX call if there are no other pending AJAX requests from prior function invocations

Arriving at a new, chaotic code base with no testing available has presented me with a significant challenge. I am currently struggling to resolve an issue without the use of ES6, only relying on plain vanilla JS and jQuery. The scenario: Within a web pag ...

Steady Navigation Bar in Javascript without Bouncing

While experimenting with a fixed navigation bar, I've encountered an issue where the content below jumps up on the page when the navigation bar "fixes" itself to the top of the screen. You can check out the JSFiddle I've been working on for refer ...

Transmitting information from directive to parent scope controller

I've successfully implemented a directive that generates a Google map on the page. Now, my goal is to pass the map object back out of the directive and into the parent controller. This will allow me to utilize it in various methods as needed. While ...

Issues with testing incorporating jest, react, webpack, and SVG

I recently delved into the world of React development, but I've hit a snag when trying to run a test with an SVG file. You can find the code in my GitHub repository https://github.com/alejomongua/react-playground. Upon running npm run test, I encoun ...

Transform an array of objects into a nested tree structure with Javascript

I am currently facing a challenge with handling a complex json file using javascript to structure it hierarchically. My goal is to convert an array of objects into a deeply nested array, where there can be multiple divNames with varying categories and subc ...

Click trigger on button in vue-test-util is not activating

I am facing an issue with my Vue component that contains a button triggering a method on click. I am currently using Jest for unit testing. I expected the .trigger method from vue-test-utils to generate a synthetic event on the button, but it seems to be i ...

Obtaining the local IP address of my system with React JS

Is there a way to retrieve the local IP of my computer within a React JS application? I would appreciate any suggestions on how to accomplish this. ...

Guide on how to beautify HTML and generate output files in the identical directory as the current one

Hey there! I'm currently working as a junior front-end developer and have recently delved into using gulp. One of the challenges I face is dealing with HTML files received from senior developers that aren't well-formatted, containing excessive wh ...