Skip to main content

Overview

The InputLocation component provides location autocomplete functionality powered by the Google Maps Places API. It requires both the API script and the @react-google-maps/api package.
Google Maps API key is required for InputLocation to function. The component will remain disabled with “Cargando…” (Loading) placeholder until the API is loaded.

Prerequisites

1. Install Required Package

npm install @react-google-maps/api

2. Get Google Maps API Key

1

Create Google Cloud Project

Navigate to the Google Cloud Console and create a new project or select an existing one.
2

Enable Places API

Go to APIs & Services > Library and enable:
  • Places API
  • Maps JavaScript API (required for Places API to work)
3

Create API Key

Go to APIs & Services > Credentials and click Create Credentials > API Key.
Restrict your API key by HTTP referrer (for web) or application (for mobile) to prevent unauthorized use and unexpected charges.
4

Configure API Key Restrictions

Edit the API key and add restrictions:
  • Application restrictions: HTTP referrers (recommended for web apps)
  • API restrictions: Restrict to Places API and Maps JavaScript API

Setup in Your Application

Add the Google Maps API script to your application’s HTML <head> section:
index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Your App</title>
    
    <!-- Google Maps Places API -->
    <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&language=es"></script>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>
Replace YOUR_API_KEY with your actual Google Maps API key.
Script Parameters:
  • key: Your Google Maps API key
  • libraries=places: Loads the Places library
  • language=es: Sets default language to Spanish (component is Spanish-localized)

Option 2: Using useJsApiLoader Hook

For dynamic loading with React:
App.tsx
import { useJsApiLoader } from '@react-google-maps/api';
import { InputLocation } from '@adoptaunabuelo/react-components';

const libraries: ("places")[] = ['places'];

function App() {
  const { isLoaded } = useJsApiLoader({
    googleMapsApiKey: process.env.REACT_APP_GOOGLE_MAPS_API_KEY as string,
    libraries,
    language: 'es'
  });

  return (
    <InputLocation
      isLoaded={isLoaded}
      placeholder="Introduce tu dirección"
      onLocationChange={(location) => {
        console.log('Selected location:', location);
      }}
    />
  );
}

Environment Variables

Store your API key securely using environment variables:
NEXT_PUBLIC_GOOGLE_MAPS_API_KEY=your_api_key_here
Never commit your .env files to version control. Add them to .gitignore.

Usage Example

LocationForm.tsx
import { useState } from 'react';
import { useJsApiLoader } from '@react-google-maps/api';
import { InputLocation, LocationProps } from '@adoptaunabuelo/react-components';

const libraries: ("places")[] = ['places'];

export default function LocationForm() {
  const { isLoaded } = useJsApiLoader({
    googleMapsApiKey: process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY as string,
    libraries,
  });

  const [location, setLocation] = useState<LocationProps | null>(null);

  return (
    <div>
      <InputLocation
        isLoaded={isLoaded}
        placeholder="Buscar dirección"
        design="primary"
        label="Dirección"
        searchTypes={['address']}
        searchFields={['geometry', 'address_components']}
        onLocationChange={(result) => {
          setLocation(result);
          console.log('Full address:', result.address);
          console.log('Coordinates:', result.location);
          console.log('Postal code:', result.zipCode);
        }}
      />

      {location && (
        <div>
          <p>Address: {location.address}</p>
          <p>City: {location.city}</p>
          <p>Postal Code: {location.zipCode}</p>
          <p>Coordinates: {location.location?.lat}, {location.location?.lng}</p>
        </div>
      )}
    </div>
  );
}

Component Props

Required Props

isLoaded
boolean
required
Must be true when Google Maps API is fully loaded. The component is disabled until this is true.

Optional Props

searchTypes
string[]
default:"[\"address\"]"
Google Places API search types. Options include "address", "geocode", "establishment", "(regions)", "(cities)".
searchFields
string[]
default:"[\"geometry\", \"address_components\"]"
Place details fields to fetch. Options include "geometry", "address_components", "formatted_address", "name", etc.
isForm
boolean
default:false
When true, only shows street name and number in the input after selection (useful for form inputs). When false, shows the full address.
onLocationChange
(location: LocationProps) => void
Callback fired when user selects a location from autocomplete suggestions.

Location Data Structure

The onLocationChange callback receives a LocationProps object:
interface LocationProps {
  address?: string;          // Full formatted address
  sortAddress?: string;      // Short format: "City, Province, Country"
  route?: string;            // Street name
  routeNumber?: string;      // Street number
  city?: string;             // City name
  province?: string;         // Province/state
  zipCode?: string;          // Postal code
  country?: string;          // Country full name
  shortCountry?: string;     // ISO country code (e.g., "ES")
  location?: {               // Coordinates
    lat: number;
    lng: number;
  };
}

Component Behavior

  • Debounced Search: Autocomplete requests are debounced by 500ms to reduce API calls
  • Spanish Localization: Search and error messages are in Spanish
  • Validation: Requires complete address with street number and postal code
  • Error Handling: Shows validation errors in Spanish below the input
  • Loading State: Displays “Cargando…” placeholder while API loads

Troubleshooting

Component stays disabled with “Cargando…” placeholder

  • Verify isLoaded prop is true
  • Check browser console for Google Maps API errors
  • Ensure API key is valid and not restricted
  • Verify Places API is enabled in Google Cloud Console

No autocomplete suggestions appear

  • Check API key billing is enabled (Google requires billing for Places API)
  • Verify API key restrictions allow your domain
  • Check network tab for failed API requests
  • Ensure libraries=places is included in script URL

Error: “Necesitamos una dirección más precisa…”

This is expected behavior when the selected location lacks a street number or postal code. The user must select a more specific address.

API Costs

Google Maps Platform charges per API request. Places Autocomplete costs $2.83-17.00 per 1000 requests depending on usage. Monitor your usage in the Google Cloud Console.Cost-saving tips:
  • Use session tokens (automatically handled by @react-google-maps/api)
  • The component’s 500ms debounce reduces unnecessary requests
  • Set up billing alerts in Google Cloud Console

Next Steps

InputLocation Component

View full component documentation and examples

Optional Dependencies

Learn about other optional peer dependencies

Build docs developers (and LLMs) love