Ways to resolve an error with a setter that is throwing 'undefined'

I've been working on crafting a geolocation class to have ready for when I need it, but I've hit a snag and keep encountering this error message:

Uncaught TypeError: Cannot read property 'setLatitude' of undefined
    at setCurrentPosition (geolocation.js:13)

Any tips or advice on how to proceed?

 class Geolocation {
    constructor() {
        this.latitude = 0;
        this.longitude = 0;
    }

    getGeoLocation() {
        if ('geolocation' in navigator) {
            navigator.geolocation.getCurrentPosition(this.setCurrentPosition);
        }
    }
    setCurrentPosition(position) {
        this.setLatitude(position.coords.latitude);
        this.setLongitude(position.coords.longitude);
    }
    setLatitude(latitude) {
        this.latitude = latitude;
    }
    setLongitude(longitude) {
        this.longitude = longitude;
    }

    getLatitude() {
        return this.latitude;
    }

    getLongitude() {
        return this.longitude;
    }
}

Answer №1

Make sure to properly connect to the appropriate this:

navigator.geolocation.getCurrentPosition(this.updateCurrentPosition.bind(this))

Answer №2

The issue here is that the reference of this is not correctly pointing to the class instance of Geolocation. To resolve this, it is necessary to bind the context of this to the instance in the constructor:

constructor() {
   this.latitude = 0;
   this.longitude = 0;
   this.setCurrentPosition = this.setCurrentPosition.bind(this);
}

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

Methods for incorporating JSON Data into ChartJS

Below is my app.js file: app.js var app = angular.module('myApp', []); app.controller('MainCtrl', function($scope, $http) { $http.get('http://happyshappy.13llama.com/wp- json/llama/v1/stats').then(function(response) ...

Issue with React rendering numbers without displaying div

In my user interface, I am attempting to display each box with a 1-second delay (Box1 after 1 second, Box2 after another 1 second, and so on). https://i.sstatic.net/FdTkY.png However, instead of the desired result, I am seeing something different: https ...

Ways to transfer a value from a JavaScript file to a PHP file?

Is there a way to transfer data from a JavaScript file to a PHP file? Code: var year = (year != null) ? year : '".$this->arrToday["year"]."'; var month = (month != null) ? month : '".$this->ConvertToDecimal($this>arrTod ...

How to prompt the browser to download a file with a specific name using node.js and express

I've created a node/express website as part of my university project. It allows users to search for a specific law ID, which then displays a table with various files in different formats and languages related to that ID. I am using the "http-proxy" mo ...

What is the best way to determine the total of values from user-input fields that are created dynamically

Scenario- A scenario where a parent component is able to create and delete input fields (child components) within an app by clicking buttons. The value of each input field is captured using v-model. Issue- The problem arises when a new input field is crea ...

Is it possible to call componentDidMount() multiple times in React?

I am in the process of converting an HTML API to ReactJS. The original HTML API is as follows: <script src="//dapi.kakao.com/v2/maps/sdk.js?appkey=3199e8f198aff9d5aff73000faae6608"></script> <script> var mapContainer = document.getE ...

The function createVNode does not exist in the context of Vue integrated with Laravel

I've been attempting to replicate a component rendering based on an online example. While it works smoothly in a sample project, it crashes when applied to the official codebase. Here is the content of the blade file being rendered: <html lang=&q ...

Verify if the connection to MongoDB Atlas has been established for MongoDB

When working with MongoDB, I find myself switching between a local database during development and MongoDB Atlas in production. My goal is to implement an efficient text search method that utilizes $search when connected to MongoDB Atlas, and $text when co ...

"The authentication cookie fields are not defined when trying to get the authentication in the Express framework

After setting up my React client on port 3000 and Express on port 5000, I encountered an issue. When logging in, the cookie fields are set without any problems. However, when trying to retrieve the isauth value, it shows as undefined. //login log message ...

Creating a transcluding element directive in AngularJS that retains attribute directives and allows for the addition of new ones

I've been grappling with this problem for the past two days. It seems like it should have a simpler solution. Issue Description The objective is to develop a directive that can be used in the following manner: <my-directive ng-something="somethi ...

The attribute of the Angular div tag that lacks an equal sign

Apologies if this question has been asked before. I've noticed in some people's code that they use the following syntax: <div ui-grid="myUIGrid" ui-grid-selection ui-grid-resize-columns class="grid" /> Can someone explain what ui-grid-sel ...

Converting a Unix timestamp to a formatted date string in Firebase: A step-by-step guide

Is there a way to change a timestamp from 1333699439 to the format 2008-07-17T09:24:17? For now, I have been utilizing Firebase.ServerValue.TIMESTAMP for timestamps in Firebase. ...

The use of Next.js v12 middleware is incompatible with both node-fetch and axios

I am facing an issue while developing a middleware that fetches user data from an external endpoint using Axios. Surprisingly, Axios is not functioning properly within the middleware. Below is the error message I encountered when using node-fetch: Module b ...

ui-router: Issues with utilizing the <ui-view> element within a bespoke directive

In my current project, I am utilizing version 0.3.1 of ui-router. Within my custom directive, there is a <ui-view></ui-view> tag present. <div > <button type="button" class="btn btn-primary btn-circle btn-lg pull-left" ui-sref="u ...

Querying and Retrieving a List of Nested Documents in MongoDB

I have multiple solutions, each of which may contain various projects. To represent this relationship, I opted for embedding the projects within the solution document. For example: [{ _id: "1", solutionTitle: "Some Sample Solution", p ...

Save the value of a webpage element into a variable and utilize it across multiple JavaScript files in TestCafe

We are working in the insurance domain and have a specific scenario that we want to achieve using TestCafe: 1st step: Login into the application 2nd step: Create a claim and store the claim number in a global variable 3rd step: Use the globally declared c ...

How can I use Express JS and Mongoose to update an array of objects in MongoDB?

Encountered a TypeError: result.taskList[id].push is not a function const taskcancel = (user, pswd, id) => { return db.Todotasks.findOne({ username: user, password: pswd }).then((result) => { if (result) { console.log(result.tas ...

Struggling to interpret the array of objects retrieved from a call to UrlFetchApp.fetch in Google App Script

When UrlFetchApp.fetch is called, it provides an array of objects that are stored in the variable 'results': var results = [{"Category 1": "Benefits/Compensatio", "Category 2": "Compensation", "Category 3": "Recognizing You", "Processing Team": ...

"Can you guide me on how to display a React component in a

I have a function that loops through some promises and updates the state like this: }).then((future_data) => { this.setState({future_data: future_data}); console.log(this.state.future_data, 'tsf'); }); This outputs an array o ...

Leveraging Prototype's Class creation function to declare confidential and safeguarded attributes and functions

Looking for a solid approach to defining private and protected properties and methods in Javascript? Check out this helpful discussion here on the site. Unfortunately, the current version of Prototype (1.6.0) doesn't offer a built-in method through it ...