Having trouble retrieving data values from methods within my Vue.js component

I am having trouble accessing the lat and lng values from the data() method within the maps() method.

Here is a link to my Vue.js component code: https://gist.github.com/melvin2016/c8082e27b9c50964dcc742ecff853080

Here is an image of the console showing the lat and lng values: enter image description here

<script>
import Vue from 'vue';
import navbarSec from './navbarSec.vue';
export default {
  data(){
    return{
      lat: '',
      lng: '',
      mapState: window.mapState,
      from:'',
      to:'',
      placesFrom:[],
      placesTo:[]
    };
  },
  components:{
    'navbar': navbarSec
  },
  created(){
    var token = this.$auth.getToken();
    this.$http.post('http://localhost:3000/book', {}, {headers: {'auth':token}}).then(function(data){
      this.session = true;
    })
    .catch(function(data){
      this.session = false;
      this.$auth.destroyToken();
      Materialize.toast(data.body.message, 6000,'rounded');
      this.$router.push('/login');
    });
    if(navigator.geolocation){
      navigator.geolocation.getCurrentPosition((data)=>{
        this.lat = data.coords.latitude;
        this.lng = data.coords.longitude;
        this.from=data.coords.latitude+' , '+data.coords.longitude;
      });
    }else{
      Materialize.toast("Cannot Get Your Current Location !", 6000,'rounded');
    }
  },
  mounted(){
    if (this.mapState.initMap) {// map is already ready
      var val = this.mapState.initMap;
      console.log(val);
      this.maps();
    }
  },
  watch: {
    // we watch the state for changes in case the map was not ready when this
    // component is first rendered
    // the watch will trigger when `initMap` will turn from `false` to `true`
    'mapState.initMap'(value){
      if(value){
        this.maps();
      }
    },
    from : function(val){
      if(val){
        var autoComplete = new google.maps.places.AutocompleteService();
        autoComplete.getPlacePredictions({input:this.from},data=>{
          this.placesFrom=data;
        });
      }
    },
    to:function(val){
      if(val){
        var autoComplete = new google.maps.places.AutocompleteService();
        autoComplete.getPlacePredictions({input:this.to},data=>{
          this.placesTo=data;
        });
      }
    }
  },
  methods:{
    maps(){
      var vm = this;
      var lati = vm.lat;
      var lngi = vm.lng;
      console.log(lati+' '+lngi);
      var map;
      var latlng = {lat: lati, lng:lngi };
      console.log(latlng);
      this.$nextTick(function(){
        console.log('tickkkk');
         map = new google.maps.Map(document.getElementById('maplo'), {
          zoom: 15,
          center: latlng
        });
        var marker = new google.maps.Marker({
          position: latlng,
          map: map
        });
      });
    }
  }
}
</script>

Answer №1

The reason for this issue is due to the fact that you are invoking the maps() function in the mounted lifecycle hook, while the

navigator.geolocation.getCurrentPosition((data) => {})
code has not yet been resolved. To resolve this problem, make sure to call this.maps() within the getCurrentPosition method like so:

navigator.geolocation.getCurrentPosition((data)=>{
    this.lat = data.coords.latitude;
    this.lng = data.coords.longitude;
    this.from=data.coords.latitude+' , '+data.coords.longitude;
    this.maps()
});

Although I haven't delved into details, you might consider modifying the logic inside the maps() method to eliminate the need for nextTick when making this change. This way, you can ensure that the function is called later in the cycle after everything has been rendered.

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

Unraveling deeply nested array objects in JSON with Java Script/jQuery

