skip to Main Content

I have recently added a search bar to my React Google Maps application, but upon selecting a value from the search bar, the map is not re-rendering. I have attempted to set a key on the Google Map component, but it is not working. Below is the code for my application:

I have recently added a search bar to my React Google Maps application, but upon selecting a value from the search bar, the map is not re-rendering. I have attempted to set a key on the Google Map component, but it is not working. Below is the code for my application:

import React, { useState} from 'react';
import { GoogleMap, LoadScript, Marker } from '@react-google-maps/api';
import usePlacesAutocomplete, { getGeocode, getLatLng } from 'use-places-autocomplete';

const MapContainer = () => {
  const [map, setMap] = useState(null);
  const [selectedPlace, setSelectedPlace] = useState(null);
  const [mapKey, setMapKey] = useState(new Date().getTime()); // Add mapKey state
  
  const containerStyle = {
    width: '100%',
    height: '400px',
  };

  const center = {
    lat: 37.7749,
    lng: -122.4194,
  };

  const onLoad = (map) => {
    setMap(map);
  };

  const handleSelect = async (address) => {
    try {
      const results = await getGeocode({ address });
      const { lat, lng } = await getLatLng(results[0]);
      setSelectedPlace({ address, lat, lng });
      setMapKey(new Date().getTime()); // Update mapKey state
    } catch (error) {
      console.error('Error:', error);
    }
  };

  const handleLoadScriptError = (error) => {
    console.error('Load Error:', error);
  };

  return (
    <LoadScript googleMapsApiKey="YOUR_API_KEY" libraries={['places']} onError={handleLoadScriptError}>
      <div style={containerStyle}>
        <GoogleMap key={mapKey} mapContainerStyle={containerStyle} center={center} zoom={10} onLoad={onLoad}>
          {selectedPlace && <Marker position={{ lat: selectedPlace.lat, lng: selectedPlace.lng }} />}
        </GoogleMap>
        <PlacesSearchBox onSelect={handleSelect} />
      </div>
    </LoadScript>
  );
};

const PlacesSearchBox = ({ onSelect }) => {
  const { ready, value, suggestions: { status, data }, setValue, clearSuggestions } = usePlacesAutocomplete();

  const handleInputChange = (e) => {
    setValue(e.target.value);
  };

  const handleSelect = (address) => {
    setValue(address, false);
    clearSuggestions();
    onSelect(address);
  };

  return (
    <div>
      <input type="text" value={value} onChange={handleInputChange} placeholder="Search..." />
      {status === 'OK' && (
        <ul>
          {data.map((suggestion, index) => (
            <li key={index} onClick={() => handleSelect(suggestion.description)}>
              {suggestion.description}
            </li>
          ))}
        </ul>
      )}
    </div>
  );
};

export default MapContainer;

2

Answers


  1. Chosen as BEST ANSWER

    I was not updating center position. After setting the selected values of lat/lng, its started to work.

     const center = {
        lat: 37.7749,
        lng: -122.4194,
      };
    

  2. hope you are doing well

    First of all key is not necessary and it is not going to work either because the component doesn’t seem to receive that prop

    https://github.com/JustFly1984/react-google-maps-api/blob/develop/packages/react-google-maps-api/src/GoogleMap.tsx

    but it seems to be that receives an option prop that could be useful and there is a hook inside of that component that reacts to that prop triggering an useEffect and probably start to re rendering the map (see the file above)

    Hope this help you to start solving the problem

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search