Code Monkey home page Code Monkey logo

google-place-autocomplete's Introduction

Google Place Autocomplete

The best practice with Google Place Autocomplete API on React

Using Google Place Autocomplete without third-party library

Autocomplete is a feature of the Places library in the Maps JavaScript API. When a user starts typing an address, autocomplete fills in the rest.

Setting up the Project

Install the repository:

git clone https://github.com/Gapur/google-place-autocomplete.git

After that, move it into the google-place-autocomplete directory and run it from the terminal:

cd google-place-autocomplete
npm start

Before we get started, you need the API-Key for the Google Places API. You can get that key here. I store Google API Key in the .env file — you should too.

Magic Code

Let’s implement the main SearchLocationInput component to work with the Google Place Autocomplete API. First, we have to create a function to load the script for working with Google API. Let’s create SearchLocationInput.js with loadScript function:

// dynamically load JavaScript files in our html with callback when finished
const loadScript = (url, callback) => {
  let script = document.createElement("script"); // create script tag
  script.type = "text/javascript";

  // when script state is ready and loaded or complete we will call callback
  if (script.readyState) {
    script.onreadystatechange = function() {
      if (script.readyState === "loaded" || script.readyState === "complete") {
        script.onreadystatechange = null;
        callback();
      }
    };
  } else {
    script.onload = () => callback();
  }

  script.src = url; // load by url
  document.getElementsByTagName("head")[0].appendChild(script); // append to head
};

I used this script for dynamic JavaScript for fast page speed load on our public pages. It dynamically loads JavaScript files with a callback when finished. Next, we have to assign the Google Place Map to the autoComplete variable when the component is rendered:

// handle when the script is loaded we will assign autoCompleteRef with google maps place autocomplete
function handleScriptLoad(updateQuery, autoCompleteRef) {
  // assign autoComplete with Google maps place one time
  autoComplete = new window.google.maps.places.Autocomplete(
    autoCompleteRef.current,
    { types: ["(cities)"], componentRestrictions: { country: "us" } }
  );
  autoComplete.setFields(["address_components", "formatted_address"]); // specify what properties we will get from API
  // add a listener to handle when the place is selected
  autoComplete.addListener("place_changed", () =>
    handlePlaceSelect(updateQuery)
  );
}

Then we attach to the autocomplete listener, which listens for whenever a user selects one of the autocomplete suggestions. Let’s createthe handlePlaceSelect method to handle selection:

async function handlePlaceSelect(updateQuery) {
  const addressObject = autoComplete.getPlace(); // get place from google api
  const query = addressObject.formatted_address;
  updateQuery(query);
  console.log(addressObject);
}

This method is called when the event is triggered and gets place data from API. Then we can do any operation with data.

Google API result

Article on Medium

How to Use Google Place Autocomplete With React Without a Third-Party Library

How to contribute?

  1. Fork this repo
  2. Clone your fork
  3. Code 🤓
  4. Test your changes
  5. Submit a PR!

google-place-autocomplete's People

Contributors

dependabot[bot] avatar gapur avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

google-place-autocomplete's Issues

reused component

Hi,
First, I would like to thank you because your work is exactly what I was looking for.
So now I want to use multiple SearchLocationInput component in my project, but it's not possible.

In the chrome console we have :
image

And only one of the inputs are working now...

here is an example:

image

I tied to put the useEffect loadScript in the parent component but I broke everything...

Do you have any idea with that ?
Thank you.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.