Getting a "read property 'coords' of undefined"

I am trying to get the coords from the browser, then set them in the
this.longitude but I am getting the error
geolocation.js:13 Uncaught TypeError: Cannot read property 'coords' of undefined at Geolocation.setCurrentPosition (geolocation.js:13) at main.js:39
I am not sure how to fix this issue. Any guidance so that I can better learn would be greatly appreciated!

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

	getGeoLocation() {
		if (navigator.geolocation) {
			navigator.geolocation.getCurrentPosition(this.setCurrentPosition.bind(this), error());
		}
	}
	setCurrentPosition(position) {
		var crd = position.coords;
		this.setLatitude(crd.latitude);
		this.setLongitude(crd.longitude);
		console.log('Your current position is:');
		console.log(`Latitude : ${crd.latitude}`);
		console.log(`Longitude: ${crd.longitude}`);
	}

	error() {
		ui.showError();
	}
	setLatitude(latitude) {
		this.latitude = latitude;
	}
	setLongitude(longitude) {
		this.longitude = longitude;
	}

	getLatitude() {
		console.log(this.latitude);
		return this.latitude;
	}

	getLongitude() {
		return this.longitude;
	}
}

Hello!

This may be an issue with your browser. For instance, if you disable the ability to access the location, the script won’t be able to find the data.

If you’re using a mobile device, it may be restricted by your privacy settings.

What @skaparate says (needs to be HTTPS, it’s protected for security reasons). But also it’s async, so afaics (you’ve a slightly strange setup, so I may be misreading something here) there isn’t a property coords because it won’t have acquired the object by the time you try to access it.

Is there a better way to do this?

I tested the code and it works, but there is an issue: the second parameter to getCurrentPosition should be a reference to a function, not the call to it. In other words, remove the parenthesis and reference it using this.

Another problem you may be having is that the location can only be accessed using https:

@skaparate your right it was, I had to make some changes but got it to work.
Thanks for your guidance!

1 Like