I need help working with a JSON file that looks like the following: {[ {"name":"avc"}, {"name":"Anna"}, {"name":"Peter"}, {"Folder":[ {"name":"John"}, {"name":"Anna"}, {"Folder":[ {"name":"gg"}, ...

Removing an object from an array when a certain key value already exists in TypeScript

I'm currently facing an issue with my function that adds objects to an array. The problem arises when a key value already exists in the array - it still gets added again, but I want it to only add if it doesn't exist yet. Here's what I have: ...

Wizard for the advanced tab panel

I am facing a challenge with my advanced TabPanel Wizard. It consists of 4 tabs, each serving as its own form to allow for validation within the tab itself. The issue I am encountering is related to the validation behavior of non-rendered tabs. One proble ...

Struggling to integrate font-awesome into my Vue.js project

Observation: The stars should be displayed using the Font Awesome font. Issue: An error font is being displayed instead of Font Awesome, indicating that it is not being loaded properly. Hello. I am encountering problems with including Font Awesome in my p ...

After initializing a Vue instance, the textContent of various HTML elements is obtained

Before and after creating a Vue instance over an element, different values of textContent are retrieved. Click here to see the issue in action To observe the varying outputs, check the console. The white space characters are being stripped off by the Vu ...

What is the best way to retrieve data from a fetch request within a GET function?

It seems like a simple issue, but I'm struggling to retrieve information from my "body" when utilizing the get method. I've experimented with various approaches to extract the data, but nothing seems to work. Any guidance would be greatly appreci ...

The passage of time becomes distorted after a few hours of using setInterval

I created a simple digital clock using JavaScript to show the time on a TV screen. However, after several hours of running, I noticed that the displayed time gets off by a few seconds (around 30 or more). Below is the code snippet I used: getTime() { ...

Separating express routes into individual files

After trying multiple solutions from Stack Overflow and various patterns for organizing routes in Node.js, I still can't seem to get it right. The endpoint either throws errors or returns a 404. Despite following suggestions from different sources lik ...

difficulty using workbox to cache content in vue-cli

In my development setup with vue-cli v3.0.0.beta10 and the default integrated workbox, I included this configuration in my vue.config.js file (located in the root folder): pwa: { //pwa configs... workboxOptions: { // ...other Wor ...

What is the method for extracting the value of a JavaScript variable using the .Net framework or C# programming language?

Looking at the code snippet below, I am trying to extract the values of title and videoId. These elements are part of the session, which is nested within units. I am unsure how to retrieve their values using C# or the .Net framework. Can anyone help m ...

How come props do not get updated along with state changes?

I've encountered an issue where the state of a component being passed into another component as a prop is not updating correspondingly. Various attempts have been made to resolve this, including placing it in the return function and updating the "low ...

Tips for managing onClick code when a user selects "open link in new tab" within a React js environment

How can I ensure that my tracking code runs when a user clicks a button in my React project, even if they open it in a new tab? Is there a solution for this in React JS? Here's a simple example: var Hello = React.createClass({ render: function( ...

`The height attribute of the textarea element is not being accurately adjusted`

When I tried to match the width(178px) and height(178px) of my table to the width and height of a text area upon clicking a button, I encountered an issue. While setting the width works perfectly fine, the height is being set to only 17px. It seems like ...

How to disable annoying browser ad extensions using Javascript

Is there a way to prevent browser add-ons from injecting HTML code? My website built in angularjs is experiencing routing issues due to certain browser add-ons. The following HTML snippet is causing errors in my angularjs: <script async="" src="http:/ ...

"Unexpected Type Inference Issue: A variable initially defined as a string inexplicably transforms into 'undefined'

Currently, I am incorporating the await-to-js library for handling errors (specifically utilizing the to method from the library). In an intriguing scenario, the variable type shifts to string | undefined within a for..of loop, whereas outside of the loop ...

Error: 'err' has not been defined

Recently, I embarked on creating my very first API using Mongo, Express and Node. As I attempted to establish an API endpoint for a specific user, the console threw me this error: ReferenceError: err is not defined. Curiously, the same method worked flawle ...

What is the method for including HTML special characters in d3.js?

I am attempting to incorporate the degree symbol in my HTML code using ° const degreeNum = d3 .select(`#windBox${order}`) .append("text") .attr("x", 250) .attr("y", 130) .style("font", "bold 50px sans-serif") ...

What could be the reason for Vuejs showing Promise {<pending>} in my project?

I am encountering an issue with two methods in Vue.js where they return a promise pending. Here is the code: TotalIncomeData(day, branch_office_id) { return fetch('/api/collection/total/'+day+'/'+branch_office_id+'?api_ ...

Having trouble understanding how to display an HTML file using Next.JS?

Currently, I am working on a project that involves utilizing Next.JS to develop a webpage. The main goal is to display a PDF file on the left side of the screen while integrating Chaindesk on the right side to create a chat bot capable of extracting inform ...

What is the best way to display data retrieved through Ajax, jQuery, and JavaScript on an HTML page

I have successfully used the script below to fetch data from an api endpoint and populate my charts. Now, I want not only to display the data in my charts but also directly output it in my HTML code using something like the document.write() function. How ...