libraries={['places']} is not working, while implementing useAutocomplete from Package @vis.gl/react-google-maps

70 Views Asked by At

I was trying to implement useAutocomplete feature from @vis.gl/react-google-maps (It is used to show suggestion of places)

libraries={['places']} was added to <APIProvider> as instructed in documentation, But later on I start getting this issue

Google Maps Places library is missing. Please add the places library to the props of the <ApiProvider> component.

<APIProvider apiKey={GOOGLE_MAP_API} libraries={['places']} >

import { API_BASE_URL, GOOGLE_MAP_API } from '../../../constant/api';
import usePlacesAutocomplete, {
  getGeocode,
  getLatLng,
} from "use-places-autocomplete";
import {
  APIProvider,
  Map,
  AdvancedMarker,
  Pin,
  useAutocomplete,
  InfoWindow,
} from "@vis.gl/react-google-maps";


function BusStop() {
  
  const center = {
    lat: 9.2905715,
    lng: 76.6337262,
  };
  const [Point, setPoint] = useState(null)
  const [stopName, setstopName] = useState('')

  const handleRouteSubmit = async () => {
    if (!Point) {
      TError("Please choice stop")
    }
    if (stopName.length < 3) {
      TError("Enter a valid stop name")
    }
    const formData = {
      'stop_name': stopName,
      'lat': Point.lat,
      'lon': Point.lng
    }

    await axios.post(API_BASE_URL + '/bus/add', formData).then((res) => {
      TSuccess("Successfully added")

    }).catch((err) => { TError("Something went wrong! Please try again.") })
  }
  
  return (
    <>
      <form action="" method="post">
        <div className='p-10'>
          <div class="mb-4">
            <label class="block text-gray-700 text-sm font-bold mb-2" for="username">
              Stop name 
            </label>
            <input value={stopName} onChange={(e) => setstopName(e.target.value)} class="shadow appearance-none border rounded w-1/2 py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="username" type="text" />
          </div>
          <div>

          </div>

          <APIProvider apiKey={GOOGLE_MAP_API} libraries={['places']} >
          <label class="block text-gray-700 text-sm font-bold mb-2 mt-9" for="username">
              Stop Location
            </label>
            <div className='text-center mb-6'>

            // Calling AutoComplete 
            <AutoComplete setPoint={setPoint} />


            </div>
            <div className='w-100 h-80' >

              <Map zoom={16} center={Point?Point:center} mapId={'7eded6b9224bb80'} onClick={(e) => {
                console.log(e.detail.latLng.lat);
                setPoint({ lat: e.detail ? e.detail.latLng.lat : null, lng: e.detail ? e.detail.latLng.lng : null })
              }}>

                <AdvancedMarker position={Point} >

                </AdvancedMarker>
              </Map>
              <button onClick={handleRouteSubmit} class="mt-10 flex-shrink-0 bg-red-500 hover:bg-red-700 border-red-600 hover:border-red-900 text-sm border-4 text-white py-1 px-2 rounded" type="button">
                Sign Up
              </button>
            </div>
          </APIProvider>
        </div>

      </form>
    </>

  )
}

export default BusStop



const AutoComplete = ({setPoint}) => {
  const inputRef = useRef(null);
  const [inputValue, setInputValue] = useState('');
  useEffect(() => {
    handleSelect(inputValue)
  },[inputValue])



  const onPlaceChanged = place => {
    if (place) {
      setInputValue(place.formatted_address || place.name);
        }
    inputRef.current && inputRef.current.focus();
  };


  useAutocomplete({
    inputField: inputRef && inputRef.current,
    onPlaceChanged
  });

  const handleSelect = async (address) => {

    const results = await getGeocode({ address });
    const { lat, lng } = await getLatLng(results[0]);
    setPoint({ lat, lng });
  };

  const handleInputChange = event => {
    setInputValue(event.target.value);
  };

  return (
    <input ref={inputRef} value={inputValue} onChange={handleInputChange} />
  );
};

It worked, but

I tried to change APIProvider props like: removing libraries={['places']} change the places to place

so all those time suggestion was working when i type in input field

But the moment when i refresh the page suggestion again stop working.

0

There are 0 best solutions below