Having some issues with assigning the latitude and longitude values to a variable in my code. I am able to retrieve them correctly, but when trying to use them in another method (onUpload()), I am facing some errors.
export class latlonComponent implements OnInit {
lat :number;
lon :number;
constructor() { }
ngOnInit(){
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
var error = "Geolocation is not supported by this browser.";
console.log(error);
}
}
function showPosition(position) {
//console.log(position);
this.lat = position.coords.latitude; //Getting error here as "ERROR TypeError: Cannot set property 'lat' of null"
this.lon = position.coords.longitude; //Getting error here as "ERROR TypeError: Cannot set property 'lon' of null"
console.log(this.lat);
console.log(this.lon);
};
getLocation();
}
onUpload(){
console.log(`Latitude ----> ${this.lat}`); //Getting undefined here
}
}
Need some assistance on this problem?