Gathering detailed insights and metrics for use-places-autocomplete
Gathering detailed insights and metrics for use-places-autocomplete
Gathering detailed insights and metrics for use-places-autocomplete
Gathering detailed insights and metrics for use-places-autocomplete
vue-use-places-autocomplete
📍 Vue composable for Google Maps Places Autocomplete.
v-use-places-autocomplete
[![npm version](https://badge.fury.io/js/v-use-places-autocomplete.svg)](https://badge.fury.io/js/v-use-places-autocomplete) [![bundle size](https://badgen.net/bundlephobia/minzip/v-use-places-autocomplete)](https://bundlephobia.com/result?p=v-use-places-
react-google-places-autocomplete
Google places autocomplete input for ReactJS.
react-google-autocomplete
React component for google autocomplete.
😎 📍 React hook for Google Maps Places Autocomplete.
npm install use-places-autocomplete
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
1,258 Stars
1,808 Commits
65 Forks
9 Watching
24 Branches
11 Contributors
Updated on 21 Nov 2024
Minified
Minified + Gzipped
TypeScript (80.13%)
HTML (7.45%)
SCSS (6.38%)
JavaScript (5.73%)
Shell (0.3%)
Cumulative downloads
Total Downloads
Last day
-15.4%
25,705
Compared to previous day
Last week
-4.9%
137,030
Compared to previous week
Last month
6%
604,084
Compared to previous month
Last year
49.5%
6,577,257
Compared to previous year
1
33
This is a React hook for Google Maps 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, you can provide a great UX (user experience) for user interacts with your search bar or form, etc. Hope you guys 👍🏻 it.
❤️ it? ⭐️ it on GitHub or Tweet about it.
⚡️ Try yourself: https://use-places-autocomplete.netlify.app
react
.To use use-places-autocomplete
, you must use react@16.8.0
or greater which includes hooks.
This package is distributed via npm.
1$ yarn add use-places-autocomplete 2# or 3$ npm install --save use-places-autocomplete
When working with TypeScript you need to install the @types/google.maps as a devDependencies
.
1$ yarn add --dev @types/google.maps 2# or 3$ npm install --save-dev @types/google.maps
usePlacesAutocomplete
is based on the Places Autocomplete (or more specific docs) of Google Maps Place API. If you are unfamiliar with these APIs, we recommend you review them before we start.
To use this hook, there're two things we need to do:
Use the script
tag to load the library in your project and pass the value of the callback
parameter to the callbackName option.
1<script 2 defer 3 src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=YOUR_CALLBACK_NAME" 4></script>
⚠️ 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 attribute of the<script>
element to achieve that.
Now we can start to build our component. Check the API out to learn more.
1import usePlacesAutocomplete, { 2 getGeocode, 3 getLatLng, 4} from "use-places-autocomplete"; 5import useOnclickOutside from "react-cool-onclickoutside"; 6 7const PlacesAutocomplete = () => { 8 const { 9 ready, 10 value, 11 suggestions: { status, data }, 12 setValue, 13 clearSuggestions, 14 } = usePlacesAutocomplete({ 15 callbackName: "YOUR_CALLBACK_NAME", 16 requestOptions: { 17 /* Define search scope here */ 18 }, 19 debounce: 300, 20 }); 21 const ref = useOnclickOutside(() => { 22 // When the user clicks outside of the component, we can dismiss 23 // the searched suggestions by calling this method 24 clearSuggestions(); 25 }); 26 27 const handleInput = (e) => { 28 // Update the keyword of the input element 29 setValue(e.target.value); 30 }; 31 32 const handleSelect = 33 ({ description }) => 34 () => { 35 // When the user selects a place, we can replace the keyword without request data from API 36 // by setting the second parameter to "false" 37 setValue(description, false); 38 clearSuggestions(); 39 40 // Get latitude and longitude via utility functions 41 getGeocode({ address: description }).then((results) => { 42 const { lat, lng } = getLatLng(results[0]); 43 console.log("📍 Coordinates: ", { lat, lng }); 44 }); 45 }; 46 47 const renderSuggestions = () => 48 data.map((suggestion) => { 49 const { 50 place_id, 51 structured_formatting: { main_text, secondary_text }, 52 } = suggestion; 53 54 return ( 55 <li key={place_id} onClick={handleSelect(suggestion)}> 56 <strong>{main_text}</strong> <small>{secondary_text}</small> 57 </li> 58 ); 59 }); 60 61 return ( 62 <div ref={ref}> 63 <input 64 value={value} 65 onChange={handleInput} 66 disabled={!ready} 67 placeholder="Where are you going?" 68 /> 69 {/* We can use the "status" to decide whether we should display the dropdown or not */} 70 {status === "OK" && <ul>{renderSuggestions()}</ul>} 71 </div> 72 ); 73};
💡 react-cool-onclickoutside is my other hook library, which can help you handle the interaction of user clicks outside of the component(s).
Easy 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 and keyword interaction like my demo, by checking the code or integrating this hook with the combobox of Reach UI to achieve that.
1import usePlacesAutocomplete from "use-places-autocomplete"; 2import { 3 Combobox, 4 ComboboxInput, 5 ComboboxPopover, 6 ComboboxList, 7 ComboboxOption, 8} from "@reach/combobox"; 9 10import "@reach/combobox/styles.css"; 11 12const PlacesAutocomplete = () => { 13 const { 14 ready, 15 value, 16 suggestions: { status, data }, 17 setValue, 18 } = usePlacesAutocomplete({ callbackName: "YOUR_CALLBACK_NAME" }); 19 20 const handleInput = (e) => { 21 setValue(e.target.value); 22 }; 23 24 const handleSelect = (val) => { 25 setValue(val, false); 26 }; 27 28 return ( 29 <Combobox onSelect={handleSelect} aria-labelledby="demo"> 30 <ComboboxInput value={value} onChange={handleInput} disabled={!ready} /> 31 <ComboboxPopover> 32 <ComboboxList> 33 {status === "OK" && 34 data.map(({ place_id, description }) => ( 35 <ComboboxOption key={place_id} value={description} /> 36 ))} 37 </ComboboxList> 38 </ComboboxPopover> 39 </Combobox> 40 ); 41};
When 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.
1import usePlacesAutocomplete from "use-places-autocomplete";
2
3const App = () => {
4 const { init } = usePlacesAutocomplete({
5 initOnMount: false, // Disable initializing when the component mounts, default is true
6 });
7
8 const [loading] = useGoogleMapsApi({
9 library: "places",
10 onLoad: () => init(), // Lazily initializing the hook when the script is ready
11 });
12
13 return <div>{/* Some components... */}</div>;
14};
1import usePlacesAutocomplete from "use-places-autocomplete"; 2 3const PlacesAutocomplete = () => { 4 const { ready, value, suggestions, setValue } = usePlacesAutocomplete(); 5 6 return <div>{/* Some components... */}</div>; 7}; 8 9const App = () => { 10 const [loading] = useGoogleMapsApi({ library: "places" }); 11 12 return ( 13 <div> 14 {!loading ? <PlacesAutocomplete /> : null} 15 {/* Other components... */} 16 </div> 17 ); 18};
By default, this library caches the response data to help you save the cost of Google Maps Places API and optimize search performance.
1const methods = usePlacesAutocomplete({
2 // Provide the cache time in seconds, the default is 24 hours
3 cache: 24 * 60 * 60,
4});
By the way, the cached data is stored via the Window.sessionStorage API.
You may need to have multiple caches. For example, if you use different place type restrictions for different pickers in your app.
1const methods = usePlacesAutocomplete({
2 // Provide a custom cache key
3 cacheKey: "region-restricted",
4});
Note that usePlacesAutocomplete will prefix this with
upa-
, so the above would becomeupa-region-restricted
in sessionStorage.
1const returnObj = usePlacesAutocomplete(parameterObj);
When using usePlacesAutocomplete
, you can configure the following options via the parameter.
Key | Type | Default | Description |
---|---|---|---|
requestOptions | object | The request options of Google Maps Places API except for input (e.g. bounds, radius, etc.). | |
googleMaps | object | window.google.maps | In case you want to provide your own Google Maps object, pass the google.maps to it. |
callbackName | string | The value of the callback parameter when loading the Google Maps JavaScript library. | |
debounce | number | 200 | Number of milliseconds to delay before making a request to Google Maps Places API. |
cache | number | false | 86400 (24 hours) | Number of seconds to cache the response data of Google Maps Places API. |
cacheKey | string | "upa" | Optional cache key so one can use multiple caches if needed. |
defaultValue | string | "" | Default value for the input element. |
initOnMount | boolean | true | Initialize the hook with Google Maps Places API when the component mounts. |
It's returned with the following properties.
Key | Type | Default | Description |
---|---|---|---|
ready | boolean | false | The ready status of usePlacesAutocomplete . |
value | string | "" | value for the input element. |
suggestions | object | { loading: false, status: "", data: [] } | See suggestions. |
setValue | function | (value, shouldFetchData = true) => {} | See setValue. |
clearSuggestions | function | See clearSuggestions. | |
clearCache | function | (key = cacheKey) => {} | Clears the cached data. |
init | function | Useful when lazily initializing the hook. |
The search result of Google Maps Places API, which contains the following properties:
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.status: string
- indicates the status of the API response, which has these values. It's useful to decide whether we should display the dropdown or not.data: array
- an array of suggestion objects each contains all the data.Set the value
of the input element. Use the case below.
1import usePlacesAutocomplete from "use-places-autocomplete"; 2 3const PlacesAutocomplete = () => { 4 const { value, setValue } = usePlacesAutocomplete(); 5 6 const handleInput = (e) => { 7 // Place a "string" to update the value of the input element 8 setValue(e.target.value); 9 }; 10 11 return ( 12 <div> 13 <input value={value} onChange={handleInput} /> 14 {/* Render dropdown */} 15 </div> 16 ); 17};
In addition, the setValue
method has an extra parameter, which can be used to disable hitting Google Maps Places API.
1import usePlacesAutocomplete from "use-places-autocomplete"; 2 3const PlacesAutocomplete = () => { 4 const { 5 value, 6 suggestions: { status, data }, 7 setValue, 8 } = usePlacesAutocomplete(); 9 10 const handleSelect = 11 ({ description }) => 12 () => { 13 // When the user selects a place, we can replace the keyword without requesting data from the API 14 // by setting the second parameter to "false" 15 setValue(description, false); 16 }; 17 18 const renderSuggestions = () => 19 data.map((suggestion) => ( 20 <li key={suggestion.place_id} onClick={handleSelect(suggestion)}> 21 {/* Render suggestion text */} 22 </li> 23 )); 24 25 return ( 26 <div> 27 <input value={value} onChange={handleInput} /> 28 {status === "OK" && <ul>{renderSuggestions()}</ul>} 29 </div> 30 ); 31};
Calling the method will clear and reset all the properties of the suggestions
object to default. It's useful for dismissing the dropdown.
1import usePlacesAutocomplete from "use-places-autocomplete"; 2import useOnclickOutside from "react-cool-onclickoutside"; 3 4const PlacesAutocomplete = () => { 5 const { 6 value, 7 suggestions: { status, data }, 8 setValue, 9 clearSuggestions, 10 } = usePlacesAutocomplete(); 11 const ref = useOnclickOutside(() => { 12 // When the user clicks outside of the component, call it to clear and reset the suggestions data 13 clearSuggestions(); 14 }); 15 16 const renderSuggestions = () => 17 data.map((suggestion) => ( 18 <li key={suggestion.place_id} onClick={handleSelect(suggestion)}> 19 {/* Render suggestion text */} 20 </li> 21 )); 22 23 return ( 24 <div ref={ref}> 25 <input value={value} onChange={handleInput} /> 26 {/* After calling the clearSuggestions(), the "status" is reset so the dropdown is hidden */} 27 {status === "OK" && <ul>{renderSuggestions()}</ul>} 28 </div> 29 ); 30};
We provide getGeocode, getLatLng, getZipCode, and getDetails utils for you to do geocoding and get geographic coordinates when needed.
It 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.
In 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.
1import { getGeocode } from "use-places-autocomplete"; 2 3const parameter = { 4 address: "Section 5, Xinyi Road, Xinyi District, Taipei City, Taiwan", 5 // or 6 placeId: "ChIJraeA2rarQjQRPBBjyR3RxKw", 7}; 8 9getGeocode(parameter) 10 .then((results) => { 11 console.log("Geocoding results: ", results); 12 }) 13 .catch((error) => { 14 console.log("Error: ", error); 15 });
getGeocode
is an asynchronous function with the following API:
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.results: array
- an array of objects each contains all the data.error: string
- the error status of API response, which has these values (except for "OK").It helps you get the lat
and lng
from the result object of getGeocode
.
1import { getGeocode, getLatLng } from "use-places-autocomplete"; 2 3const parameter = { 4 address: "Section 5, Xinyi Road, Xinyi District, Taipei City, Taiwan", 5}; 6 7getGeocode(parameter).then((results) => { 8 const { lat, lng } = getLatLng(results[0]); 9 console.log("Coordinates: ", { lat, lng }); 10});
getLatLng
is a function with the following API:
parameter: object
- the result object of getGeocode
.latLng: object
- contains the latitude and longitude properties.error: any
- an exception.It helps you get the postal_code
from the result object of getGeocode
.
1import { getGeocode, getZipCode } from "use-places-autocomplete"; 2 3const parameter = { 4 address: "Section 5, Xinyi Road, Xinyi District, Taipei City, Taiwan", 5}; 6 7getGeocode(parameter) 8 // By default we use the "long_name" value from API response, you can tell the utility to use "short_name" 9 // by setting the second parameter to "true" 10 .then((results) => { 11 const zipCode = getZipCode(results[0], false); 12 console.log("ZIP Code: ", zipCode); 13 });
getZipCode
is a function with the following API:
parameters
- there're two parameters:
1st: object
- the result object of getGeocode
.2nd: boolean
- should use the short_name
or not from API response, default is false
.zipCode: string | null
- the zip code. If the address doesn't have a zip code it will be null
.error: any
- an exception.Retrieves a great deal of information about a particular place ID (suggestion
).
1import usePlacesAutocomplete, { getDetails } from "use-places-autocomplete"; 2 3const PlacesAutocomplete = () => { 4 const { suggestions, value, setValue } = usePlacesAutocomplete(); 5 6 const handleInput = (e) => { 7 // Place a "string" to update the value of the input element 8 setValue(e.target.value); 9 }; 10 11 const submit = () => { 12 const parameter = { 13 // Use the "place_id" of suggestion from the dropdown (object), here just taking the first suggestion for brevity 14 placeId: suggestions[0].place_id, 15 // Specify the return data that you want (optional) 16 fields: ["name", "rating"], 17 }; 18 19 getDetails(parameter) 20 .then((details) => { 21 console.log("Details: ", details); 22 }) 23 .catch((error) => { 24 console.log("Error: ", error); 25 }); 26 }; 27 28 return ( 29 <div> 30 <input value={value} onChange={handleInput} /> 31 {/* Render dropdown */} 32 <button onClick={submit}>Submit Suggestion</button> 33 </div> 34 ); 35};
getDetails
is an asynchronous function with the following API:
parameter: object
- the request 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.placeResult: object | null
- the details about the specific place your queried.error: any
- an exception.⚠️ warning, you are billed based on how much information you retrieve, So it is advised that you retrieve just what you need.
💡 If you have written any blog post or article about
use-places-autocomplete
, please open a PR to add it here.
Thanks goes to these wonderful people (emoji key):
Welly 💻 📖 🚧 | Kyle 🌍 | Lazar Karić 💻 📖 | Raif Harik 💻 📖 🤔 | Xerxes Jarquin 🐛 | Lucas O'Connell 📖 | Keven Jesus 🐛 |
Vinicius Uehara 📖 | Damon 💻 | Matthew Marcus 💻 | Chris Sandvik 💻 | Thomas Yee 📖 |
This project follows the all-contributors specification. Contributions of any kind are welcome!
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
SAST tool detected but not run on all commits
Details
Reason
security policy file detected
Details
Reason
Found 2/17 approved changesets -- score normalized to 1
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
38 existing vulnerabilities detected
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More