React JS谷歌地图在从搜索中选择新位置后未刷新。

huangapple go评论72阅读模式
英文:

React JS google map not refreshing upon selecting a new location from search

问题

我最近在我的React谷歌地图应用程序中添加了一个搜索栏,但在从搜索栏中选择一个值后,地图没有重新渲染。我尝试在谷歌地图组件上设置一个key,但它不起作用。以下是我的应用程序的代码:

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()); // 添加mapKey状态

  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()); // 更新mapKey状态
    } catch (error) {
      console.error('错误:', error);
    }
  };

  const handleLoadScriptError = (error) => {
    console.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="搜索..." />
      {status === 'OK' && (
        <ul>
          {data.map((suggestion, index) => (
            <li key={index} onClick={() => handleSelect(suggestion.description)}>
              {suggestion.description}
            </li>
          ))}
        </ul>
      )}
    </div>
  );
};

export default MapContainer;

请注意,此处提供的翻译只包括代码部分。如果您需要进一步的帮助或解释,请随时提问。

英文:

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 &#39;react&#39;;
import { GoogleMap, LoadScript, Marker } from &#39;@react-google-maps/api&#39;;
import usePlacesAutocomplete, { getGeocode, getLatLng } from &#39;use-places-autocomplete&#39;;

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

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

  const onLoad = (map) =&gt; {
    setMap(map);
  };

  const handleSelect = async (address) =&gt; {
    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(&#39;Error:&#39;, error);
    }
  };

  const handleLoadScriptError = (error) =&gt; {
    console.error(&#39;Load Error:&#39;, error);
  };

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

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

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

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

  return (
    &lt;div&gt;
      &lt;input type=&quot;text&quot; value={value} onChange={handleInputChange} placeholder=&quot;Search...&quot; /&gt;
      {status === &#39;OK&#39; &amp;&amp; (
        &lt;ul&gt;
          {data.map((suggestion, index) =&gt; (
            &lt;li key={index} onClick={() =&gt; handleSelect(suggestion.description)}&gt;
              {suggestion.description}
            &lt;/li&gt;
          ))}
        &lt;/ul&gt;
      )}
    &lt;/div&gt;
  );
};

export default MapContainer;

答案1

得分: 0

首先,key 不是必需的,而且它也不会起作用,因为该组件似乎不会接收该属性。

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

但似乎 <GoogleMap> 接收一个 option 属性,这可能会有用,并且该组件内部有一个钩子会对该属性做出反应,触发一个 useEffect,可能会开始重新渲染地图(请参见上述文件)。

英文:

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 <GoogleMap> 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-render the map (see the file above).

答案2

得分: 0

我没有更新中心位置。在设置了纬度和经度的选定值后,它开始工作。

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

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,
};

huangapple
  • 本文由 发表于 2023年6月16日 04:04:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76485169.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定