i have implemented @react-google-maps/api. The map is working fine. Now i have add one more features in this map when a user changes the map bounds, my marker should also move. i tied this onBoundsChanged={handleBoundsChanged} but the problem is when i, set state it's going in infinite loop. i want same like this sample
import React, { useState, useCallback } from "react"; import { GoogleMap, Polygon, Circle, Marker, useJsApiLoader, } from "@react-google-maps/api"; const GOOGLE_API_KEY = "AIcyvu8"; function MyComponent() { const [centers, setCenters] = useState({ lat: 25.285417543870093, lng: 55.32845735549927, });
const onUnmount = useCallback(() => {
setMapRef(null);
}, []);
const [mapref, setMapRef] = React.useState(null);
const handleOnLoad = (map) => {
console.log("on load");
setMapRef(map);
};
const handleBoundsChanged = () => {
let center = {};
if (mapref) {
const newCenter = mapref.getCenter();
const lat = newCenter.lat();
const lng = newCenter.lng();
center = {
lat,
lng,
};
}
console.log({ center });
setCenters(center);
};
const { isLoaded } = useJsApiLoader({
id: "script-loader",
googleMapsApiKey: GOOGLE_API_KEY,
});
return (
<React.Fragment>
<div className={` ${showInput ? "map-height " : "relative "}`}>
{isLoaded ? (
<>
<GoogleMap
onBoundsChanged={handleBoundsChanged}
mapContainerClassName="App-map"
zoom={12}
center={centers}
onLoad={handleOnLoad}
onUnmount={onUnmount}
>
<Marker position={centers} />
</GoogleMap>
</>
) : (
<>Loading</>
)}
</div>
</React.Fragment>
);
}
export default React.memo(MyComponent);