user2589339
user2589339

Reputation: 91

React and Google's autocomplete Service and fetching zipcodes

I'm having a few issues with google's autocomplete location service. There are two different approaches, both of which lead me to issues:

Option 1 use 'react-places-autocomplete' and apply extensions where necessary:

  handleInputChange(event) {
    this.props.inputProps.onChange(event.target.value)
    if (!event.target.value) {
      this.clearAutocomplete()
      return
    }
    this.autocompleteService.getPlacePredictions({ ...this.props.options, input: event.target.value }, this.autocompleteCallback)
  }

The above calls my autocompleteCallback method with predictions which is great. I have street address, city, state, country, but NOT zip codes. Perhaps I should then do a 2nd call after choosing one of the predictions to then fetch the zip code information? I haven't scene anything from google that will then fetch a zip code from an adddress though

Option 2A:

    method1(a1, a2, a3) {
        //do state things because method1 is bound in the constructor
    };
... later ....
    var input = document.getElementById('my-input-id');
    var options = {
        types: ['address'],
        componentRestrictions: {
            country: 'us'
        }
    };
    var autocomplete = new google.maps.places.Autocomplete(input, options);
    google.maps.event.addListener(autocomplete, 'place_changed', this.method1);

Option 2B

    google.maps.event.addListener(autocomplete, 'place_changed', function () {
        place = autocomplete.getPlace();
        //call states
    })

My issues with Option 2 the first part is that although we hit method 1 and I have access to props/states, the variable autocommpleten is out of scope so I can't get the addresses.

My issue with Option 2,the second part, is that I don't see a way to have access to the state inside of an addlistener method.

I feel like my option 1 is the most reasonable solution, but for some reason, google decided not to include zip codes. Additionally, using a listener makes me uneasy within react.

Upvotes: 0

Views: 1419

Answers (1)

user2589339
user2589339

Reputation: 91

I found a work around which is more elegant and preserves the ability to use the parent class 'react-places-autocomplete' in my handleselect, I add the below code:

    googleMapsClient.geocode({
        address: address
    }, this.method1);

where googlemapsclient = require('@google/maps').createClient({ key: '...' });

It calls another asynch method which isn't ideal, but it preserves my other information.

Upvotes: 1

Related Questions