Gathering detailed insights and metrics for preact-places-autocomplete
Gathering detailed insights and metrics for preact-places-autocomplete
Gathering detailed insights and metrics for preact-places-autocomplete
Gathering detailed insights and metrics for preact-places-autocomplete
npm install preact-places-autocomplete
Typescript
Module System
Node Version
NPM Version
76.4
Supply Chain
98.3
Quality
75
Maintenance
100
Vulnerability
99.6
License
Cumulative downloads
Total Downloads
Last day
-66.7%
1
Compared to previous day
Last week
-14.3%
6
Compared to previous week
Last month
133.3%
14
Compared to previous month
Last year
23.1%
80
Compared to previous year
No dependencies detected.
A React component to build a customized UI for Google Maps Places Autocomplete
Live demo: kenny-hibino.github.io/preact-places-autocomplete/
To install the stable version
1npm install --save preact-places-autocomplete
React component is exported as a default export
1import PlacesAutocomplete from 'preact-places-autocomplete'
utility functions are named exports
1import { geocodeByAddress, geocodeByPlaceId, getLatLng } from 'preact-places-autocomplete'
To use this component, you are going to need to load Google Maps JavaScript API
Load the library in your project
1<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>
Create your component
1import React from 'react' 2import PlacesAutocomplete, { geocodeByAddress, getLatLng } from 'preact-places-autocomplete' 3 4class LocationSearchInput extends React.Component { 5 constructor(props) { 6 super(props); 7 this.state = { address: '' } 8 } 9 10 handleChange = (address) => { 11 this.setState({ address }) 12 } 13 14 handleSelect = (address) => { 15 geocodeByAddress(address) 16 .then(results => getLatLng(results[0])) 17 .then(latLng => console.log('Success', latLng)) 18 .catch(error => console.error('Error', error)) 19 } 20 21 render() { 22 return ( 23 <PlacesAutocomplete 24 value={this.state.address} 25 onChange={this.handleChange} 26 onSelect={this.handleSelect} 27 > 28 {({ getInputProps, suggestions, getSuggestionItemProps }) => ( 29 <div> 30 <input 31 {...getInputProps({ 32 placeholder: 'Search Places ...', 33 className: 'location-search-input' 34 })} 35 /> 36 <div className="autocomplete-dropdown-container"> 37 {suggestions.map(suggestion => { 38 const className = suggestion.active ? 'suggestion-item--active' : 'suggestion-item'; 39 // inline style for demonstration purpose 40 const style = suggestion.active 41 ? { backgroundColor: '#fafafa', cursor: 'pointer' } 42 : { backgroundColor: '#ffffff', cursor: 'pointer' }; 43 return ( 44 <div {...getSuggestionItemProps(suggestion, { className, style })}> 45 <span>{suggestion.description}</span> 46 </div> 47 ) 48 })} 49 </div> 50 </div> 51 )} 52 </PlacesAutocomplete> 53 ); 54 } 55}
PlacesAutocomplete is a Controlled Component with a Render Prop. Therefore, you MUST pass at least value
and onChange
callback to the input element, and render function via children
.
Prop | Type | Required | Description |
---|---|---|---|
value | string | :white_check_mark: | value for the input element |
onChange | function | :white_check_mark: | onChange function for the input element |
children | function | :white_check_mark: | Render function to specify the rendering |
onSelect | function | Event handler to handle user's select event | |
onError | function | Error handler function that gets called when Google Maps API responds with an error | |
searchOptions | object | Options to Google Maps API (i.e. bounds, radius) | |
debounce | number | Number of milliseconds to delay before making a call to Google Maps API | |
highlightFirstSuggestion | boolean | If set to true , first list item in the dropdown will be automatically highlighted | |
shouldFetchSuggestions | boolean | Component will hit Google Maps API only if this flag is set true | |
googleCallbackName | string | You can provide a callback name to initialize PlacesAutocomplete after google script is loaded |
Type: string
,
Required: true
Type: function
,
Required: true
Typically this event handler will update value
state.
1<PlacesAutocomplete 2 value={this.state.value} 3 onChange={value => this.setState({ value })} 4> 5 {/* custom render function */} 6</PlacesAutocomplete>
Type: function
Required: true
This is where you render whatever you want to based on the state of PlacesAutocomplete
.
The function will take an object with the following keys.
getInputProps
: functiongetSuggestionItemProps
: functionsuggestions
: arraySimple example
1const renderFunc = ({ getInputProps, getSuggestionItemProps, suggestions }) => ( 2 <div className="autocomplete-root"> 3 <input {...getInputProps()} /> 4 <div className="autocomplete-dropdown-container"> 5 {suggestions.map(suggestion => ( 6 <div {...getSuggestionItemProps(suggestion)}> 7 <span>{suggestion.description}</span> 8 </div> 9 ))} 10 </div> 11 </div> 12); 13 14// In render function 15<PlacesAutocomplete 16 value={this.state.value} 17 onChange={this.handleChange} 18> 19 {renderFunc} 20</PlacesAutocomplete>
This function will return the props that you can spread over the <input />
element.
You can optionally call the function with an object to pass other props to the input.
1// In render function
2<input {...getInputProps({ className: 'my-input', autoFocus: true })} />
This function will return the props that you can spread over each suggestion item in your
autocomplete dropdown. You MUST call it with suggestion
object as an argument, and optionally pass an object to pass other props to the element.
1// Simple example 2<div className="autocomplete-dropdown"> 3 {suggestions.map(suggestion => ( 4 <div {...getSuggestionItemProps(suggesions)}> 5 {suggesion.description} 6 </div> 7 ))} 8</div> 9 10// Pass options as a second argument 11<div className="autocomplete-dropdown"> 12 {suggestions.map(suggestion => { 13 const className = suggestion.active ? 'suggestion-item--active' : 'suggesion-item'; 14 return ( 15 <div {...getSuggestionItemProps(suggestion, { className })}> 16 {suggestion.description} 17 </div> 18 ); 19 })} 20</div> 21
This is an array of suggestion objects each containing all the data from Google Maps API and other metadata.
An example of a suggestion object.
1{ 2 active: false, 3 description: "San Francisco, CA, USA", 4 formattedSuggestion: { mainText: "San Francisco", secondaryText: "CA, USA" }, 5 id: "1b9ea3c094d3ac23c9a3afa8cd4d8a41f05de50a", 6 index: 0, 7 matchedSubstrings: [ {length: 8, offset: 0} ], 8 placeId: "ChIJIQBpAG2ahYAR_6128GcTUEo", 9 terms: [ 10 { offset: 0, value: "San Francisco" }, 11 { offset: 15, value: "CA" }, 12 { offset: 19, value: "USA" } 13 ], 14 types: ["locality", "political", "geocode"] 15}
Type: function
Required: false
,
Default: null
You can pass a function that gets called instead of onChange
function when user
hits the Enter key or clicks on a suggestion item.
The function takes two positional arguments. First argument is address
, second is placeId
.
1// NOTE: `placeId` is null when user hits Enter key with no suggestion item selected. 2const handleSelect = (address: string, placeId: ?string) => { 3 // Do something with address and placeId 4} 5 6// Pass this function via onSelect prop. 7<PlacesAutocomplete 8 value={this.state.value} 9 onChange={this.handleChange} 10 onSelect={this.handleSelect} 11> 12 {/* Custom render function */} 13</PlacesAutocomplete>
Type: function
Required: false
You can pass onError
prop to customize the behavior when google.maps.places.PlacesServiceStatus is not OK
(e.g., no predictions are found)
Function takes status
(string) and clearSuggestions
(function) as parameters
1// Log error status and clear dropdown when Google Maps API returns an error. 2const onError = (status, clearSuggestions) => { 3 console.log('Google Maps API returned error with status: ', status) 4 clearSuggestions() 5} 6 7<PlacesAutocomplete 8 value={this.state.value} 9 onChange={this.handleChange} 10 onError={onError} 11> 12 {/* Custom render function */} 13</PlacesAutocomplete>
Type: Object
Required: false
Default: {}
You can fine-tune the settings passed to the AutocompleteService class with searchOptions
prop.
This prop accepts an object following the same format as google.maps.places.AutocompletionRequest
(except for input
, which comes from the value of the input field).
1// these options will bias the autocomplete predictions toward Sydney, Australia with a radius of 2000 meters, 2// and limit the results to addresses only 3const searchOptions = { 4 location: new google.maps.LatLng(-34, 151), 5 radius: 2000, 6 types: ['address'] 7} 8 9<PlacesAutocomplete 10 value={this.state.value} 11 onChange={this.handleChange} 12 searchOptions={searchOptions} 13> 14 {/* Custom render function */} 15</PlacesAutocomplete>
Type: number
Required: false
Default: 200
The number of milliseconds to delay before making a call to Google Maps API.
Type: boolean
Required: false
Default: false
If set to true
, first suggestion in the dropdown will be automatically set to be active.
Type: boolean
Required: false
Default: true
1// Only fetch suggestions when the input text is longer than 3 characters. 2<PlacesAutocomplete 3 value={this.state.address} 4 onChange={this.handleChange} 5 shouldFetchSuggestions={this.state.address.length > 3} 6> 7 {/* custom render function */} 8</PlacesAutocomplete>
Type: string
Required: false
Default: undefined
If provided, component will initialize after the browser has finished downloading google script.
IMPORTANT: To enable this async mode, you need to provide the same callback name to google script via callback=[YOUR CALLBACK NAME]
.
Example:
1<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=myCallbackFunc"></script>
Then, provide googleCallbackName
prop to PlacesAutocomplete
.
1<PlacesAutocomplete 2 value={this.state.value} 3 onChange={this.handleChange} 4 googleCallbackName="myCallbackFunc" 5> 6 {/* custom render function */} 7</PlacesAutocomplete>
NOTE: If there are more than one PlacesAutocomplete
components rendered in the page,
set up a callback function that calls a callback function for each component.
Example:
1<script> 2window.myCallbackFunc = function() { 3 window.initOne && window.initOne(); 4 window.initTwo && window.initTwo(); 5} 6</script> 7<script async defer 8src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=myCallbackFunc"></script>
1<PlacesAutocomplete 2 value={this.state.value} 3 onChange={this.handleChange} 4 googleCallbackName="initOne" 5> 6 {/* custom render function */} 7</PlacesAutocomplete> 8 9<PlacesAutocomplete 10 value={this.state.value} 11 onChange={this.handleChange} 12 googleCallbackName="initTwo" 13> 14 {/* custom render function */} 15</PlacesAutocomplete> 16
geocodeByAddress
API1/** 2 * Returns a promise 3 * @param {String} address 4 * @return {Promise} 5*/ 6geocodeByAddress(address)
Type: String
,
Required: true
String that gets passed to Google Maps Geocoder
1import { geocodeByAddress } from 'preact-places-autocomplete' 2 3// `results` is an entire payload from Google API. 4geocodeByAddress('Los Angeles, CA') 5 .then(results => console.log(results)) 6 .catch(error => console.error(error))
geocodeByPlaceId
API1/** 2 * Returns a promise 3 * @param {String} placeId 4 * @return {Promise} 5*/ 6geocodeByPlaceId(placeId)
Type: String
,
Required: true
String that gets passed to Google Maps Geocoder
1import { geocodeByPlaceId } from 'preact-places-autocomplete' 2 3// `results` is an entire payload from Google API. 4geocodeByPlaceId('ChIJE9on3F3HwoAR9AhGJW_fL-I') 5 .then(results => console.log(results)) 6 .catch(error => console.error(error))
getLatLng
API1/** 2 * Returns a promise 3 * @param {Object} result 4 * @return {Promise} 5*/ 6getLatLng(result)
Type: Object
Required: true
One of the element from results
(returned from Google Maps Geocoder)
1import { geocodeByAddress, getLatLng } from 'preact-places-autocomplete' 2 3geocodeByAddress('Tokyo, Japan') 4 .then(results => getLatLng(results[0])) 5 .then(({ lat, lng }) => console.log('Successfully got latitude and longitude', { lat, lng }))
Join us on Gitter if you are interested in contributing!
MIT
No vulnerabilities found.
No security vulnerabilities found.