Issue with Retrieving User's Location
In my Angular project, I am trying to access the user's current location and store the longitude and latitude values in two properties named lng
and lat
. However, I am facing a persistent issue where I keep receiving the error message
ERROR TypeError: Cannot set property 'lat' of null
despite trying various solutions.
Snippet of TypeScript Code Related to the Issue
lat : any;
lng : any;
constructor() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(this.setValues);
}
}
setValues(values) {
this.lat = values?.coords?.latitude
this.lng = values?.coords?.longitude;
}
The error seems to be originating from the first line of the setValues
method.
Sample JSON Object Returned by getCurrentPosition Function
{
coords:
{
latitude: 27.380583,
longitude: 33.631839
}
}
Solutions Attempted So Far
- I have successfully received and printed the JSON object along with its subobjects. I even tried binding it to a local variable within the
setValues
function, but still encountered the same error. - Tried changing
lat: any
tolat: number
or addingpublic
before it. - Removed the null operators from the
setValues
method. - Attempted executing the code within the
ngOnInit
lifecycle hook.
All these attempts resulted in the same error persisting.