Attempt to modify the parameters within a function in the app.component.ts file

I have been trying to retrieve the Latitude and Longitude data using geolocation.getCurrentLocation, but I am facing issues with saving them. The function does not return a number and when I try to save them using lat and lng variables, I encounter this error: ERROR TypeError: Cannot set property 'lat' of null

If anyone can provide assistance on this matter, it would be greatly appreciated.

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
    public constructor( private geo: GeoDataService, private tags: TagService) { }
    title = 'Select a tag:';
    latt =0;
    lngg = 0;
    zoomlv = 18;
    lat = 1;
    lng = 1;

    iconUrl = 'http://maps.google.com/mapfiles/dir_0.png';
    a : Array<any>;
    polylines: Array<any>;
    markers = new Array();
    mapClicked($event: MouseEvent) {
        console.log('Clicked the map at longitude: ' + $event.coords.lng + ', latitude: ' + $event.coords.lat); 
    }

    ngOnInit(): void {
        var options = {
            enableHighAccuracy: true,
            timeout: 5000,
            maximumAge: 0
          };

          function success(pos) {
            var crd = pos.coords;

            console.log('Your current position is:');
            console.log(`Latitude : ${crd.latitude}`);
            console.log(`Longitude: ${crd.longitude}`);
            console.log(`More or less ${crd.accuracy} meters.`);
            this.lat = crd.latitude;
            this.lng = crd.longitude;
          }

          function error(err) {
            console.warn(`ERROR(${err.code}): ${err.message}`);
          }

          navigator.geolocation.getCurrentPosition(success, error, options);
    }

}

Answer №1

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
    public constructor( private geo: GeoDataService, private tags: TagService) { }
    title = 'Choose a tag:';
    latt =0;
    lngg = 0;
    zoomlv = 18;
    lat = 1;
    lng = 1;

    iconUrl = 'http://maps.google.com/mapfiles/dir_0.png';
    a : Array<any>;
    polylines: Array<any>;
    markers = new Array();
    mapClicked($event: MouseEvent) {
        console.log('Map clicked at longitude: ' + $event.coords.lng + ', latitude: ' + $event.coords.lat); 
    }

    ngOnInit(): void {
        }

            var options = {
            enableHighAccuracy: true,
            timeout: 5000,
            maximumAge: 0
          };

          let success = (pos) => { <--------- using arrow function syntax instead
            var crd = pos.coords;

            console.log('Your current position is:');
            console.log(`Latitude : ${crd.latitude}`);
            console.log(`Longitude: ${crd.longitude}`);
            console.log(`Approximately ${crd.accuracy} meters.`);
            this.lat = crd.latitude;
            this.lng = crd.longitude;
          }

          let error = (err) => { <-------- arrow function used here as well 
            console.warn(`ERROR(${err.code}): ${err.message}`);
          }

          navigator.geolocation.getCurrentPosition(success, error, options);



    }

}

Replacing function expressions with arrow functions

In the case of function expression this refers to the object created inside the createObject. In the scenario of an arrow function, this refers to the this of createObject itself.

This feature makes arrow functions handy when you need to access the this of the present context

Answer №2

const self = this;
function handleSuccess(position) {
  const coordinates = position.coords;
  console.log('Your current location:');
  console.log(`Latitude : ${coordinates.latitude}`);
  console.log(`Longitude: ${coordinates.longitude}`);
  console.log(`Approximately ${coordinates.accuracy} meters.`);
  self.latitude = coordinates.latitude;
  self.longitude = coordinates.longitude;
}

Your error was using this, which refers to the current function scope. The success function does not have properties like latitude or longitude, hence the issue.

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

"Combining the power of AngularJS2 beta with Spring Boot: the ultimate

I am currently using Atom 1.4.0 with the atom-typescript package to develop AngularJS2 modules in TypeScript. On the backend, I have a spring-boot application for handling the REST APIs. After making changes to the .ts files in Atom, it seems to compile t ...

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 ...

Checking the validity of an HTML tag with the contenteditable attribute set to true

Take for instance the input tag, which includes a field known as type. When type is set to "numeric", only numbers can be entered. Now, if I set a td element as contenteditable, is there a way to restrict the user from inputting anything other than number ...

Using Typescript and Webpack with Fabric.js: Error - Canvas is not a constructor

I'm currently experimenting with integrating fabric.js into a Laravel 5.4 application using Typescript and Webpack, alongside other modules that are functioning properly in the browser. Although @types/fabric is installed and Typescript is behaving co ...

