How-to: Google Places Using Autocomplete in React

Let’s see how we can use the Google Places API within our simple React app.

And to start with, we would be using the React Places Autocomplete package to help us build the input that would show all the suggestions and grabs the coordinates as we type something.

Getting Started:

  1. npx create-react-app my-app –template typescript
  2. Get your Google API key / Make sure to put restrictions in your API
  3. In your index.html. Put the following script and along with your API key NOTE: Insert your generated API key ONLY on the part.
  4. Npm install react-places-autocomplete
  5. npm install @types/react-places-autocomplete – for typescript

After creating your create react app project, let’s do some imports on our App component. Again, let’s just it simple by putting everything on our App component.

import React from "react";
import PlacesAutocomplete, {geocodeByAddress,getLatLng,
} from "react-places-autocomplete";
import "./App.css";

export default function App(){
	return <div> This my Google Places </div> 
}

Inside the div of is where we will put the PlacesAutocomplete.

import React from "react";
import PlacesAutocomplete, {geocodeByAddress,getLatLng,
} from "react-places-autocomplete";
import "./App.css";

export default function App(){


	return (
	<div className="App" style={{ margin: "20rem" }}>
		<PlacesAutocomplete 
		value={} //current value of user's input
		onChange={} //a function being called everytime input value changes to update the state
		onSelect={}>  //when the user selects one of the suggestions that we display to them
	
		</PlacesAutoComplete/> 

	</div> 

);
}

Next we will fill in those props with some values and pass it down to the return functions.

const [address, setAddress] = useState("");
const handleSelect = async(value)=> {
		//TODO HERE 
}


	return (
	<div className="App" style={{ margin: "20rem" }}>
		<PlacesAutocomplete 
		value={address} 
		onChange={setAddress} 
		onSelect={handleSelect}>

	 </PlacesAutoComplete>  

 </div> 

Before we forget, the PlacesAutoComplete components wants to render some prop function. And we will get those from the React Places Autocomplete.

  • getInputProps
  • suggestions
  • getSuggestionItemProps
  • loading

The getInputProps is a function that we can call to create Input.

Next, pass the props returned from the getInputProps

Additionally, we can attach another props to input, and in this case, a placeholder.

...
return (
    <div className="App" style={{ margin: "20rem" }}>
      <PlacesAutocomplete
        value={address} 
        onChange={setAddress} 
        onSelect={handleSelect} 
      >
        {({ getInputProps, suggestions, getSuggestionItemProps, loading }) => ( 

				<div> 
						<input {...getInputProps([placeholder: "Type Address"]) } /> 

				</div>

				{/*  to check if loading or not */}   
				<div> {loading? <div>...loading</div>} : null </div>  


			)}

...

We need to show the suggestions, which is an array of objects that we are going to map . And then we shall render each suggestions below.

{suggestions.map((suggestion) => {
                const style = {
                  backgroundColor: suggestion.active ? "#41b6e6" : "#fff",
                };


return (
                  <div {...getSuggestionItemProps(suggestion, { style })}>
                    {suggestion.description}
                  </div>
                );

Next, let’s go back to the handleSelect that we’ve neglected so far. And the first thing we need to do is to set some coordinates.

const [coordinates, setCoordinates] = React.useState({
    lat: null,
    lng: null,
  });

And then we would just render them in a div.

					<div className="App-header" style={{ color: "orange" }}>
            <p>Latitude: {coordinates.lat}</p>
            <p>Longitude: {coordinates.lng}</p>

            <input
              style={{ margin: "2rem", padding: "20px" }}
              {...getInputProps({ placeholder: "Type address" })}
            />

In handleSelect: is where we will be using the geoCodeByAddress and getLatLng that we took from the React Autocomplete. Before we do that, make sure that you have enabled the Google APIs that we need for this demo app.

📌 Enabled Google APIs for this demo:

  • Geocoding API
  • Places API

The first thing we need to do is to get the results that are coming from the value that is being passed by the user in the handleSelect.

const handleSelect = async (value: string) => {
    const results = await geocodeByAddress(value);
    const latLng = await getLatLng(results[0]);
    setAddress(value);
    setCoordinates(latLng);

Let’s play around with the app to check if its working.