0

I am using a Google Autocomplete search to recenter my map on selection of a place within the search. This is working perfectly, the only issue is that if a user hits enter without selecting a place, it will not work as there are no lat/lng coordinates passed. I am trying to rectify this by creating a geocoder and geocoding the input value if a place is not selected. This is creating an error: Cannot read property 'updateParentState' of undefined I'm assuming because this does not refer to the component but to the geocoder, but I'm not sure how to rectify this.

render() {
  return (
    <React.Fragment>
      <SearchBar
        updateParentState={(lat, lng) => {
          this.setState({ lat, lng });
        }}
      />
      <div className="container">
        <MapContainer
          google={this.props.google}
          lat={this.state.lat}
          lng={this.state.lng}
        />
      </div>
    </React.Fragment>
  );
}

And the autocomplete functionality:

handlePlaceChanged() {
  const place = this.autocomplete.getPlace();

  if (place.geometry) {
    this.props.updateParentState(
      place.geometry.location.lat(),
      place.geometry.location.lng()
    );
  } else {
    let geocoder = new google.maps.Geocoder();
    geocoder.geocode({'address': place.name}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          console.log(results[0]);
          this.props.updateParentState(
            results[0].geometry.location.lat(),
            results[0].geometry.location.lng()
          );
        }
      });
  }
}

CodeSandbox

user13286
  • 3,027
  • 9
  • 45
  • 100

1 Answers1

1

You are right, var self = this; would solve the issue.you can find excellent explanation here

 handlePlaceChanged() {
        var self = this;
        const place = this.autocomplete.getPlace();
        if (place.geometry) {
          console.log(place.geometry.location.lat(), place.geometry.location.lng());
          this.props.updateParentState(
            place.geometry.location.lat(),
            place.geometry.location.lng()
          );
        } else {
          let geocoder = new google.maps.Geocoder();
          geocoder.geocode({ address: place.name }, function(results, status) {
            if (status === google.maps.GeocoderStatus.OK) {
              self.props.updateParentState(
                results[0].geometry.location.lat(),
                results[0].geometry.location.lng()
              );
            }
          });
        }
      }
Alex
  • 3,941
  • 1
  • 17
  • 24