简体   繁体   中英

google autocomplete places api in react

I'm using google places autocomplete api in my react code.When i kept this code in seperate file and was calling this component in another it was working properly.But when i combined place search input feild with others field in form its not working.Whats the issue when i combined with other field in form?

This code

import React from "react";
/* global google */

class SearchBar extends React.Component {
constructor(props) {
 super(props);
 this.autocompleteInput = React.createRef();
 this.autocomplete = null;
 this.handlePlaceChanged = this.handlePlaceChanged.bind(this);}

componentDidMount() {
 this.autocomplete = new google.maps.places.Autocomplete(this.autocompleteInput.current,
    {"types": ["geocode"]});

 this.autocomplete.addListener('place_changed', this.handlePlaceChanged);
}

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

render() {
 return (
    <input ref={this.autocompleteInput}  id="autocomplete" placeholder="Enter your address"
     type="text"></input>
 );
}
}

output of this: in seperate file

code after integrating other files(form input)

import React from "react";
import Geocode from "react-geocode";
import DatePicker from 'react-datepicker';
import Scrollbars from 'react-custom-scrollbars';
require('react-datepicker/dist/react-datepicker.css');

// set Google Maps Geocoding API for purposes of quota management. Its optional but 
recommended.
Geocode.setApiKey("API_KEY");
/* global google */

export default class Checkout extends React.Component {
constructor(props) {
  super(props);
  this.state = {
    locality: "",
    lat : 0,
    lng: 0,
    otherState...
  }
  this.autocompleteInput = React.createRef();
  this.autocomplete = null;
  this.handlePlaceChanged = this.handlePlaceChanged.bind(this);
}

componentDidMount() {
  this.autocomplete = new google.maps.places.Autocomplete(this.autocompleteInput.current,
    {"types": ["geocode"]});

  this.autocomplete.addListener('place_changed', this.handlePlaceChanged);

}

handlePlaceChanged(){
  const place = this.autocomplete.getPlace().formatted_address;
  //this.props.onPlaceLoaded(place);
  this.setState({locality: place})
  Geocode.fromAddress(this.state.locality).then(
  response => {
    const { lat, lng } = response.results[0].geometry.location;
    console.log(lat, lng);
    this.setState({
        lat: lat,
        lng: lng
    })
  },
  error => {
    console.error(error);
  }
);
}
render() {
let publicUrl = process.env.PUBLIC_URL+'/'
let items = JSON.parse(localStorage.getItem("items"));

return (
  
// checkout page
    <div className="contact-area pd-top-20 pd-bottom-65">
      <div className="container">
            <form className="contact-form-wrap contact-form-bg" onSubmit={e => 
             this.handleSubmit(e)}>
              <h4>Checkout</h4>
                ...other input feilds
               <div className="row">
            
               <div className="col-10 col-md-11" >
               <h4>Select/Add new address</h4>

               <div className="rld-single-input">
                <label>Enter new address</label>
                <input className="mb-2" ref={this.autocompleteInput}  id="autocomplete" 
                placeholder="Enter Locality"
                type="text"></input>
                <input placeholder="Enter flat no./Bilding name" onChange={(e) => 
                 this.handleLandmark(e)}/>
                
                  </div>
              </div>
            </div>
          </div>            
         </form>

Output after adding all code into one file

Accessing this.state immediately after calling this.setState({...}) is not a guaranteed operation because it's asynchronous read this react FAQ .

So what I will advice you do is pass a callback as second argument to this.setState(newState, callback) , and your callback should contain the whole body of Geocode.fromAddress(...) while you access your state from inside your callback.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM