tintef / react-google-places-autocomplete Goto Github PK
View Code? Open in Web Editor NEWReact Google Places Autocomplete input -- fully customizable
Home Page: https://tintef.github.io/react-google-places-autocomplete
License: MIT License
React Google Places Autocomplete input -- fully customizable
Home Page: https://tintef.github.io/react-google-places-autocomplete
License: MIT License
According to the documentation, the following request constraints should work.
const autocompletionRequest = { componentRestrictions: { country: 'us' }, location: { lat: Number(40.7128), lng: Number(74.0060) }, radius: 5 }
I am receiving the error: 'Uncaught (in promise) TypeError: a.lat is not a function' back from Google places API. I believe the code processing the location and creating the google.maps.LatLng object may have an issue. I was experiencing the same issue while creating bounds.
Hello.
I can't get location data from object given by onSelect method.
I'm receiving this error in an infinite loop cause sometimes I work offline, there is no way to catch that error and no keep throwing every time I worked offline?
Something like the onError method or something?
How could I get formatted_address from search results?
I was trying another similar component (react-google-autocomplete) and it uses google's own formatting as base for both input and results (for example, 1st word as bolded in results). I wonder if same is possible with this component?
I guess one could partly get it from using geocodeByAddress -function, but then again it takes only one argument, and not object in which one could then restrict or bias the results. And actually, I did not get the bolded word when trying with that.
Anyway thumbs for good component!
Would there be a possibility to return the address components by name? So if a user inserts an address I would like to check the City it is in.
Hi,
First of all, loving the library! Awesome job! 👍
I want to set the currently active suggestion in response to a mouse hover.
I managed to do this with CSS using :hover
but the suggestion that is already active from scrolling with my keyboard arrows remains active (in addition to what I'm hovering over).
Any easy way to do this? Thanks!
Getting the error Failed prop type: Invalid prop bounds
supplied to GooglePlacesAutocomplete
Regardless of if I supply the autocompletionRequest prop to the component. If I do supply property without bounds, same issue. If i supply with bounds: {} same issue.
Cheers
Paul
Hi,
How can i add suggestion to List.
I mean, if there is no google autocomplete suggestion found, i would like input val to be a suggestion in the suggestion container.
Thanks.
Does anyone have a suggestion on how too keep your api key secure upon deployment?
I am using an .env file in development, but when I npm run build, the html file reverts to showing the api key. And then if I manually change it back, the deployed version is not accepting the syntax of (%REACT_APP_KEY%).
I'm getting this error in the console when using this component:
You have included the Google Maps JavaScript API multiple times on this page. This may cause unexpected errors.
And sometimes (not all the time - sometimes it works fine but still throws the above warning) when I type in a place name in the rendered component, the dropdown is stuck at "Loading...".
I did have another Google Maps related fetch that I thought was causing the warning but I've removed that to see if it might solve the issue but no dice.
Here's my import
import GooglePlacesAutocomplete from 'react-google-places-autocomplete';
And here's a stripped down version of how I'm calling the component
const NewHorse = props => {
const [location, setLocation] = useState({});
const [places, setPlaces] = useState([]);
const setLocationState = data => {
setLocation({
id: data.id,
description: data.description
});
}
const GetLocation = () => {
if (places.length > 0) {
// return a select element with places
console.log(places);
// return <Select className="horse-form-select horse-form-input places" options={places} defaultValue={places[0]} onChange={onPlacesChange} />
} else {
return <GooglePlacesAutocomplete onSelect={setLocationState} apiKey={props.firebaseAPIKey} placeholder="Enter a city or zip code" autocompletionRequest={{types: ["(regions)"]}} />
}
}
return (
<Form className="horse-form">
<div className="horse-form-container">
{/* Location */}
<Label className="horse-form-label" for="location">Location</Label>
<div className="location">
{/* <MdLocationSearching fill="white" className="location-icon" onClick={getLocation} /> */}
<GetLocation />
</div>
</div>
</Form>
)
}
Any help is greatly appreciated.
Hi it is possible to load Google API lazily or pragmatically?
I have a React App and I only need this features in a few pages/routes of my code, loading it on all pages is unnecessary
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_GOOGLE_API_KEY&libraries=places"></script>
I start to have this problem from 2.2.0 in a gatsby project (it works only with a downgrade to 2.1.0). It works fine in develop, but once you try to build you will get this error:
ERROR #95313
Building static HTML failed
See our docs page for more info on this error: https://gatsby.dev/debug-html
428 | var _componentDidMount = _asyncToGenerator(
429 | /#PURE/
430 | regeneratorRuntime.mark(function _callee() {
| ^
431 | var _this$props3, apiKey, onLoadFailed;
432 |
433 | return regeneratorRuntime.wrap(function _callee$(_context) {
WebpackError: ReferenceError: regeneratorRuntime is not defined
react-google-places-autocomplete.esm.js:430
node_modules/react-google-places-autocomplete/dist/react-google-places-autocomplete.esm.js:430:1
react-google-places-autocomplete.esm.js:472
node_modules/react-google-places-autocomplete/dist/react-google-places-autocomplete.esm.js:472:4
react-google-places-autocomplete.esm.js:530
node_modules/react-google-places-autocomplete/dist/react-google-places-autocomplete.esm.js:530:3
Hello !
It's not a bug but a question about how to check the value of the Places Autocomplete component. In my case, I have a multi steps form and the field must be valid before accessing to the next step. In my "Billing Address" step I have the following code :
import { Component, h } from 'preact'
import PropTypes from 'prop-types'
import { __ } from '@wordpress/i18n'
import GooglePlacesAutocomplete, { geocodeByAddress } from 'react-google-places-autocomplete'
import { isCountryEU } from '../../../../utils'
import 'react-google-places-autocomplete/dist/index.min.css'
class FieldBillingAddress extends Component {
constructor() {
super()
this.state = {
countryCode: null,
errorMessage: null,
hasError: false,
isValid: false,
}
}
/**
* Get the ISO 3166 country's code from the address
* @param {Object} address contains all location datas from address
*/
getCountryISOCodeFromAddress(address) {
const { handleFieldDatas, index } = this.props
geocodeByAddress(address.description).then(results => {
const result = results[0]
for (let i = 0; i < result.address_components.length; i++) {
let addressType = result.address_components[i].types[0]
if (addressType == 'country') {
const countryCode = result.address_components[i].short_name
this.setState(
{
countryCode,
hasError: false,
isCountryEU: isCountryEU(countryCode),
isValid: true,
},
() => {
handleFieldDatas({
index,
isValid: this.state.isValid,
value: address.description,
})
}
)
}
}
})
}
render() {
const { errorMessage, hasError, isValid } = this.state
let className = ''
className += hasError ? 'form__field--error' : ''
className += isValid ? 'form__field--valid' : ''
return (
<div className="form__fields-row">
<label htmlFor="billing-address" className="form__label">
{__('Your billing address', 'kmo-app')}
</label>
<GooglePlacesAutocomplete
inputClassName={`google-places-autocomplete__input form__field ${className}`}
onSelect={address => this.getCountryISOCodeFromAddress(address)}
placeholder={__('Enter your billing address', 'kmo-app')}
renderInput={props => (
<div className="google-places-autocomplete">
<input {...props} autocomplete="chrome-off" id="billing-address" name="billing-address" type="text" />
</div>
)}
/>
<p className="form__field-indication">{__('Ex: 1 rue de Rivoli, Paris, France', 'kmo-app')}</p>
{hasError && (
<div className="form__field-error-message">
<p>{errorMessage}</p>
</div>
)}
</div>
)
}
}
FieldBillingAddress.propTypes = {
handleFieldDatas: PropTypes.func.isRequired,
index: PropTypes.number.isRequired,
}
export default FieldBillingAddress
As you can see, I pass to my handleFieldDatas
props a boolean parameter isValid
on my <GooglePlacesAutocomplete />
component's onSelect
props. But if the user change the value of the input without selecting an address from the suggestion list, the isValue
value is still at true
. There is a way to listen the input field onChange
?
In the documentation, there is this notice :
Important: do not override the value and onChange properties of the input, neither the onBlur or onKeyDown.
Thanks for help.
I am trying to change the cursor and opacity when a user is hovering over/clicking on a suggestion. To do so, I want to pass in a custom class name using suggestionsClassNames.
Right now I have:
<GooglePlacesAutocomplete suggestionsClassNames={{ container: '', suggestion: '', suggestionActive: "custom-suggestions-classname--active" }}
With this in my main.css
.custom-suggestions-classname--active { color:red; opacity: 0.5; cursor: 'pointer'; }
.custom-suggestions-classname--active:hover { color:red; opacity: 0.5; cursor: 'pointer'; }
And nothing happens when I click/hover over a suggestion.
Since the documentation does not provide any examples for suggestionsClassNames, can anyone tell me what I am doing wrong here? I am somewhat new to JS/CSS.
How to can I add restrictions to location & setup search preference based on Geolocation?
I have tried editing the following, in GooglePlacesAutocomplete class
this.placesService.setComponentRestrictions({ 'country': ['us', 'ca'] });
But no luck, any ideas?
Hi,
Thanks for the great library.
i was wondering if there is a way to programmatically clear the input field? I'm using renderInput to apply my styling, and I read that onChange should not be overriden.
Thanks again.
<GooglePlacesAutocomplete
placeholder='Address line 1*'
initialValue="test string"
minLength={2}
autoFocus={false}
returnKeyType={'default'}
fetchDetails={true}
onPress={this.props.onSelectAddress}
query={{
key: Constants.googlePlcesApiKey,
language: 'en',
}}
styles={{
container: {
border: 0,
marginBottom: 40,
paddingHorizontal: 8,
paddingTop: 8
},
textInputContainer: {
backgroundColor: 'transparent',
borderTopWidth: 0,
borderBottomColor: '#000',
paddingLeft: 0
},
textInput: {
backgroundColor: 'transparent',
marginLeft: 0
},
powered: {
display: 'none'
},
poweredContainer: {
display: 'none'
},
listView: {
width: Dimensions.get('window').width - 40
}
}}
/>
Thank you for the excellent library.
I want to be able to run a function when the user hits the Enter key while searching for something.
However, according to the documentation:
Important: do not override the value and onChange properties of the input, neither the onBlur or onKeyDown.
I am referring to the renderInput
prop of the GooglePlacesAutocomplete
component.
To get around this I tried placing the input field inside a <form>
with an onSubmit
prop but that didn't fire.
So I went against the documentation and wrote an onKeyDown
handler which check if the event
's keyCode
is 13 (Enter).
This seemed to work perfectly fine. However as I went against the documentation I fear this might break some key functionality somewhere.
Is it safe to target the Enter key in an onKeyDown
handler? Or should I approach this in a different way?
Unable to force user to select from autocomplete suggestion only. Since there is no freedom to modify the onBlur method, I am unable to implement the functionality.
I have the following code in my app and it shows the suggestions. But once I click any of these suggested locations, nothing happens at all. If I remove this renderSuggestions
, input field gets populated again.
<GooglePlacesAutocomplete
placeholder="Search City"
autocompletionRequest={autocompletionRequest}
renderSuggestions={(active, suggestions, onSelectSuggestion) => (
<div className="suggestions-container">
{suggestions.map(suggestion => (
<div className="suggestion" key={suggestion.id}>
{suggestion.description
.split(', ')
.slice(0, -1)
.join(', ')}
</div>
))}
</div>
)}
/>```
react should not be a dependency, but a peerDependency.
You should add it as devDependency as well for development
I want to achieve the following effect with your library:
`
const autocomplete = new google.maps.places.Autocomplete(
document.getElementById('autocomplete'),
options,
);
const mapUrl = autocomplete.getPlace().url;
`
How can I get the google maps url?
Hello, I just installed the component and used the basic demo example.
<GooglePlacesAutocomplete apiKey={API_KEY} onSelect={console.log} />
I got this
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
in GooglePlacesAutocomplete (created by PersonalInfoLocation)
in div (created by PersonalInfoLocation)
in PersonalInfoLocation (created by Context.Consumer)
in Route (created by Onboarding)```
Anyone knows why?
i have placed placeholder as the current address, when i move the marker, the placeholder's value change accordingly, but if i use the autocomplete box, the value of the search box wont change unless i type in a new input.
Works fine in production, but is throwing an error in my builds.
> Build error occurred ReferenceError: regeneratorRuntime is not defined at /tmp/build_36f04826_/node_modules/react-google-places-autocomplete/dist/react-google-places-autocomplete.cjs.prod.js:317:48 at /tmp/build_36f04826_/node_modules/react-google-places-autocomplete/dist/react-google-places-autocomplete.cjs.prod.js:346:4 at Object.<anonymous> (/tmp/build_36f04826_/node_modules/react-google-places-autocomplete/dist/react-google-places-autocomplete.cjs.prod.js:382:2) at Module._compile (internal/modules/cjs/loader.js:1138:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10) at Module.load (internal/modules/cjs/loader.js:986:32) at Function.Module._load (internal/modules/cjs/loader.js:879:14) at Module.require (internal/modules/cjs/loader.js:1026:19) at require (internal/modules/cjs/helpers.js:72:18) at Object.<anonymous> (/tmp/build_36f04826_/node_modules/react-google-places-autocomplete/dist/react-google-places-autocomplete.cjs.js:4:20) at Module._compile (internal/modules/cjs/loader.js:1138:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10) at Module.load (internal/modules/cjs/loader.js:986:32) at Function.Module._load (internal/modules/cjs/loader.js:879:14) at Module.require (internal/modules/cjs/loader.js:1026:19) at require (internal/modules/cjs/helpers.js:72:18)
The initial value and the value from the select. is not the same type.
The value that gets selected has all the the adresses values, and puts the description in the input.
But if I want to already choose a adress in the initial value , I have to use a string value.
Which means that in a CRUD application , I would not be able to open a update window and leave the adress as is. I'll have to choose a new value for me to hold all the adresses value(adress_id, description and so on)
Hi
I wonder if you can add prop for language restriction so I can use like:
https://maps.googleapis.com/maps/api/js?key=${googleApiKey}&libraries=places&language=${language}
componentWillReceiveProps will be deprecated in React 17.0, and must be renamed to UNSAFE_componentWillReceiveProps.
I tried to make a pull request but couldn't figure out how :( (im noob). It's a quick change, just change line 57 to UNSAFE_componentWillReceiveProps
I think a good addition to the library would be a "X" button to clear the field, and that one should trigger a provided callback (if provided).
When trying to search using a zipcode, I'm not getting any results when I'm using the autoCompletionRequest.
Example:
autocompletionRequest={{
componentRestrictions: {
country: ['US'],
},
types: ['postal_code'],
}}
Is this being used properly or can you not use the types like this? I can't use types: ['(region)']
, it's too restrictive so I was hoping to use an array of a bunch of items. Something like ['postal_code', 'locality', 'administrative_area_level_1', 'neighborhood']
but I can't get a single option to work.
version: 2.3.0
let LatLng = {lat: 0, lng: 0}
<GooglePlacesAutocomplete
apiKey='xxxx'
onSelect={console.log}
withSessionToken={true}
debounce={300}
autocompletionRequest={
location: LatLng
}
/>
I am getting this error
Overload 1 of 2, '(props: Readonly): GooglePlacesAutocomplete', gave the following error.
Type 'Location' has no properties in common with type 'autocompletionRequestType'.
Overload 2 of 2, '(props: GooglePlacesAutocompleteProps, context?: any): GooglePlacesAutocomplete', gave the following error.
Type 'Location' has no properties in common with type 'autocompletionRequestType'.ts(2769)
The below code produces the console error Warning: Failed prop type: Invalid prop 'bounds' supplied to 'GooglePlacesAutocomplete'. Validation failed.
<GooglePlacesAutocomplete
placeholder='Address Search'
renderInput={(props) => (
<SearchWrapper className="custom-wrapper">
<PlacesSearch
// Custom properties
{...props}
/>
</SearchWrapper>
)}
renderSuggestions={(active, suggestions, onSelectSuggestion) => (
<ResultsContainer className="suggestions-container">
{
suggestions.map((suggestion) => (
<Results
className="suggestion"
key={suggestion.id}
onClick={event => onSelectSuggestion(suggestion, event)}>
{suggestion.description}
</Results>
))
}
</ResultsContainer>
)}
autocompletionRequest={
{
bounds: [
{ lat: -46.243365, lng: 169.739438 },
{ lat: -45.909430, lng: 170.165843 }
],
componentRestrictions: {
country: 'nz',
}
}
}
onSelect={console.log}
/>
Note styled components are used in place of div
and input
elements. It renders and work as intended just getting the bounds error.
While using GootPlacesAutocomplete with react 16.9, I get the following warning:
Warning: componentWillReceiveProps has been renamed, and is not recommended for use. See https://fb.me/react-async-component-lifecycle-hooks for details.
* Move data fetching code or side effects to componentDidUpdate.
* If you're updating state whenever props change, refactor your code to use memoization techniques or move it to static getDerivedStateFromProps. Learn more at: https://fb.me/react-derived-state
* Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress this warning in non-strict mode. In React 17.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run `npx react-codemod rename-unsafe-lifecycles` in your project source folder.
Please update the following components: GooglePlacesAutocomplete
Versions:
Getting a Warning: Each child in a list should have a unique "key" prop.
error when using this library inside a React Typescript application.
To reproduce:
I probably could fix it and make a PR, but I thought I should submit the issue first.
Hi, I'm trying a quite basic setup:
import React from 'react';
import GooglePlacesAutocomplete from 'react-google-places-autocomplete';
import 'react-google-places-autocomplete/dist/index.min.css';
const Component = () => (
<div>
<GooglePlacesAutocomplete
apiKey="MY_API_KEY"
onSelect={console.log}
/>
</div>
);
export default Component;
The api key is fresh and unrestricted, places API is enabled.
Yet after typing in the input, a dropdown list comes up with a 'Loading...' item, and noting more happens.
Any suggestion on what could go wrong here, or how can I debug & check the response from the Places API?
Would it be possible for you to add an onInputValueChange that is called in the internal changeValue function so that the current input value is available easily outside of the component or would you accept a pull request if it were submitted.
changeValue = (value) => {
this.setState({ value });
if (value.length > 0) {
this.fetchSuggestions(value);
} else {
this.setState({ suggestions: [] });
}
if (onInputValueChange)
onInputValueChange(value);
}
Hi I just installed you lib and got this error
hot-dev-client.js:131 Uncaught (in promise) /node_modules/react-google-places-autocomplete/dist/GooglePlacesAutocomplete/index.css:1
(function (exports, require, module, __filename, __dirname) { .google-places-autocomplete {
^SyntaxError: Unexpected token .
at new Script (vm.js:80:7)
at createScript (vm.js:274:10)
at Object.runInThisContext (vm.js:326:10)
at Module._compile (internal/modules/cjs/loader.js:664:28)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
at Function.Module._load (internal/modules/cjs/loader.js:531:3)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:22:18)
at Object. (/Users/alexanderberdichevsky/Desktop/Dev/floki/node_modules/react-google-places-autocomplete/dist/GooglePlacesAutocomplete/index.js:29:1)
at Module._compile (internal/modules/cjs/loader.js:701:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
at Function.Module._load (internal/modules/cjs/loader.js:531:3)
I've attempted to have two of these autocomplete components and it works, however i am warned since it utilizes the same id twice:
[DOM] Found 2 elements with non-unique id #google-places-autocomplete-input: (More info: https://goo.gl/9p2vKq)
script for google API has been loaded in inde.html, suggestions didn't load, tried to use the APIKey props, still not loaded. weird. no referrer not allowed error on console. Maybe ive used it wrong?
Buenas! Tengo una consulta, en la propiedad renderInput el componente claramente espera un objeto del tipo .
¿Se podría mejorar para que espere algun otro objeto o por ejemplo un TextField de material?
Gracias!
Steps to reproduce:
<GooglePlacesAutocomplete />
component with apiKey
prop defined.Expected behavior:
Current behavior:
<GooglePlacesAutocomplete />
instance injects the google places script, throwing warnings in the console and effectively stops working (stuck at Loading...
).Keep up the good work.
I'm trying to restrict results by type, but it doesn't work. Any help ? Thanks.
Here's my code:
<GooglePlacesAutocomplete
placeholder={'Enter Area'}
autocompletionRequest = {{
types: ["cities"]
}}
debounce={500}
/>
Not sure why but it seems that you are missing an if statement in the initializeService function.
index.js (line 117 -143)
key: 'initializeService',
value: function initializeService() {
var _this2 = this;
if (!window.google) {
console.error('[react-google-places-autocomplete]: Google script not loaded');
setTimeout(function () {
_this2.initalizeService();
}, 1000);
return;
}
if (!window.google.maps.places) {
console.error('[react-google-places-autocomplete]: Google maps places script not loaded');
setTimeout(function () {
_this2.initializeService();
}, 1000);
return;
}
this.placesService = new window.google.maps.places.AutocompleteService();
this.setState({
placesServiceStatus: window.google.maps.places.PlacesServiceStatus.OK
});
}
Adding in
if (!window.google.maps) {
console.error('[react-google-places-autocomplete]: Google maps places script not loaded');
setTimeout(function () {
_this2.initializeService();
}, 1000);
return;
}
fixed the error. Not sure if it's an oversight on my part or the module.
Would be great if a TypeScript definition would be provided for easier usage of the component.
According to Dev Docs from Google, you must specify a 'sessionToken' for every suggestion call. When an address is selected, the sessionToken
is expired and you are charged for the suggestion.
Is there any way to create a token like so:
const sessionToken = new.google.maps.places.AutocompleteSessionToken();
and pass it to some props of <GooglePlacesAutocomplete>
?
I find myself needing to pass a name through to the underlying input that gets created, but it looks like this is currently not possible ...was this by design? I can do the PR if not
Thanks!
Joel
Hi everyone:
I need to know whats the right way to use onSelect
with Typescript cause I'm receiving a warning when I use it. This is my code:
handleSelect = (addressSelected:any):void => {
geocodeByPlaceId(addressSelected.place_id)
.then(results => results[0])
.then(latLng => console.log('Success', latLng))
.catch(error => console.error('Error', error));
};
componentDidCatch(error: Error, errorInfo: React.ErrorInfo): void {
console.log(
error: ${error}, errorInfo: ${errorInfo});
}
searchOptions = {
componentRestrictions: { country: 'us' },
};
render(): React.ReactElement {
return (
<GooglePlacesAutocomplete
autocompletionRequest={this.searchOptions}
onSelect={this.handleSelect}
initialValue={this.props.initialValue}
/>
);
}
This is the warning I'm receiving :
The expected type comes from property 'onSelect' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<GooglePlacesAutocomplete> & Readonly<GooglePlacesAutocompleteProps> & Readonly<...>
Thanks beforehand 👍
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.