0

why onMapClicked work but onGpsClicked not work this.setState show Error TypeError: Cannot read property 'setState' of undefined react....................................................................................................................................................................................

enter image description here

import React from "react";
import { Map, Marker, GoogleApiWrapper } from "google-maps-react";
import GpsFixedRoundedIcon from "@material-ui/icons/GpsFixedRounded";
import Button from "@material-ui/core/Button";
export class SimpleMap extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      lat: this.props.lat,
      lng: this.props.lng,
      markers: [
        {
          position: { lat: this.props.lat, lng: this.props.lng },
        },
      ],
    };
    this.onMapClicked = this.onMapClicked.bind(this);
    this.onGpsClicked = this.onGpsClicked.bind(this);
  }

  onMapClicked(t, map, coord) {
    if (this.props.activeStep === 1 || this.props.disable === false) {
      const { latLng } = coord;
      const lat = latLng.lat();
      const lng = latLng.lng();

      this.setState((previousState) => {
        return {
          markers: [
            {
              position: { lat, lng },
            },
          ],
        };
      });

      this.props.onChange(lat, lng);
    }
  }
  onGpsClicked() {
    navigator.geolocation.getCurrentPosition(function (position) {
      this.setState({
        lat: position.coords.latitude,
        lng: position.coords.longitude,
      });
    });
  }

1 Answer 1

4
   navigator.geolocation.getCurrentPosition(function (position) {
      this.setState({
        lat: position.coords.latitude,
        lng: position.coords.longitude,
      });
    });

React doesn't understand this in here because its referring to the function scope, not React scope. You can change the syntax to fat arrow function, which using lexical scoping/this

navigator.geolocation.getCurrentPosition( (position) => {
      this.setState({
        lat: position.coords.latitude,
        lng: position.coords.longitude,
      });
    });
Sign up to request clarification or add additional context in comments.

1 Comment

For more details: fat arrow function automatically bind your method to the context of your class. Before this, you had to write this.myMethod = this.myMethod.bind(this) which is not necessary anymore :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.