I´m currently using google Maps in React without a library. I keep getting that error (cannot read property setState of null) which I know has to do with the use of "this" inside the function. I´m clueless as to how to solve it in this particular case.

Method

getGPS = () =>{
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      let start = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      };
      this.setState({start: start})
    });
  } else {
    let start= {lat:"-34.603474", lng:"-58.381592"};
    this.setState({start: start})
  };
  this.calculateAndDisplayRoute()
}

Map component

<Map
id="myNewMap"
float="right"
width= "50%"
options={{
center: {lat: this.state.currentMarker[0].getPosition().lat(), lng: this.state.currentMarker[0].getPosition().lng()},
zoom: 18,
disableDefaultUI: true,
}}
onMapLoad={map => {
this.newMap = map;
{this.getGPS()}
} 
}
/>

1 Answers

0
user2340824 On Best Solutions
function(position) {
      let start = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      };
      this.setState({start: start})
    }

You are correct, it's the scope of this. JavaScript thinks you are referencing the this within the function. If you update your function to an arrow function, the this value of the enclosing lexical scope is used, which will be your component.

navigator.geolocation.getCurrentPosition(position => {
      let start = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      };
      this.setState({start: start})
    };