Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

reactjs - Google Maps JavaScript API library must be loaded - convert solution for react functional component

This solution (below) was given and fixes the problem of checking PlacesAutocomplete is loaded first before trying to load it and causing an error(within a class component), but I'm struggling to convert it to use in a functional component with react hooks as I can't access window.initMap.

state = {
  gmapsLoaded: false,
}

initMap = () => {
  this.setState({
    gmapsLoaded: true,
  })
}

componentDidMount () {
  window.initMap = this.initMap
  const gmapScriptEl = document.createElement(`script`)
  gmapScriptEl.src = `https://maps.googleapis.com/maps/api/js?key=SECRET_EATING&libraries=places&callback=initMap`
  document.querySelector(`body`).insertAdjacentElement(`beforeend`, gmapScriptEl)
}

render () {
  return (
    <div>
      {this.state.gmapsLoaded && (
        <PlacesAutocomplete />
      )}
    </div>
  )
}

was trying:

const [gmapsLoaded,setgmapsLoaded ] = useState(false)



initMap = () => {
    
      setgmapsLoaded(true)

  }


  useEffect(() => {
    window.initMap = this.initMap
  const gmapScriptEl = document.createElement(`script`)
  gmapScriptEl.src = "https://maps.googleapis.com/maps/api/js?key=AIzaSyAmlRtE1Ggrzz-iSUAWGIcm0mmi7GXbKtI&callback=initMap"
  document.querySelector(`body`).insertAdjacentElement(`beforeend`, gmapScriptEl)
  });

but to no avail

question from:https://stackoverflow.com/questions/65643802/google-maps-javascript-api-library-must-be-loaded-convert-solution-for-react-f

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I also tried this though it doesn't work, it solves it from crashing though it won't load the suggestions on the screen found inside PlacesAutoComplete and just keeps saying "Loading..."

 import React, { useContext, useState , useEffect} from "react";

const initMap = () => {
    
      setgmapsLoaded(true)

  }


  useEffect(() => {

    if (gmapsLoaded === false) {
    window.initMap = initMap
  const gmapScriptEl = document.createElement(`script`)
  gmapScriptEl.src = "https://maps.googleapis.com/maps/api/js?key=AIzaSyAmlRtE1Ggrzz-iSUAWGIcm0mmi7GXbKtI&callback=initMap"
  document.querySelector(`body`).insertAdjacentElement(`beforeend`, gmapScriptEl)
    }
  });



    {gmapsLoaded && (
    <PlacesAutocomplete
        value={address}
        onChange={setAddress}
        onSelect={handleSelect}
      >
        {({ getInputProps, suggestions, getSuggestionItemProps, loading }) => (
          <div>

<p> latitude: {coordinates.lat}</p>
<p> longitude: {coordinates.lng}</p>
<p> Address: {address}</p>


            <input
              {...getInputProps({
                placeholder: 'Search Places ...',
                className: 'location-search-input',
              })}
            />
            <div className="autocomplete-dropdown-container">
              {loading && <div>Loading...</div>}
              {suggestions.map(suggestion => {
                const className = suggestion.active
                  ? 'suggestion-item--active'
                  : 'suggestion-item';
                // inline style for demonstration purpose
                const style = suggestion.active
                  ? { backgroundColor: '#fafafa', cursor: 'pointer' }
                  : { backgroundColor: '#ffffff', cursor: 'pointer' };
                return (
                  <div
                    {...getSuggestionItemProps(suggestion, {
                      className,
                      style,
                    })}
                  >
                    <span>{suggestion.description}</span>
                  </div>
                );
              })}
            </div>
          </div>
        )}
      </PlacesAutocomplete>
    )
            }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...