0

I am building a google map component and I'm trying to set the lng and lat of the user into the state.

position.coords.latitude and position.coords.longitude logs the right coordinates but when I try to set them into state I get the error in the title.

constructor(props) {
        super(props);

        this.state = {
            userLatitude: 0,
            userLongitude: 0
        }
    }

componentDidMount() {
        navigator.geolocation.getCurrentPosition(function(position) {
            console.log(position.coords.latitude + " " + position.coords.longitude);

            this.setState({userLatitude: position.coords.latitude});
            this.setState({userLongitude: position.coords.longitude});
        });
    }
Bojan Ivanac
  • 1,170
  • 8
  • 17

1 Answers1

0

You need to bind the getCurrentPosition since this inside it doesn't refer to the React component's context and hence setState is unavailable

Also instead of using two setState statements, you should do it in one statement else your component will be re-rendered twice

navigator.geolocation.getCurrentPosition((position) => {
        console.log(position.coords.latitude + " " + position.coords.longitude);

        this.setState({userLatitude: position.coords.latitude, userLongitude: position.coords.longitude});
    });
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400