@@ -9,6 +9,7 @@ export default class ReactGoogleAutocomplete extends React.Component {
99 bounds : PropTypes . object ,
1010 fields : PropTypes . array ,
1111 inputAutocompleteValue : PropTypes . string ,
12+ apiKey : PropTypes . string
1213 } ;
1314
1415 constructor ( props ) {
@@ -22,6 +23,7 @@ export default class ReactGoogleAutocomplete extends React.Component {
2223 types = [ '(cities)' ] ,
2324 componentRestrictions,
2425 bounds,
26+ apiKey,
2527 fields = [
2628 'address_components' ,
2729 'geometry.location' ,
@@ -41,15 +43,23 @@ export default class ReactGoogleAutocomplete extends React.Component {
4143
4244 this . disableAutofill ( ) ;
4345
44- this . autocomplete = new google . maps . places . Autocomplete (
45- this . refs . input ,
46- config
47- ) ;
46+ const handleAutoComplete = ( ) => {
47+ this . autocomplete = new google . maps . places . Autocomplete (
48+ this . refs . input ,
49+ config
50+ ) ;
4851
49- this . event = this . autocomplete . addListener (
50- 'place_changed' ,
51- this . onSelected . bind ( this )
52- ) ;
52+ this . event = this . autocomplete . addListener (
53+ 'place_changed' ,
54+ this . onSelected . bind ( this )
55+ ) ;
56+ } ;
57+
58+ if ( apiKey ) {
59+ this . handleLoadScript ( ) . then ( ( ) => handleAutoComplete ( ) ) ;
60+ } else {
61+ handleAutoComplete ( ) ;
62+ }
5363 }
5464
5565 disableAutofill ( ) {
@@ -78,12 +88,34 @@ export default class ReactGoogleAutocomplete extends React.Component {
7888 }
7989 }
8090
91+ handleLoadScript = ( ) => {
92+ const googleMapsScriptUrl = `https://maps.googleapis.com/maps/api/js?key=${ this . props . apiKey } &libraries=places` ;
93+
94+ // Check if script exists already
95+ if (
96+ document . querySelectorAll ( `script[src="${ googleMapsScriptUrl } "]` ) . length >
97+ 0
98+ ) {
99+ return Promise . resolve ( ) ;
100+ }
101+
102+ this . googleMapsScript = document . createElement ( 'script' ) ;
103+ this . googleMapsScript . src = googleMapsScriptUrl ;
104+
105+ document . body . appendChild ( this . googleMapsScript ) ;
106+
107+ return new Promise ( ( resolve ) => {
108+ this . googleMapsScript . addEventListener ( 'load' , ( ) => resolve ( ) ) ;
109+ } ) ;
110+ } ;
111+
81112 render ( ) {
82113 const {
83114 onPlaceSelected,
84115 types,
85116 componentRestrictions,
86117 bounds,
118+ apiKey,
87119 ...rest
88120 } = this . props ;
89121
0 commit comments