Establish the geolocation within the data object once Vue.js has been mounted

Just dipping my toes into the world of VueJS. I've got a side project in the works that hinges on fetching User's Geolocation Data right after the main component has mounted.

My code snippet is as follows:

var app = new Vue({
  el: '#app', 
  data: {
    position: null
  },
  mounted: function() {
    if(navigator.geolocation){
       navigator.geolocation.getCurrentPosition(function(position){
        this.position = position.coords;
      })
    }

  }
});

I've been attempting to update the position in the data object with the current geolocation upon mounting, however, it doesn't seem to be working. Am I overlooking something?

Answer №1

There seems to be a context issue here, where the navigator inside is bound to the wrong context. This means that when you use this.position, the this keyword does not refer to the Vue object.

To solve this problem, you can make use of arrow functions:

  mounted: function() {
    if(navigator.geolocation){
       navigator.geolocation.getCurrentPosition(position => {
        this.position = position.coords;
      })
    }
  }

Alternatively, you can declare a variable before the navigator object to hold the correct context:

  mounted: function() {
    if(navigator.geolocation) {
       var self = this;
       navigator.geolocation.getCurrentPosition(function(position){
        self.position = position.coords;
      })
    }
  }

By the way, just so you know - the position.coords will return an Object with properties like latitude and longitude. If you want to access one of them specifically, you'll need to point to it like this:

self.position = position.coords.latitude;

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

Struggling with JavaScript's getElementById function

If anyone has any suggestions or alternative methods, please kindly assist me. I currently have: 1 Textbox 1 Label 1 LinkButton Upon clicking the lnk_NameEdit button, the txtUserName textbox should become visible while the lblusername label should becom ...

Connecting NGINX to a Node.js cluster with proxy_pass

After setting up both a NGINX server and a node.js process, the node.js code structure is as follows: function initiateCluster() { var numCPUs = require('os').cpus().length; if (cluster.isMaster) { // Fork workers. for (var i = 0; i ...

Struggling with sending a post request in Node.js as the response always returns with an empty body

Here is the structure of my project And this error pops up when I run my program using npm run dev command I'm working on a basic webpage where users can input their name, email, and job details. I then try to insert this information from the HTML fo ...

Problem with JWT authentication causing SockJS handshake to block WebSocket connection attempts

I have an operational Spring Boot server with Authentication/Authorization features. However, I am facing issues when trying to establish a connection with SockJS due to my security protocols blocking it. Although I do not have a complete understanding of ...

Swap out periods with commas in the content of Json Data

I have a JSON file containing percentage data that I am extracting and displaying on my website: <?php $resultData = file_get_contents('https://example.com/json/stats?_l=en'); $jsonData = json_decode($resultData, true); if( isset( ...

I am looking to retrieve a sophisticated/nested JSON data using jQuery

I need some assistance in fetching specific JSON object data. Specifically, I am looking to extract the name, poster image URL, size of the second backdrop image, and version number. As a newcomer to JSON, I was wondering if there is an easy way for me to ...

Creating a "select all" feature in an HTML multiple select box with jQuery - a step-by-step guide

I'm currently working on an HTML form that includes a multiple select box. I am looking to create a "select all" option within the multiple select box so that when a user clicks on that option, all other options in the select box are automatically sel ...

Router-view failing to display component

I am currently working on setting up basic routing in Vue. I have identified three file listings that seem to be causing issues. When I include <router-view> in app.vue, the foo component appears in the browser. However, when I follow the instruction ...

The grid fails to apply remote filtering values when an additional Nested ajax call is incorporated alongside the current HttpProxy configuration

Whenever I click for filter/sort for remote filtering, Forms.asp triggers using a proxy and automatically reloads. Previously, when I used the script below to reload the ExtJS grid with Forms.asp returning new XML with filtered grid data, everything worked ...

Troubleshooting: Imported Variable in Angular 2+ Throwing Module Not Found Error

During my testing process, I encountered an issue when trying to require a .json file with data to perform checks on. Despite passing the string indicating where to find the file into the require function, it seems to be unsuccessful... Success: const da ...

Navigate the JSON object at predetermined intervals, such as in the case of movie subtitles

Apologies if the title is not specific enough, open to any suggestions for improvement. Here's my issue: I have a JSON file (presented here as a JavaScript object) that contains subtitles for a movie. My goal is to display the text exactly as it appea ...

Steps to turn off popover functionality for a specific child element

Within a container, there are details along with a button. The container exhibits popover behavior upon hovering over it. However, the challenge lies in disabling the popover behavior while hovering specifically over the button within it. You can find th ...

Incorporating Distinct Items into an Array with JavaScript

There is a Filter object that stores information about different Car Types. The data is fetched via AJAX calls - on the first call, objects 0-10 are created and added to an array. Subsequent calls bring more car types which are also appended to the array. ...

extracting array index from a Mongoose array

//index.js let countryNameList = { "name"=["Bangladesh","India","Australia"] } //Output Section let findCountryIndex = awaitDataModel.find({$indexOfArray:{CountryName:"Bangladesh"}}) console.log(findCountryIndex); //Expecting Output : 0 I am l ...

A dynamic Angular search box designed for filtering columns in a table

I have a functioning table code that displays data related to domains: Now, I would like to enhance this table by adding a dynamic search box specifically for filtering the column named domain. As the user types in new characters in the search box, the ta ...

Combining a group of JavaScript objects

I am facing a challenge with my collection as I need to perform aggregation using only JavaScript. I have attempted various approaches utilizing the Lodash library but unfortunately, I have not been successful. If you could provide me with some guidance on ...

Vue parent component not receiving events properly

Referring to these sources: Forum Post Stack Overflow Question In my project, I am utilizing: CodeSandbox Example The setup involves the parent component listening for events emitted by a child component: mounted() { this.$on("edit-category& ...

Using JavaScript and Ruby on Rails to dynamically modify URL query parameters based on a dropdown form

I need help updating a URL based on dropdown selection. I want the query to be dynamic, and here is my current code snippet: <select id="mySchool" onchange="this.form.submit()"> <% @schools.each do |school| %> <option value="< ...

The Joi validate() function will return a Promise instead of a value when used within an asynchronous function

Trying to understand how async functions and the Joi.validate() function behave. Below is a function used for validating user input. const Joi = require("joi"); const inputJoiSchema= Joi.object().keys({ name: Joi.string(), email: Joi.string().require ...

Please do not exceed two words in the input field

I need to restrict the input field to only allow up to two words to be entered. It's not about the number of characters, but rather the number of words. Can this restriction be achieved using jQuery Validation? If not, is there a way to implement it u ...