Clue Mediator

Google Place Autocomplete in ReactJS

📅February 13, 2020

Today we will show you how to implement google place autocomplete in ReactJS. We will simply use the google map API to create the autocomplete for google places using ReactJS.

Google Place Autocomplete API in React JS, React component for google autocomplete, Implementing Google Places Autocomplete with ES6, example or tutorial of the google places autocomplete, react js with google maps autocomplete search engine.

Checkout more articles on ReactJS

Way to implement google place autocomplete

  1. Google map script
  2. Implement google map
  3. Design the form
  4. Initialize the google place autocomplete
  5. Output

1. Google map script

Here we will use the below API to implement the place autocomplete in ReactJS where we use the place libraries.

https://maps.googleapis.com/maps/api/js?key=<YOUR_GOOGLE_MAP_API_KEY>&libraries=places

2. Implement google map

Let’s start with implementing Google Maps in ReactJS. If you don’t know how to do this then refer to the link below for your reference.

Implement Google Maps in ReactJS

Don't forget to update the above API in google map example.

3. Design the form

Now we will design the simple form. In which we use the input field for place autocomplete and labels for display purpose.

import React, { useRef, useState } from "react";

const GPlace = () => {
  const placeInputRef = useRef(null);
  const [place, setPlace] = useState(null);

  return (
    <>
      <input type="text" ref={placeInputRef} />
      {place && <div style={{ marginTop: 20, lineHeight: '25px' }}>
        <div style={{ marginBottom: 10 }}><b>Selected Place</b></div>
        <div><b>Address:</b> {place.address}</div>
        <div><b>Lat:</b> {place.lat}</div>
        <div><b>Lng:</b> {place.lng}</div>
      </div>}
    </>
  );
};

export default GPlace;

4. Initialize the google place autocomplete

It's time to initialize the google place autocomplete for that we will assign the input reference in `google.maps.places.Autocomplete`.

To capture `place_changed` events, we will use `google.maps.event.addListener`.

GPlace.js

import React, { useEffect, useRef, useState } from "react";

const GPlace = () => {
  const placeInputRef = useRef(null);
  const [place, setPlace] = useState(null);

  useEffect(() => {
    initPlaceAPI();
  }, []);

  // initialize the google place autocomplete
  const initPlaceAPI = () => {
    let autocomplete = new window.google.maps.places.Autocomplete(placeInputRef.current);
    new window.google.maps.event.addListener(autocomplete, "place_changed", function () {
      let place = autocomplete.getPlace();
      setPlace({
        address: place.formatted_address,
        lat: place.geometry.location.lat(),
        lng: place.geometry.location.lng()
      });
    });
  };

  return (
    <>
      <input type="text" ref={placeInputRef} />
      {place && <div style={{ marginTop: 20, lineHeight: '25px' }}>
        <div style={{ marginBottom: 10 }}><b>Selected Place</b></div>
        <div><b>Address:</b> {place.address}</div>
        <div><b>Lat:</b> {place.lat}</div>
        <div><b>Lng:</b> {place.lng}</div>
      </div>}
    </>
  );
};

export default GPlace;

Please refer to `App.js` code for your reference.

App.js

import React, { useState, useEffect } from 'react';
import GPlace from './GPlace';

// API key of the google map
const GOOGLE_MAP_API_KEY = '<YOUR_GOOGLE_MAP_API_KEY>';

// load google map script
const loadGoogleMapScript = (callback) => {
  if (typeof window.google === 'object' && typeof window.google.maps === 'object') {
    callback();
  } else {
    const googleMapScript = document.createElement("script");
    googleMapScript.src = `https://maps.googleapis.com/maps/api/js?key=${GOOGLE_MAP_API_KEY}&libraries=places`;
    window.document.body.appendChild(googleMapScript);
    googleMapScript.addEventListener("load", callback);
  }
}

const App = () => {
  const [loadMap, setLoadMap] = useState(false);

  useEffect(() => {
    loadGoogleMapScript(() => {
      setLoadMap(true)
    });
  }, []);

  return (
    <div className="App">
      <a href="https://www.cluemediator.com">Clue Mediator</a><br /><br />
      {!loadMap ? <div>Loading...</div> : <GPlace />}
    </div>
  );
}

export default App;

5. Output

Output - Google Place Autocomplete in ReactJS - Clue Mediator

Output - Google Place Autocomplete in ReactJS - Clue Mediator

That's it for today.
Thank you for reading. Happy Coding!

Demo & Source Code

Github Repository StackBlitz Project