reactjs React JS google map在搜索中选择新位置时不刷新

ppcbkaq5  于 2023-06-22  发布在  React
关注(0)|答案(2)|浏览(91)

我最近在我的React Google Maps应用程序中添加了一个搜索栏,但是在从搜索栏中选择一个值时,Map不会重新渲染。我尝试在GoogleMap组件上设置一个键,但它不起作用。下面是我的应用程序代码:

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;
omqzjyyz

omqzjyyz1#

我没有更新中心位置。在设置了选定的lat/lng值后,它开始工作。

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

1qczuiv02#

首先,key不是必需的,它也不会工作,因为组件似乎没有接收到prop。
https://github.com/JustFly1984/react-google-maps-api/blob/develop/packages/react-google-maps-api/src/GoogleMap.tsx
但它似乎接收到一个可能有用的option prop,并且该组件内部有一个钩子,它对该prop做出React,触发useEffect,并可能开始重新渲染Map(请参阅上面的文件)。

相关问题