The mystery of the undefined return value in my Ionic v4 get function

I attempted to retrieve my location by saving the latitude and longitude, but my declared variable isn't returning anything.

Take a look at my code snippet:

public device_location: any = {};

constructor(private geolocation: Geolocation) {
  this.setGeolocation();
  this.getGeolocation();
}

setGeolocation(){
   this.geolocation.getCurrentPosition().then((resp) => {
       // resp.coords.latitude
       this.device_location.latitude = resp.coords.latitude;
       this.device_location.longitude = resp.coords.longitude;
       console.log( this.device_location.longitude);
       }).catch((error) => {
   console.log('Error getting location', error);
 });

 let watch = this.geolocation.watchPosition();
 watch.subscribe((data) => {
// data can be a set of coordinates, or an error (if an error occurred).
// data.coords.latitude
// data.coords.longitude
 });
}

getGeolocation(){
    console.log( JSON.stringify(this.device_location) );
    return this.device_location;
}

Here is the result of the code:

123.45600 {}

Answer №1

Do not include this line in the constructor:

this.getGeolocation();

Instead, call it within this method like so:

setGeolocation(){
this.geolocation.getCurrentPosition().then((resp) => {
   // resp.coords.latitude
   this.device_location.latitude = resp.coords.latitude;
   this.device_location.longitude = resp.coords.longitude;

   this.getGeolocation();

   console.log( this.device_location.longitude);
   }).catch((error) => {
   console.log('Error getting location', error);
});

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

Adding local images to Excel can be easily accomplished using Office Scripts

Hello, I've been attempting to replace Excel cells that contain image filepaths with the actual images themselves. I found an example in Office Scripts that shows how to insert images with online URLs but doesn't mention anything about inserting ...

Error Encountered with Next.js 13.4.1 when using styled-components Button in React Server-Side Rendering

I am currently working on a React project using Next.js version 13.4.1 and styled-components. One problem I'm facing is with a custom Button component that I've created: import React from 'react'; import styled from 'styled-compone ...

Discovering the RequestMethod's method type by using Angular 2's MockBackend

When utilizing Angular 2 MockBackend to mock the outcome and define the response based on the method type (Post|Get|...), I encountered a specific issue. An example of this scenario is shown below: if (connection.request.url.endsWith('/api/authentica ...

What is the process of substituting types in typescript?

Imagine I have the following: type Person = { name: string hobbies: Array<string> } and then this: const people: Array<Person> = [{name: "rich", age: 28}] How can I add an age AND replace hobbies with a different type (Array< ...

Is it possible to designate a Typescript generic type as a tuple with equal length to that of another tuple?

Imagine having a function that takes in a dataset which is an array of (identically-typed) tuples: type UnknownTuple = any[] function modifyDataStructure<T extends UnknownTuple>(list: T[]) { ... } The goal is to define a second argument with the ...

Make sure accordion items stay open even when another one is clicked

I have implemented an accordion component that currently opens and closes on click. However, I am facing an issue where clicking on one item closes another item that was previously open, which is not the behavior I desire. I'm unsure of the best appro ...

The view fails to update when the object is modified

Within the acceptRequest function in child.component, the commissioner.requestAccepted property is set to false, and then the updated commissioner object is returned. Ideally, I want the button to be automatically removed from the view once the object is ...

Exciting Update: Previously, webpack version 5 did not automatically include polyfills for node.js core modules (such as React JS, TypeScript, and JWT)!

Having trouble verifying the jwt token in React with TypeScript and encountering this error, how can I fix it? ` const [decodedToken, setDecodedToken] = useState<null | JwtPayload | string>(null); const verifyToken = (token: string) => { t ...

What steps can be taken to resolve the error message "How can you repair 'Cannot read properties of undefined (reading 'front_default')'?"

I'm encountering an issue while trying to display data from an API. Although I am able to access the data, a perplexing error keeps popping up that I can't seem to troubleshoot. Here's the error message: Uncaught TypeError: Cannot read pr ...

Tips for Managing the Hardware Back Button in Ionic 3

Can someone help me enable the hardware back button in Ionic 3? I want it to redirect to specific pages and display designated content. Being new to Ionic 3, I need guidance on how to set up the hardware device buttons for redirection. ...

Having trouble getting @types/express-session to function properly. Any suggestions on how to fix it?

My web-app backend is built with TypeScript and I've integrated express-session. Despite having @types/express and @types/express-session, I continue to encounter type errors that say: Property 'session' does not exist on type 'Request ...

Angular directive problem

Within the module, I have defined a directive but the <div> is not being highlighted as expected. test.directive.ts import { Directive, ElementRef, HostListener, Input } from "@angular/core"; @Directive({ selector: '[test]' }) expor ...

Complicated nestjs application successfully resolves path issue

Currently, I am in the process of creating a boilerplate for NestJS and microservices (still a work in progress). The problem arises when trying to run the app or perform tests, resulting in this https://i.sstatic.net/uj4un.png You can find the code on t ...

Check to see if the upcoming birthday falls within the next week

I'm trying to decide whether or not to display a tag for an upcoming birthday using this boolean logic, but I'm a bit confused. const birthDayDate = new Date('1997-09-20'); const now = new Date(); const today = new Date(now.getFullYear( ...

How can I automatically select the first radio button using Angular?

I am facing an issue with displaying a dynamic list of radio buttons, where the first one always needs to be pre-selected. Initially, I used: [checked]="i === 0" Then, when I added: [(ngModel)]="item.modifType" The first radio button was no longer sele ...

How come the useEffect hook is causing re-rendering on every page instead of just the desired endpoint?

I am a novice attempting to retrieve data from a database and display it on the front-end using Axios, ReactJS, and TypeScript. My intention is for the data to be rendered specifically on localhost:3000/api/v1/getAll, but currently, it is rendering on all ...

Having trouble locating the module node_modules@ionicapp-scripts within IONIC 3

I have npm version 3.10.10 installed followed by the installation of Ionic 3.9.2 and Cordova 7.0.1. Here are the steps I have taken: ionic start newProject (chose a tabs project) https://i.sstatic.net/D9tFI.png https://i.sstatic.net/KP4OV.png https: ...

What is the best approach to prevent the occurrence of two instances of | async in this particular scenario (version 4.0

Is there a way to achieve the desired outcome in this component without using .subscribe()? I attempted to implement *ngIf="user$ | async as user" but encountered difficulties with it. What is the best approach to create a local variable using user$ | asy ...

Error in Angular 7: Image is not being rendered

Currently, I am working on a project that involves Angular JS. I have been following this example: https://jsbin.com/gumaraz/edit?html,output However, I need to transition this code to Angular 7. I have tried upgrading the code from Angular.js to Angular ...

Definition of TypeScript for caching middleware in Express

I recently came across a helpful Medium post that inspired me to create an express middleware function for caching the response. However, I'm facing some challenges while trying to implement it in typescript. Specifically, I am struggling to identify ...