Error: Property 'mytest' is undefined and cannot be read

While working with Swagger API, I encountered an error message when calling the endpoint stating "Cannot read property 'mytest' of undefined" class UserData { private mytest(req:any, res:any, next:any){ return res.json('test32423423&a ...

Angular 6 - Struggling to translate "Invalid Date" to a valid date using the "DatePipe" filter

Greetings, I am encountering an issue related to converting dates into a specific format that I desire. Currently, the REST API is sending dates in Milliseconds format, which I need to convert to a date format like yyyy-MM-dd for my date-picker component ...

Obtain access to a React DOM Element using an external script

I am facing a challenge in accessing a React DOM element 'id' from an external script file. It seems like the script is properly imported because console.log('test') from the file is working; however, console.log(myDiv) returns null. I ...

What could be the reason for the authentication issues in ionic/angular?

An authentication application has been created to receive user information and tokens (jwt) from the server. The data is stored locally and used for further computations within the app. For route guarding, if the token is available, it should proceed to th ...

What are the steps to connecting incoming data to an Angular view utilizing a reactive form?

Hello, I am currently fetching data from an API and have successfully displayed the teacher values. However, I am unsure of how to utilize the incoming array values for "COURSES" in my Angular view. This is the response from the REST API: { "courses ...

Invoke a function within the embedded element

I currently have two components, known as app-student-list and app-student-detail. My goal is to incorporate the student-detail within the student-list in the following manner: Within app-student-detail.html: <p>Student Detail Component content go ...

What is the process for implementing a pipe to establish data binding?

I've been trying to use a pipe for data binding in Angular, but it's not working as expected. Previously, I had this: [message]="enum.text" and now I want to replace enum.text with a custom pipe. Here's what I tried: [text]=" '' ...

How to update Angular Material table dynamically after CRUD operation without needing to reload the page

Hello, I am currently using Angular (v.9) along with ASP .NET Core Web API and EF Core (v 3.1) to perform CRUD operations. I have a region component form which is used as a dialog, you can view it https://i.stack.imgur.com/6w7hO.png The HTML code for the ...

Using absolute imports to resolve modules in TypeScript and Next.js

When I import functions from files using absolute imports, I keep encountering errors that I have been trying to resolve. The errors manifest in a certain way, as shown here: https://i.sstatic.net/J7Ai1.png Despite the errors, the functions are successful ...

The error message "registerNgModuleType: Uncaught TypeError: Cannot read property 'id' of undefined" indicates that there is an issue

I am facing an issue with my Angular app repository. After cloning the repository, installing the node_module, and running ng serve, I encounter an error. Despite searching for numerous solutions, none seem to be effective. The app is built on Angular 8.1, ...

Using Angular, Typescript, and ngxs to manage state observables, one may wonder what exactly a variable ending with an exclamation mark (!) signifies. An example of this can be seen in the following code snippet:

Within my TS file, a declaration is present: import { Select } from '@ngxs/store'; @Injectable() export class someService { @Select(someSELECTOR) varName$!: Observable<someType[]>; elements$ = this.varName$.pipe( map(elements => e ...

Could JOI be used to validate unidentified keys within nested data structures?

I've developed a middleware that uses Joi to validate incoming requests. export default (schema: any) => async (req: Request, res: Response, next: NextFunction) => { try { const validation = schema.validate(req, { abortEarly: false }) ...

Is it possible to set specific points within a Points object in THREE.js to be transparent or invisible?

I am working with a Three.js Points object that holds information for displaying multiple points in 3D space. I am looking for a way to dynamically hide certain points, but I am uncertain of the process. The PointsMaterial used has xyz data stored in poin ...

When using MERN Stack (with Typescript) on DigitalOcean, encountering an issue where HTML files are displayed instead of JS and

Upon checking the console, I encountered this https://i.sstatic.net/PWoT5.jpg The app has been developed using Ubuntu and Nginx so far with no firewall configuration yet in place. This is my first time deploying a MERN stack and utilizing DigitalOcean. ...

React: Issue with Intersection Observer not triggering state updates

Looking to implement an endless scroll feature using intersection observer, where new content appears as the user reaches the bottom. Here's a simplified version of the code: function App() { const ids = [1, 2, 3, 4, 5, 6] const [ProductIds, setPr ...

Angular parent component struggles to manage control over multiple child components

As a newcomer to Angular, I have a question regarding my Page1 setup. Page1 has two menu options at the top: when the first option is clicked, Page1.html is displayed, and clicking the second menu displays another component (Page2) in the context area. I w ...