javascriptreactjsreact-google-maps

Autocomplete in react-google-autocomplete does not take me to the place on the map


This could also be a rendering issue but I am not sure. apiKey is correect.

I am expecting the user to be taken to the coordinates on the map.

I can see logged that my place has been selected but it does not take me to the location.

import { GoogleMap} from '@react-google-maps/api';
import Autocomplete from 'react-google-autocomplete';

const Autocomplete= () => {

  const [map, setMap] = useState(null);
const handlePlaceSelect = (place) => {
    console.log('Place selected:', place);
    if (!place.geometry) {
      window.alert("No details available for input: '" + place.name + "'");
      return;
    }

    if (map) {
      if (place.geometry.viewport) {
        map.fitBounds(place.geometry.viewport);
      } else {
        map.setCenter(place.geometry.location);
        map.setZoom(17); // Zoom in to an appropriate level when searching by place name
      }
    } else {
      console.error('Map is not yet initialized');
    }
  };
return(
 <GoogleMap
            mapContainerStyle={mapContainerStyle}
            zoom={11}
            center={center}
            options={{ styles: mapStyles, fullscreenControl: false }}
            onLoad={(map) => setMap(map)}
          >
            {map && (
              <Autocomplete
                apiKey=""
                onPlaceSelected={handlePlaceSelect}
                options={{
                }}
                style={{ width: '100%', position: 'absolute', zIndex: '100' }}
                placeholder="Search..."
              />
            )}
          </GoogleMap>
    )
    };

export default Autocomplete;


Solution

  • import { GoogleMap} from '@react-google-maps/api';
    import Autocomplete from 'react-google-autocomplete';
    
    const Autocomplete= () => {
    
    
    const [map, setMap] = useState(null);
    
    const [selectedLocation, setSelectedLocation] = useState({
        lat:"initial latitude"
        lng: "initial longitude"
      });
    
    const handlePlaceSelect = (place) => {
        if (!place.geometry) {
          window.alert("No details available for input: '" + place.name + "'");
          return;
        }
    
        if (map) {
          if (place.geometry.viewport) {
            map.fitBounds(place.geometry.viewport);
          } else {
            map.setCenter(place.geometry.location);
            map.setZoom(17);
          }
        } else {
          console.error('Map is not yet initialized');
        }
        setSelectedLocation(place.geometry.location);
      };
     return (
      <GoogleMap
              center={selectedLocation}
              onLoad={(map) => setMap(map)}
            >
              {map && (
                 <Autocomplete
                  apiKey=["Your Api Key"]
                  onPlaceSelected={handlePlaceSelect} 
                />
      </GoogleMap>
        )
    }