0
votes

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

1 Answers

4
votes
   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,
      });
    });