I work with the GoogleMaps
API, using React.js
.
Inside the GoogleMap
component:
I have a component called
UserLocationTimer
, which activatessetInterval
withinuseEffect
and samples the user's location every 2 seconds, centering the map accordingly. In addition, returns theUserLocation
component that displays the marker of the user's location on the map.In case the user drags the map, I catch the event
isDragged
, and return only theUserLocation
component that displays the marker of the user's location on the map.
It works fine, however, how would you optimize this code? Is there a more efficient way to catch the dragging event and stopping the timer interval from the parent, instead using conditional rendering?
<GoogleMap
. . .
onDrag={(map) => {
setIsDragged(true);
}}
onDragEnd={(map) => {
setIsDragged(true);
}}
>
. . .
{!isDragged && (
<UserLocationTimer
userLocation={userLocation}
setUserLocation={setUserLocation}
panTo={panTo}
></UserLocationTimer>
)}
{isDragged && (
<UserLocation userLocation={userLocation}></UserLocation>
)}
</GoogleMap>
export const UserLocationTimer = (props) => {
const [timer, setTimer] = useState(null);
useEffect(() => {
const interval = setInterval(() => {
setTimer(new Date());
locateMe();
}, 2000);
return () => clearInterval(interval);
}, []);
function locateMe() {
// locating using geolocation...
}
return (
<>
{timer && <UserLocation userLocation={props.userLocation}></UserLocation>}
</>
);
};
export const UserLocation = (props) => {
if (props.userLocation)
return (
<>
<Marker
position={{
lat: props.userLocation.lat,
lng: props.userLocation.lng,
}}
icon={{
url: userLocationIcon,
scaledSize: new window.google.maps.Size(30, 30),
origin: new window.google.maps.Point(0, 0),
anchor: new window.google.maps.Point(15, 15),
}}
/>
</>
);
else return null;
};