{"id":13450827,"url":"https://github.com/wellyshen/use-places-autocomplete","last_synced_at":"2025-05-13T19:14:32.114Z","repository":{"id":37072303,"uuid":"234698190","full_name":"wellyshen/use-places-autocomplete","owner":"wellyshen","description":"😎 📍 React hook for Google Maps Places Autocomplete.","archived":false,"fork":false,"pushed_at":"2025-04-02T14:39:17.000Z","size":5513,"stargazers_count":1274,"open_issues_count":40,"forks_count":64,"subscribers_count":9,"default_branch":"master","last_synced_at":"2025-04-27T20:01:47.188Z","etag":null,"topics":["autocomplete","geocoding","geocoding-api","google-maps","google-maps-api","google-place-autocomplete","google-places","google-places-api","hook","places","places-autocomplete","react","typescript","use-places-autocomplete"],"latest_commit_sha":null,"homepage":"https://use-places-autocomplete.netlify.app","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/wellyshen.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":null,"patreon":null,"open_collective":"use-places-autocomplete","ko_fi":null,"tidelift":null,"community_bridge":null,"liberapay":null,"issuehunt":null,"otechie":null,"custom":null}},"created_at":"2020-01-18T07:28:41.000Z","updated_at":"2025-04-22T22:31:10.000Z","dependencies_parsed_at":"2025-04-12T01:55:31.715Z","dependency_job_id":"a1269aae-e7ea-47e7-b373-6117d3f0533b","html_url":"https://github.com/wellyshen/use-places-autocomplete","commit_stats":{"total_commits":1163,"total_committers":15,"mean_commits":77.53333333333333,"dds":0.5012897678417885,"last_synced_commit":"4200fdb17b96779e870778cc7dec0dc8f7a08214"},"previous_names":[],"tags_count":99,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wellyshen%2Fuse-places-autocomplete","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wellyshen%2Fuse-places-autocomplete/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wellyshen%2Fuse-places-autocomplete/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wellyshen%2Fuse-places-autocomplete/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/wellyshen","download_url":"https://codeload.github.com/wellyshen/use-places-autocomplete/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":251958685,"owners_count":21671419,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["autocomplete","geocoding","geocoding-api","google-maps","google-maps-api","google-place-autocomplete","google-places","google-places-api","hook","places","places-autocomplete","react","typescript","use-places-autocomplete"],"created_at":"2024-07-31T07:00:39.010Z","updated_at":"2025-05-13T19:14:32.096Z","avatar_url":"https://github.com/wellyshen.png","language":"TypeScript","funding_links":["https://opencollective.com/use-places-autocomplete"],"categories":["Packages","TypeScript"],"sub_categories":[],"readme":"\u003e 👀 We're actively seeking dedicated maintainers for the repo — if you're interested, please contact me directly.\n\n# \u003cem\u003e\u003cb\u003eUSE-PLACES-AUTOCOMPLETE\u003c/b\u003e\u003c/em\u003e\n\nThis is a React [hook](https://reactjs.org/docs/hooks-custom.html#using-a-custom-hook) for [Google Maps Places Autocomplete](https://developers.google.com/maps/documentation/javascript/places-autocomplete), which helps you build a UI component with the feature of place autocomplete easily! By leveraging the power of [Google Maps Places API](https://developers.google.com/maps/documentation/javascript/places), you can provide a great UX (user experience) for user interacts with your search bar or form, etc. Hope you guys 👍🏻 it.\n\n❤️ it? ⭐️ it on [GitHub](https://github.com/wellyshen/use-places-autocomplete/stargazers) or [Tweet](https://twitter.com/intent/tweet?text=With%20@use-places-autocomplete,%20I%20can%20build%20a%20component%20with%20the%20feature%20of%20place%20autocomplete%20easily!%20Thanks,%20@Welly%20Shen%20🤩) about it.\n\n[![build status](https://img.shields.io/github/workflow/status/wellyshen/use-places-autocomplete/CI?style=flat-square)](https://github.com/wellyshen/use-places-autocomplete/actions?query=workflow%3ACI)\n[![coverage status](https://img.shields.io/coveralls/github/wellyshen/use-places-autocomplete?style=flat-square)](https://coveralls.io/github/wellyshen/use-places-autocomplete?branch=master)\n[![npm version](https://img.shields.io/npm/v/use-places-autocomplete?style=flat-square)](https://www.npmjs.com/package/use-places-autocomplete)\n[![npm downloads](https://img.shields.io/npm/dm/use-places-autocomplete?style=flat-square)](https://www.npmtrends.com/use-places-autocomplete)\n[![npm downloads](https://img.shields.io/npm/dt/use-places-autocomplete?style=flat-square)](https://www.npmtrends.com/use-places-autocomplete)\n[![gzip size](https://badgen.net/bundlephobia/minzip/use-places-autocomplete?label=gzip%20size\u0026style=flat-square)](https://bundlephobia.com/result?p=use-places-autocomplete)\n[![All Contributors](https://img.shields.io/badge/all_contributors-12-orange.svg?style=flat-square)](#contributors-)\n[![PRs welcome](https://img.shields.io/badge/PRs-welcome-brightgreen?style=flat-square)](CONTRIBUTING.md)\n[![Twitter URL](https://img.shields.io/twitter/url?style=social\u0026url=https%3A%2F%2Fgithub.com%2Fwellyshen%2Fuse-places-autocomplete)](https://twitter.com/intent/tweet?text=With%20@use-places-autocomplete,%20I%20can%20build%20a%20component%20with%20the%20feature%20of%20place%20autocomplete%20easily!%20Thanks,%20@Welly%20Shen%20🤩)\n\n## Live Demo\n\n![demo](https://user-images.githubusercontent.com/21308003/91069764-6133e680-e668-11ea-8a57-bfbea2cfbd29.gif)\n\n⚡️ Try yourself: https://use-places-autocomplete.netlify.app\n\n## Features\n\n- 🧠 Provides intelligent places suggestions powered by [Google Maps Places API](https://developers.google.com/maps/documentation/javascript/places).\n- 🎣 Builds your own customized autocomplete UI by [React hook](https://reactjs.org/docs/hooks-custom.html#using-a-custom-hook).\n- 🔧 [Utility functions](#utility-functions) to do geocoding and get geographic coordinates using [Google Maps Geocoding API](https://developers.google.com/maps/documentation/javascript/geocoding).\n- 🤑 Built-in [cache mechanism](#cache-data-for-you) for you to save the cost of Google APIs.\n- 💰 Built-in debounce mechanism for you to lower the cost of Google APIs.\n- 🚀 Supports asynchronous Google script loading.\n- 📜 Supports [TypeScript](https://www.typescriptlang.org) type definition.\n- ⌨️ Builds a UX-rich component (e.g. [WAI-ARIA compliant](https://rawgit.com/w3c/aria-practices/master/aria-practices-DeletedSectionsArchive.html#autocomplete) and keyword support) via comprehensive [demo code](app/src/App/index.tsx).\n- 🦔 Tiny size ([~ 1.7KB gzipped](https://bundlephobia.com/result?p=use-places-autocomplete)). No external dependencies, aside from the `react`.\n\n## Requirement\n\nTo use `use-places-autocomplete`, you must use `react@16.8.0` or greater which includes hooks.\n\n## Installation\n\nThis package is distributed via [npm](https://www.npmjs.com/package/use-places-autocomplete).\n\n```sh\n$ yarn add use-places-autocomplete\n# or\n$ npm install --save use-places-autocomplete\n```\n\nWhen working with TypeScript you need to install the [@types/google.maps](https://www.npmjs.com/package/@types/google.maps) as a `devDependencies`.\n\n```sh\n$ yarn add --dev @types/google.maps\n# or\n$ npm install --save-dev @types/google.maps\n```\n\n## Getting Started\n\n`usePlacesAutocomplete` is based on the [Places Autocomplete](https://developers.google.com/maps/documentation/javascript/places-autocomplete) (or more specific [docs](https://developers.google.com/maps/documentation/javascript/reference/places-autocomplete-service)) of [Google Maps Place API](https://developers.google.com/maps/documentation/javascript/places). If you are unfamiliar with these APIs, we recommend you review them before we start.\n\n### Setup APIs\n\nTo use this hook, there're two things we need to do:\n\n1. [Enable Google Maps Places API](https://developers.google.com/maps/documentation/javascript/places#enable_apis).\n2. [Get an API key](https://developers.google.com/maps/documentation/javascript/get-api-key).\n\n### Load the library\n\nUse the `script` tag to load the library in your project and pass the value of the `callback` parameter to the [callbackName](#parameter-optional) option.\n\n```js\n\u003cscript\n  defer\n  src=\"https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY\u0026libraries=places\u0026callback=YOUR_CALLBACK_NAME\"\n\u003e\u003c/script\u003e\n```\n\n\u003e ⚠️ If you got a global function not found error. Make sure `usePlaceAutocomplete` is declared before the script was loaded. You can use the [async or defer](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attributes) attribute of the `\u003cscript\u003e` element to achieve that.\n\n### Create the component\n\nNow we can start to build our component. Check the [API](#api) out to learn more.\n\n```js\nimport usePlacesAutocomplete, {\n  getGeocode,\n  getLatLng,\n} from \"use-places-autocomplete\";\nimport useOnclickOutside from \"react-cool-onclickoutside\";\n\nconst PlacesAutocomplete = () =\u003e {\n  const {\n    ready,\n    value,\n    suggestions: { status, data },\n    setValue,\n    clearSuggestions,\n  } = usePlacesAutocomplete({\n    callbackName: \"YOUR_CALLBACK_NAME\",\n    requestOptions: {\n      /* Define search scope here */\n    },\n    debounce: 300,\n  });\n  const ref = useOnclickOutside(() =\u003e {\n    // When the user clicks outside of the component, we can dismiss\n    // the searched suggestions by calling this method\n    clearSuggestions();\n  });\n\n  const handleInput = (e) =\u003e {\n    // Update the keyword of the input element\n    setValue(e.target.value);\n  };\n\n  const handleSelect =\n    ({ description }) =\u003e\n    () =\u003e {\n      // When the user selects a place, we can replace the keyword without request data from API\n      // by setting the second parameter to \"false\"\n      setValue(description, false);\n      clearSuggestions();\n\n      // Get latitude and longitude via utility functions\n      getGeocode({ address: description }).then((results) =\u003e {\n        const { lat, lng } = getLatLng(results[0]);\n        console.log(\"📍 Coordinates: \", { lat, lng });\n      });\n    };\n\n  const renderSuggestions = () =\u003e\n    data.map((suggestion) =\u003e {\n      const {\n        place_id,\n        structured_formatting: { main_text, secondary_text },\n      } = suggestion;\n\n      return (\n        \u003cli key={place_id} onClick={handleSelect(suggestion)}\u003e\n          \u003cstrong\u003e{main_text}\u003c/strong\u003e \u003csmall\u003e{secondary_text}\u003c/small\u003e\n        \u003c/li\u003e\n      );\n    });\n\n  return (\n    \u003cdiv ref={ref}\u003e\n      \u003cinput\n        value={value}\n        onChange={handleInput}\n        disabled={!ready}\n        placeholder=\"Where are you going?\"\n      /\u003e\n      {/* We can use the \"status\" to decide whether we should display the dropdown or not */}\n      {status === \"OK\" \u0026\u0026 \u003cul\u003e{renderSuggestions()}\u003c/ul\u003e}\n    \u003c/div\u003e\n  );\n};\n```\n\n\u003e 💡 [react-cool-onclickoutside](https://github.com/wellyshen/react-cool-onclickoutside) is my other hook library, which can help you handle the interaction of user clicks outside of the component(s).\n\nEasy right? This is the magic of `usePlacesAutocomplete` ✨. I just showed you how it works via a minimal example. However, you can build a UX rich autocomplete component, like [WAI-ARIA compliant](https://rawgit.com/w3c/aria-practices/master/aria-practices-DeletedSectionsArchive.html#autocomplete) and keyword interaction like my [demo](#live-demo), by checking the [code](app/src/App/index.tsx) or integrating this hook with the [combobox](https://reacttraining.com/reach-ui/combobox) of [Reach UI](https://reacttraining.com/reach-ui) to achieve that.\n\n[![Edit usePlacesAutocomplete x Reach UI](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/useplacesautocomplete-x-reach-ui-lik2c?fontsize=14\u0026hidenavigation=1\u0026theme=dark)\n\n```js\nimport usePlacesAutocomplete from \"use-places-autocomplete\";\nimport {\n  Combobox,\n  ComboboxInput,\n  ComboboxPopover,\n  ComboboxList,\n  ComboboxOption,\n} from \"@reach/combobox\";\n\nimport \"@reach/combobox/styles.css\";\n\nconst PlacesAutocomplete = () =\u003e {\n  const {\n    ready,\n    value,\n    suggestions: { status, data },\n    setValue,\n  } = usePlacesAutocomplete({ callbackName: \"YOUR_CALLBACK_NAME\" });\n\n  const handleInput = (e) =\u003e {\n    setValue(e.target.value);\n  };\n\n  const handleSelect = (val) =\u003e {\n    setValue(val, false);\n  };\n\n  return (\n    \u003cCombobox onSelect={handleSelect} aria-labelledby=\"demo\"\u003e\n      \u003cComboboxInput value={value} onChange={handleInput} disabled={!ready} /\u003e\n      \u003cComboboxPopover\u003e\n        \u003cComboboxList\u003e\n          {status === \"OK\" \u0026\u0026\n            data.map(({ place_id, description }) =\u003e (\n              \u003cComboboxOption key={place_id} value={description} /\u003e\n            ))}\n        \u003c/ComboboxList\u003e\n      \u003c/ComboboxPopover\u003e\n    \u003c/Combobox\u003e\n  );\n};\n```\n\n## Lazily Initializing The Hook\n\nWhen loading the Google Maps Places API via a 3rd-party library, you may need to wait for the script to be ready before using this hook. However, you can lazily initialize the hook in the following ways, depending on your use case.\n\n### Option 1, manually initialize the hook:\n\n```js\nimport usePlacesAutocomplete from \"use-places-autocomplete\";\n\nconst App = () =\u003e {\n  const { init } = usePlacesAutocomplete({\n    initOnMount: false, // Disable initializing when the component mounts, default is true\n  });\n\n  const [loading] = useGoogleMapsApi({\n    library: \"places\",\n    onLoad: () =\u003e init(), // Lazily initializing the hook when the script is ready\n  });\n\n  return \u003cdiv\u003e{/* Some components... */}\u003c/div\u003e;\n};\n```\n\n### Option 2, wrap the hook into a conditional component:\n\n```js\nimport usePlacesAutocomplete from \"use-places-autocomplete\";\n\nconst PlacesAutocomplete = () =\u003e {\n  const { ready, value, suggestions, setValue } = usePlacesAutocomplete();\n\n  return \u003cdiv\u003e{/* Some components... */}\u003c/div\u003e;\n};\n\nconst App = () =\u003e {\n  const [loading] = useGoogleMapsApi({ library: \"places\" });\n\n  return (\n    \u003cdiv\u003e\n      {!loading ? \u003cPlacesAutocomplete /\u003e : null}\n      {/* Other components... */}\n    \u003c/div\u003e\n  );\n};\n```\n\n## Cache Data For You\n\nBy default, this library caches the response data to help you save the [cost of Google Maps Places API](https://developers.google.com/maps/billing/gmp-billing#ac-per-request) and optimize search performance.\n\n```js\nconst methods = usePlacesAutocomplete({\n  // Provide the cache time in seconds, the default is 24 hours\n  cache: 24 * 60 * 60,\n});\n```\n\n\u003e By the way, the cached data is stored via the [Window.sessionStorage API](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage).\n\n### Custom cache key\n\nYou may need to have multiple caches. For example, if you use different [place type restrictions](https://developers.google.com/maps/documentation/places/web-service/supported_types#table3_) for different pickers in your app.\n\n```js\nconst methods = usePlacesAutocomplete({\n  // Provide a custom cache key\n  cacheKey: \"region-restricted\",\n});\n```\n\n\u003e Note that usePlacesAutocomplete will prefix this with `upa-`, so the above would become `upa-region-restricted` in sessionStorage.\n\n## API\n\n```js\nconst returnObj = usePlacesAutocomplete(parameterObj);\n```\n\n### Parameter object (optional)\n\nWhen using `usePlacesAutocomplete`, you can configure the following options via the parameter.\n\n| Key              | Type            | Default              | Description                                                                                                                                                                                                             |\n| ---------------- | --------------- | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `requestOptions` | object          |                      | The [request options](https://developers.google.com/maps/documentation/javascript/reference/places-autocomplete-service#AutocompletionRequest) of Google Maps Places API except for `input` (e.g. bounds, radius, etc.).|\n| `googleMaps`     | object          | `window.google.maps` | In case you want to provide your own Google Maps object, pass the `google.maps` to it.                                                                                                                                  |\n| `callbackName`   | string          |                      | The value of the `callback` parameter when [loading the Google Maps JavaScript library](#load-the-library).                                                                                                             |\n| `debounce`       | number          | `200`                | Number of milliseconds to delay before making a request to Google Maps Places API.                                                                                                                                      |\n| `cache`          | number \\| false | `86400` (24 hours)   | Number of seconds to [cache the response data of Google Maps Places API](#cache-data-for-you).                                                                                                                          |\n| `cacheKey`       | string          | `\"upa\"`              | Optional cache key so one can use multiple caches if needed.                                                                                                                                                            |\n| `defaultValue`   | string          | `\"\"`                 | Default value for the `input` element.                                                                                                                                                                                  |\n| `initOnMount`    | boolean         | `true`               | Initialize the hook with Google Maps Places API when the component mounts.                                                                                                                                              |\n\n### Return object\n\nIt's returned with the following properties.\n\n| Key                | Type     | Default                                    | Description                                                                |\n| ------------------ | -------- | ------------------------------------------ | -------------------------------------------------------------------------- |\n| `ready`            | boolean  | `false`                                    | The ready status of `usePlacesAutocomplete`.                               |\n| `value`            | string   | `\"\"`                                       | `value` for the input element.                                             |\n| `suggestions`      | object   | `{ loading: false, status: \"\", data: [] }` | See [suggestions](#suggestions).                                           |\n| `setValue`         | function | `(value, shouldFetchData = true) =\u003e {}`    | See [setValue](#setvalue).                                                 |\n| `clearSuggestions` | function |                                            | See [clearSuggestions](#clearsuggestions).                                 |\n| `clearCache`       | function | `(key = cacheKey) =\u003e {}`                   | Clears the [cached data](#cache-data-for-you).                             |\n| `init`             | function |                                            | Useful when [lazily initializing the hook](#lazily-initializing-the-hook). |\n\n#### suggestions\n\nThe search result of Google Maps Places API, which contains the following properties:\n\n- `loading: boolean` - indicates the status of a request is pending or has been completed. It's useful for displaying a loading indicator for the user.\n- `status: string` - indicates the status of the API response, which has these [values](https://developers.google.com/maps/documentation/javascript/reference/places-service#PlacesServiceStatus). It's useful to decide whether we should display the dropdown or not.\n- `data: array` - an array of suggestion objects each contains all the [data](https://developers.google.com/maps/documentation/javascript/reference/places-autocomplete-service#AutocompletePrediction).\n\n#### setValue\n\nSet the `value` of the input element. Use the case below.\n\n```js\nimport usePlacesAutocomplete from \"use-places-autocomplete\";\n\nconst PlacesAutocomplete = () =\u003e {\n  const { value, setValue } = usePlacesAutocomplete();\n\n  const handleInput = (e) =\u003e {\n    // Place a \"string\" to update the value of the input element\n    setValue(e.target.value);\n  };\n\n  return (\n    \u003cdiv\u003e\n      \u003cinput value={value} onChange={handleInput} /\u003e\n      {/* Render dropdown */}\n    \u003c/div\u003e\n  );\n};\n```\n\nIn addition, the `setValue` method has an extra parameter, which can be used to disable hitting Google Maps Places API.\n\n```js\nimport usePlacesAutocomplete from \"use-places-autocomplete\";\n\nconst PlacesAutocomplete = () =\u003e {\n  const {\n    value,\n    suggestions: { status, data },\n    setValue,\n  } = usePlacesAutocomplete();\n\n  const handleSelect =\n    ({ description }) =\u003e\n    () =\u003e {\n      // When the user selects a place, we can replace the keyword without requesting data from the API\n      // by setting the second parameter to \"false\"\n      setValue(description, false);\n    };\n\n  const renderSuggestions = () =\u003e\n    data.map((suggestion) =\u003e (\n      \u003cli key={suggestion.place_id} onClick={handleSelect(suggestion)}\u003e\n        {/* Render suggestion text */}\n      \u003c/li\u003e\n    ));\n\n  return (\n    \u003cdiv\u003e\n      \u003cinput value={value} onChange={handleInput} /\u003e\n      {status === \"OK\" \u0026\u0026 \u003cul\u003e{renderSuggestions()}\u003c/ul\u003e}\n    \u003c/div\u003e\n  );\n};\n```\n\n#### clearSuggestions\n\nCalling the method will clear and reset all the properties of the `suggestions` object to default. It's useful for dismissing the dropdown.\n\n```js\nimport usePlacesAutocomplete from \"use-places-autocomplete\";\nimport useOnclickOutside from \"react-cool-onclickoutside\";\n\nconst PlacesAutocomplete = () =\u003e {\n  const {\n    value,\n    suggestions: { status, data },\n    setValue,\n    clearSuggestions,\n  } = usePlacesAutocomplete();\n  const ref = useOnclickOutside(() =\u003e {\n    // When the user clicks outside of the component, call it to clear and reset the suggestions data\n    clearSuggestions();\n  });\n\n  const renderSuggestions = () =\u003e\n    data.map((suggestion) =\u003e (\n      \u003cli key={suggestion.place_id} onClick={handleSelect(suggestion)}\u003e\n        {/* Render suggestion text */}\n      \u003c/li\u003e\n    ));\n\n  return (\n    \u003cdiv ref={ref}\u003e\n      \u003cinput value={value} onChange={handleInput} /\u003e\n      {/* After calling the clearSuggestions(), the \"status\" is reset so the dropdown is hidden */}\n      {status === \"OK\" \u0026\u0026 \u003cul\u003e{renderSuggestions()}\u003c/ul\u003e}\n    \u003c/div\u003e\n  );\n};\n```\n\n## Utility Functions\n\nWe provide [getGeocode](#getgeocode), [getLatLng](#getlatlng), [getZipCode](#getzipcode), and [getDetails](#getdetails) utils for you to do geocoding and get geographic coordinates when needed.\n\n### getGeocode\n\nIt helps you convert address (e.g. \"Section 5, Xinyi Road, Xinyi District, Taipei City, Taiwan\") into geographic coordinates (e.g. latitude 25.033976 and longitude 121.5645389), or restrict the results to a specific area by [Google Maps Geocoding API](https://developers.google.com/maps/documentation/javascript/geocoding).\n\nIn case you want to restrict the results to a specific area, you will have to pass the `address` and the `componentRestrictions` matching the [GeocoderComponentRestrictions interface](https://developers.google.com/maps/documentation/javascript/reference/geocoder#GeocoderComponentRestrictions).\n\n```js\nimport { getGeocode } from \"use-places-autocomplete\";\n\nconst parameter = {\n  address: \"Section 5, Xinyi Road, Xinyi District, Taipei City, Taiwan\",\n  // or\n  placeId: \"ChIJraeA2rarQjQRPBBjyR3RxKw\",\n};\n\ngetGeocode(parameter)\n  .then((results) =\u003e {\n    console.log(\"Geocoding results: \", results);\n  })\n  .catch((error) =\u003e {\n    console.log(\"Error: \", error);\n  });\n```\n\n`getGeocode` is an asynchronous function with the following API:\n\n- `parameter: object` - you must supply one, only one of `address` or `location` or `placeId` and optionally `bounds`, `componentRestrictions`, `region`. It'll be passed as [Geocoding Requests](https://developers.google.com/maps/documentation/javascript/geocoding#GeocodingRequests).\n- `results: array` - an array of objects each contains all the [data](https://developers.google.com/maps/documentation/javascript/geocoding#GeocodingResults).\n- `error: string` - the error status of API response, which has these [values](https://developers.google.com/maps/documentation/javascript/geocoding#GeocodingStatusCodes) (except for \"OK\").\n\n### getLatLng\n\nIt helps you get the `lat` and `lng` from the result object of `getGeocode`.\n\n```js\nimport { getGeocode, getLatLng } from \"use-places-autocomplete\";\n\nconst parameter = {\n  address: \"Section 5, Xinyi Road, Xinyi District, Taipei City, Taiwan\",\n};\n\ngetGeocode(parameter).then((results) =\u003e {\n  const { lat, lng } = getLatLng(results[0]);\n  console.log(\"Coordinates: \", { lat, lng });\n});\n```\n\n`getLatLng` is a function with the following API:\n\n- `parameter: object` - the result object of `getGeocode`.\n- `latLng: object` - contains the latitude and longitude properties.\n- `error: any` - an exception.\n\n### getZipCode\n\nIt helps you get the `postal_code` from the result object of `getGeocode`.\n\n```js\nimport { getGeocode, getZipCode } from \"use-places-autocomplete\";\n\nconst parameter = {\n  address: \"Section 5, Xinyi Road, Xinyi District, Taipei City, Taiwan\",\n};\n\ngetGeocode(parameter)\n  // By default we use the \"long_name\" value from API response, you can tell the utility to use \"short_name\"\n  // by setting the second parameter to \"true\"\n  .then((results) =\u003e {\n    const zipCode = getZipCode(results[0], false);\n    console.log(\"ZIP Code: \", zipCode);\n  });\n```\n\n`getZipCode` is a function with the following API:\n\n- `parameters` - there're two parameters:\n  - `1st: object` - the result object of `getGeocode`.\n  - `2nd: boolean` - should use the `short_name` or not from [API response](https://developers.google.com/places/web-service/details#PlaceDetailsResponses), default is `false`.\n- `zipCode: string | null` - the zip code. If the address doesn't have a zip code it will be `null`.\n- `error: any` - an exception.\n\n### getDetails\n\nRetrieves a great deal of information about a particular place ID (`suggestion`).\n\n```js\nimport usePlacesAutocomplete, { getDetails } from \"use-places-autocomplete\";\n\nconst PlacesAutocomplete = () =\u003e {\n  const { suggestions, value, setValue } = usePlacesAutocomplete();\n\n  const handleInput = (e) =\u003e {\n    // Place a \"string\" to update the value of the input element\n    setValue(e.target.value);\n  };\n\n  const submit = () =\u003e {\n    const parameter = {\n      // Use the \"place_id\" of suggestion from the dropdown (object), here just taking the first suggestion for brevity\n      placeId: suggestions[0].place_id,\n      // Specify the return data that you want (optional)\n      fields: [\"name\", \"rating\"],\n    };\n\n    getDetails(parameter)\n      .then((details) =\u003e {\n        console.log(\"Details: \", details);\n      })\n      .catch((error) =\u003e {\n        console.log(\"Error: \", error);\n      });\n  };\n\n  return (\n    \u003cdiv\u003e\n      \u003cinput value={value} onChange={handleInput} /\u003e\n      {/* Render dropdown */}\n      \u003cbutton onClick={submit}\u003eSubmit Suggestion\u003c/button\u003e\n    \u003c/div\u003e\n  );\n};\n```\n\n`getDetails` is an asynchronous function with the following API:\n\n- `parameter: object` - [the request](https://developers.google.com/maps/documentation/javascript/places#place_details_requests) of the PlacesService's `getDetails()` method. You must supply the `placeId` that you would like details about. If you do not specify any fields or omit the fields parameter you will get every field available.\n- `placeResult: object | null` - [the details](https://developers.google.com/maps/documentation/javascript/reference/places-service#PlaceResult) about the specific place your queried.\n- `error: any` - an exception.\n\n\u003e ⚠️ warning, you are billed based on how much information you retrieve, So it is advised that you retrieve just what you need.\n\n## Articles / Blog Posts\n\n\u003e 💡 If you have written any blog post or article about `use-places-autocomplete`, please open a PR to add it here.\n\n- Featured on [React Status #175](https://react.statuscode.com/issues/175).\n- Featured on [React Newsletter #199](https://reactnewsletter.com/issues/199).\n\n## Contributors ✨\n\nThanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):\n\n\u003c!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section --\u003e\n\u003c!-- prettier-ignore-start --\u003e\n\u003c!-- markdownlint-disable --\u003e\n\u003ctable\u003e\n  \u003ctbody\u003e\n    \u003ctr\u003e\n      \u003ctd align=\"center\" valign=\"top\" width=\"14.28%\"\u003e\u003ca href=\"https://wellyshen.com\"\u003e\u003cimg src=\"https://avatars1.githubusercontent.com/u/21308003?v=4?s=100\" width=\"100px;\" alt=\"Welly\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003eWelly\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"https://github.com/wellyshen/use-places-autocomplete/commits?author=wellyshen\" title=\"Code\"\u003e💻\u003c/a\u003e \u003ca href=\"https://github.com/wellyshen/use-places-autocomplete/commits?author=wellyshen\" title=\"Documentation\"\u003e📖\u003c/a\u003e \u003ca href=\"#maintenance-wellyshen\" title=\"Maintenance\"\u003e🚧\u003c/a\u003e\u003c/td\u003e\n      \u003ctd align=\"center\" valign=\"top\" width=\"14.28%\"\u003e\u003ca href=\"https://kylekirkby.github.io\"\u003e\u003cimg src=\"https://avatars0.githubusercontent.com/u/4564433?v=4?s=100\" width=\"100px;\" alt=\"Kyle\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003eKyle\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"#translation-kylekirkby\" title=\"Translation\"\u003e🌍\u003c/a\u003e\u003c/td\u003e\n      \u003ctd align=\"center\" valign=\"top\" width=\"14.28%\"\u003e\u003ca href=\"https://www.lkaric.tech\"\u003e\u003cimg src=\"https://avatars0.githubusercontent.com/u/16634314?v=4?s=100\" width=\"100px;\" alt=\"Lazar Karić\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003eLazar Karić\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"https://github.com/wellyshen/use-places-autocomplete/commits?author=rejvban\" title=\"Code\"\u003e💻\u003c/a\u003e \u003ca href=\"https://github.com/wellyshen/use-places-autocomplete/commits?author=rejvban\" title=\"Documentation\"\u003e📖\u003c/a\u003e\u003c/td\u003e\n      \u003ctd align=\"center\" valign=\"top\" width=\"14.28%\"\u003e\u003ca href=\"https://github.com/reharik\"\u003e\u003cimg src=\"https://avatars2.githubusercontent.com/u/882382?v=4?s=100\" width=\"100px;\" alt=\"Raif Harik\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003eRaif Harik\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"https://github.com/wellyshen/use-places-autocomplete/commits?author=reharik\" title=\"Code\"\u003e💻\u003c/a\u003e \u003ca href=\"https://github.com/wellyshen/use-places-autocomplete/commits?author=reharik\" title=\"Documentation\"\u003e📖\u003c/a\u003e \u003ca href=\"#ideas-reharik\" title=\"Ideas, Planning, \u0026 Feedback\"\u003e🤔\u003c/a\u003e\u003c/td\u003e\n      \u003ctd align=\"center\" valign=\"top\" width=\"14.28%\"\u003e\u003ca href=\"https://github.com/Xerxes-J\"\u003e\u003cimg src=\"https://avatars0.githubusercontent.com/u/18053412?v=4?s=100\" width=\"100px;\" alt=\"Xerxes Jarquin\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003eXerxes Jarquin\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"https://github.com/wellyshen/use-places-autocomplete/issues?q=author%3AXerxes-J\" title=\"Bug reports\"\u003e🐛\u003c/a\u003e\u003c/td\u003e\n      \u003ctd align=\"center\" valign=\"top\" width=\"14.28%\"\u003e\u003ca href=\"https://www.lucasoconnell.net/\"\u003e\u003cimg src=\"https://avatars1.githubusercontent.com/u/63400356?v=4?s=100\" width=\"100px;\" alt=\"Lucas O'Connell\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003eLucas O'Connell\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"https://github.com/wellyshen/use-places-autocomplete/commits?author=Isoaxe\" title=\"Documentation\"\u003e📖\u003c/a\u003e\u003c/td\u003e\n      \u003ctd align=\"center\" valign=\"top\" width=\"14.28%\"\u003e\u003ca href=\"http://www.keven.com.br\"\u003e\u003cimg src=\"https://avatars.githubusercontent.com/u/5994795?v=4?s=100\" width=\"100px;\" alt=\"Keven Jesus\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003eKeven Jesus\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"https://github.com/wellyshen/use-places-autocomplete/issues?q=author%3Akevenjesus\" title=\"Bug reports\"\u003e🐛\u003c/a\u003e\u003c/td\u003e\n    \u003c/tr\u003e\n    \u003ctr\u003e\n      \u003ctd align=\"center\" valign=\"top\" width=\"14.28%\"\u003e\u003ca href=\"https://github.com/viniciusueharaweb\"\u003e\u003cimg src=\"https://avatars.githubusercontent.com/u/77734864?v=4?s=100\" width=\"100px;\" alt=\"Vinicius Uehara\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003eVinicius Uehara\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"https://github.com/wellyshen/use-places-autocomplete/commits?author=viniciusueharaweb\" title=\"Documentation\"\u003e📖\u003c/a\u003e\u003c/td\u003e\n      \u003ctd align=\"center\" valign=\"top\" width=\"14.28%\"\u003e\u003ca href=\"http://orbiteleven.net\"\u003e\u003cimg src=\"https://avatars.githubusercontent.com/u/331393?v=4?s=100\" width=\"100px;\" alt=\"Damon\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003eDamon\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"https://github.com/wellyshen/use-places-autocomplete/commits?author=orbiteleven\" title=\"Code\"\u003e💻\u003c/a\u003e\u003c/td\u003e\n      \u003ctd align=\"center\" valign=\"top\" width=\"14.28%\"\u003e\u003ca href=\"https://github.com/RavenHursT\"\u003e\u003cimg src=\"https://avatars.githubusercontent.com/u/496983?v=4?s=100\" width=\"100px;\" alt=\"Matthew Marcus\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003eMatthew Marcus\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"https://github.com/wellyshen/use-places-autocomplete/commits?author=RavenHursT\" title=\"Code\"\u003e💻\u003c/a\u003e\u003c/td\u003e\n      \u003ctd align=\"center\" valign=\"top\" width=\"14.28%\"\u003e\u003ca href=\"https://github.com/csandman\"\u003e\u003cimg src=\"https://avatars.githubusercontent.com/u/9214195?v=4?s=100\" width=\"100px;\" alt=\"Chris Sandvik\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003eChris Sandvik\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"https://github.com/wellyshen/use-places-autocomplete/commits?author=csandman\" title=\"Code\"\u003e💻\u003c/a\u003e\u003c/td\u003e\n      \u003ctd align=\"center\" valign=\"top\" width=\"14.28%\"\u003e\u003ca href=\"https://linktr.ee/tyeetale\"\u003e\u003cimg src=\"https://avatars.githubusercontent.com/u/17817587?v=4?s=100\" width=\"100px;\" alt=\"Thomas Yee\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003eThomas Yee\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"https://github.com/wellyshen/use-places-autocomplete/commits?author=tyeetale\" title=\"Documentation\"\u003e📖\u003c/a\u003e\u003c/td\u003e\n    \u003c/tr\u003e\n  \u003c/tbody\u003e\n\u003c/table\u003e\n\n\u003c!-- markdownlint-restore --\u003e\n\u003c!-- prettier-ignore-end --\u003e\n\n\u003c!-- ALL-CONTRIBUTORS-LIST:END --\u003e\n\nThis project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind are welcome!\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwellyshen%2Fuse-places-autocomplete","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fwellyshen%2Fuse-places-autocomplete","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwellyshen%2Fuse-places-autocomplete/lists"}