英文:
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 '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;
答案1
得分: 0
首先,key
不是必需的,而且它也不会起作用,因为该组件似乎不会接收该属性。
但似乎 <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.
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,
};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论