在反應中將更改標記陣列應用于谷歌地圖我的反應應用程式中有一個谷歌地圖,它允許顯示一個標記在地圖上移動(因為緯度每隔幾秒就會改變一次)
但是,如果我有一個標記陣列(使用具有相應緯度/經度的新標記不斷更新),有沒有辦法遍歷這些標記并將它們添加到地圖中。它需要繼續檢查它們沒有改變位置,或者新標記沒有出現在陣列中,或者從陣列中洗掉。本質上,它看起來像這樣:
const Map = ({ location, zoomLevel, markers }) => {
for(let marker of markers)
{
const [marker.markerLatVal, marker.setMarkerLatVal] =
useState(marker.markerLat)
}
useEffect(() => {
const interval = setInterval(() => {
changeMarkerLatitude();
}, 2000);
return () => clearInterval(interval);
}, []);
const changeMarkerLatitude = () => {
for(let marker of markers)
{
marker.setMarkerLatVal(prev => prev 50);
}
};
return (
<div className='map'>
<div className='google-map'>
<GoogleMapReact
for(let marker of this.markers)
{
<MyGreatPlace lat={marker.markerLat}
lng={marker.markerLong} text=
{marker.markerText} />
}
</GoogleMapReact>
</div>
</div>
);
}
Is this possible?
React SetState array not updating
I have a Google map in my react application which allows users to sign up (by entering their name). It then gets their location every 1 second and sends it to all the other users currently using the app.
I am trying to plot the users on a map using google-map-react. This should update every time a user is added, or their location changes and reflect this with their marker moving on the map.
It is console logging the usersArray correctly, but users is not being updated, am I doing setState wrong?
const Map = ({ location, zoomLevel }) => {
const { name } = useParams();
const [messages, setMessages] = useState([]);
const ws = useRef();
let [latitude, setLatitude] = useState('');
let [longitude, setLongitude] = useState('');
const [isConnectionOpen, setConnectionOpen] = useState(false);
const [users, setUsers] = useState([]);
useEffect(() => {
ws.current = new WebSocket('ws://localhost:8081');
//new user has connected
ws.current.onopen = () => {
setConnectionOpen(true);
};
//sending message to other users
ws.current.onmessage = (ev) => {
const message = JSON.parse(ev.data);
//update users function
handleAddNewUser(message);
setMessages((_messages) => [..._messages, message]);
};
return () => {};
}, []);
//checks if a message has been received my a new user. If existing user - update location
function handleAddNewUser(message) {
let usersArray = [];
let newUser = true;
if (users.length == 0) {
usersArray.push(message);
} else {
for (let user of users) {
if (message.sender == user.sender) {
newUser = false;
user = message;
}
}
if (newUser == true) {
usersArray.push(message);
}
}
console.log(usersArray);
// update the state to the updatedUsers
setUsers(usersArray);
console.log(users);
}
//triggers the send function every 1 second
useEffect(() => {
const interval = setInterval(() => {
send();
}, 1000);
return () => clearInterval(interval);
}, []);
//sends the users location as a message to all the other users
const send = () => {
if (navigator.geolocation) {
navigator.geolocation.watchPosition(function (position) {
latitude = position.coords.latitude.toString();
longitude = position.coords.longitude.toString();
ws.current.send(JSON.stringify({ sender: name, latitude: latitude, longitude: longitude }));
setLatitude('');
setLongitude('');
});
}
};
return (
<div className='map'>
<div className='google-map'>
<GoogleMapReact
bootstrapURLKeys={{ key: 'keyID' }}
defaultCenter={location}
defaultZoom={zoomLevel}>
users.map(marker => {
<MyGreatPlace lat={marker.markerLat}
lng={marker.markerLong} text=
{marker.markerText} />
})lng={users[0].longitude} text={users[0].sender} />) */}
</GoogleMapReact>
</div>
</div>
);
};
export default Map;
Also, when plotting the users on the map, i am getting this error: Unexpected token. Did you mean {'>'} or >?
1
Source
Edit
Rollback
Link
asked 13 hours ago
Pippa97
75
6
Apply changing markers array to Google map in react
I have a Google map in my react application which allows one single marker to be shown moving around the map (as the latitude is being changed every few seconds)
However if i had a markers array (which keeps being updated with new markers with corresponding latitude/longitude), is there a way to loop through these markers and add them to the map. It would need to keep checking they haven't changed location, or new markers haven't appeared in the array, or been deleted from the array. Essentially, it would look something like this:
const Map = ({ location, zoomLevel, markers }) => {
for(let marker of markers)
{
const [marker.markerLatVal, marker.setMarkerLatVal] =
useState(marker.markerLat)
}
useEffect(() => {
const interval = setInterval(() => {
changeMarkerLatitude();
}, 2000);
return () => clearInterval(interval);
}, []);
const changeMarkerLatitude = () => {
for(let marker of markers)
{
marker.setMarkerLatVal(prev => prev 50);
}
};
return (
<div className='map'>
<div className='google-map'>
<GoogleMapReact
for(let marker of this.markers)
{
<MyGreatPlace lat={marker.markerLat}
lng={marker.markerLong} text=
{marker.markerText} />
}
</GoogleMapReact>
</div>
</div>
);
}
這可能嗎?
uj5u.com熱心網友回復:
由于這是非作業代碼,我無法真正除錯它,但這應該可以幫助您完成 99.9999% 的作業。
const Map = ({ location, zoomLevel, markers: markersList }) => {
// We set a state array with the markers (renaming markersList in props to avoid collisions)
const [markers, setMarkers] = useState(markersList)
useEffect(() => {
const interval = setInterval(() => {
changeMarkerLatitude();
}, 2000);
return () => clearInterval(interval);
}, []);
const changeMarkerLatitude = () => {
// map over each marker, keep original values by spreading old state, only modify what we want to change
markers.map(marker => {
setMarkers( prev => {
...prev,
marker.latitude: marker.latitude = 50 //whatever you want here
}
}
};
return (
<div className='map'>
<div className='google-map'>
<GoogleMapReact
markers.map(marker => {
<MyGreatPlace lat={marker.markerLat}
lng={marker.markerLong} text=
{marker.markerText} />
})
</GoogleMapReact>
</div>
</div>
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/429739.html
標籤:javascript html 反应 谷歌地图
上一篇:將值添加到LiveChartc#
下一篇:顫動||谷歌地圖的替代包
