Showing posts with label google autocomplete address. Show all posts
Showing posts with label google autocomplete address. Show all posts

Thursday, January 2, 2020

Using Google Place Autocomplete API in React

I want to have an auto completing location search bar in my react component
Reference Google Maps API JS library via /public/index.html file:
Get google API Key from here -> https://developers.google.com/places/web-service/get-api-key
https://cloud.google.com/console/google/maps-apis/overview
You need to enable Maps JavaScript API & Places Api from below links ->
https://console.developers.google.com/google/maps-apis/apis/maps-backend.googleapis.com

https://console.developers.google.com/google/maps-apis/apis/places-backend.googleapis.com

import React from "react";

class MyComponent 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>
    );
  }
}

export default MyComponent