DEV Community

John Mark Harrell
John Mark Harrell

Posted on

Implementing Google Maps Autocomplete for Address Fields in React

When building modern web applications, integrating location-based features can greatly enhance the user experience. Google Maps API provides a robust Autocomplete service that suggests addresses as users type, reducing errors and improving input efficiency. In this blog post, we’ll walk through the process of implementing Google Maps Autocomplete for address fields in a React application, including detailed explanations and code snippets.

Prerequisites

Before we dive in, ensure you have the following:

  1. A Google Cloud Platform (GCP) project with the Places API enabled.
  2. An API key for accessing Google Maps services.
  3. Basic knowledge of React and functional components.

Step 1: Install and Configure the Google Maps API

First, include the Google Maps JavaScript API in your project. Add the following <script> tag to your public/index.html file:

<script
  src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"
  async
  defer
></script>
Enter fullscreen mode Exit fullscreen mode

Replace YOUR_API_KEY with your actual API key.

Step 2: Set Up the Address Input Component

Let’s create a React component for the address input field. We’ll use React’s useRef and useEffect hooks to initialize the Google Maps Autocomplete.

Full Component Code

import React, { useRef, useEffect } from "react";
import { useFormik } from "formik";
import * as yup from "yup";

const AddressForm = () => {
    const addressInputRef = useRef(null);

    const formik = useFormik({
        initialValues: {
            address: "",
        },
        validationSchema: yup.object({
            address: yup.string().required("Address is required."),
        }),
        onSubmit: (values) => {
            console.log("Submitted Address:", values.address);
        },
    });

    useEffect(() => {
        if (addressInputRef.current) {
            const autocomplete = new window.google.maps.places.Autocomplete(addressInputRef.current, {
                types: ["geocode"], // Restrict results to geographic locations
            });

            autocomplete.addListener("place_changed", () => {
                const place = autocomplete.getPlace();
                if (place && place.formatted_address) {
                    formik.setFieldValue("address", place.formatted_address);
                }
            });
        }
    }, []);

    return (
        <form onSubmit={formik.handleSubmit}>
            <label htmlFor="address">Address:</label>
            <input
                id="address"
                name="address"
                type="text"
                placeholder="Enter your address"
                ref={addressInputRef}
                value={formik.values.address}
                onChange={formik.handleChange}
                onBlur={formik.handleBlur}
            />
            {formik.touched.address && formik.errors.address && (
                <div style={{ color: "red" }}>{formik.errors.address}</div>
            )}

            <button type="submit">Submit</button>
        </form>
    );
};

export default AddressForm;
Enter fullscreen mode Exit fullscreen mode

Step 3: How It Works

1. useRef for Input Field Reference

We use the useRef hook to create a persistent reference (addressInputRef) to the input field. This allows the Google Maps API to attach its Autocomplete functionality to the correct DOM element.

2. Initializing Autocomplete in useEffect

The useEffect hook initializes the Autocomplete instance only once (thanks to the empty dependency array []).

  • new window.google.maps.places.Autocomplete(addressInputRef.current, options):
    • Creates an Autocomplete instance tied to the referenced input field.
    • Accepts an options object, such as restricting results to geographic locations (types: ["geocode"]).

3. Handling the place_changed Event

The addListener method listens for the place_changed event, which fires when a user selects a suggestion from the dropdown.

  • autocomplete.getPlace() retrieves the selected place.
  • place.formatted_address provides the formatted address string. This is then set as the value of the address field using Formik’s setFieldValue method.

4. Formik Integration

Formik simplifies form handling in React by managing state, validation, and submission. In this example:

  • The address field is initialized in Formik’s state.
  • The value of the field is dynamically updated when the user selects an address.

Step 4: Testing the Component

Run your React application and navigate to the form. Begin typing an address in the input field. The Google Maps Autocomplete dropdown should appear with suggestions. When you select an address, it will populate the input field.

Submit the form to see the selected address logged in the console.

Step 5: Enhancements and Next Steps

Here are some ideas to extend this implementation:

  1. Store Additional Location Data
    • The place object from getPlace() contains detailed information, such as latitude, longitude, and place ID. You can store this data in your database for advanced features like calculating distances or displaying maps.

Example:

   const place = autocomplete.getPlace();
   const latitude = place.geometry?.location.lat();
   const longitude = place.geometry?.location.lng();
   console.log({ formatted_address: place.formatted_address, latitude, longitude });
Enter fullscreen mode Exit fullscreen mode
  1. Restrict Search Results
    • Use the componentRestrictions option to limit results to a specific country or region:
   new window.google.maps.places.Autocomplete(addressInputRef.current, {
       componentRestrictions: { country: "us" },
   });
Enter fullscreen mode Exit fullscreen mode
  1. Styling and Accessibility
    • Customize the input field and dropdown to match your application’s design.
    • Ensure the form is accessible by adding proper ARIA attributes.

Common Issues and Troubleshooting

  1. ApiNotActivatedMapError

    • Ensure the Places API is enabled in your Google Cloud project.
  2. Missing or Invalid API Key

    • Double-check that your API key is correctly added and has the required permissions.
  3. Autocomplete Not Working

    • Ensure the libraries=places query parameter is included in the script URL.

Conclusion

Integrating Google Maps Autocomplete into a React application is a powerful way to improve user experience when dealing with location input. With a few lines of code, you can streamline the address entry process and enhance your app’s functionality. By extending this basic implementation, you can build features like location-based searches, proximity calculations, and more.

Top comments (0)