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

3 comments:

  1. I don't even know how I ended up here, but I thought this post was good. I don't know who you are but definitely you're going to a famous blogger if you are not already ;) Cheers!

    ReplyDelete
  2. I think the admin of this site is truly working hard in support of his web site, since here every information is quality based data.

    ReplyDelete