I have an ReactJS admin panel that monitors the location of all our company drivers and plots them as markers using @react-google-maps/api, I also want to provide live-location tracking. I was able to plot the markers but when I did a simulation for the live tracking, the CPU usage spiked up and made the map laggy.
This is how I plotted the markers
//DashboardMap.jsx
import { GoogleMap } from "@react-google-maps/api";
import Markers from "./Markers";
const DashboardMap = () => {
return (
<GoogleMap {...MAP_CONFIG}>
<Markers />
</GoogleMap>
);
};
//Markers.jsx
import { useSelector} from "react-redux";
const Markers = () => {
const {drivers} = useSelector((state) => state.drivers);
return (
<React.Fragment>
{drivers.map((driver, index) => <Marker {...driver.marker} //marker config />}
</React.Fragment>
);
};
To simulate the live-location tracking I created an interval that updates the marker position every second
const simulateTracking = () => {
setInterval(() => {
drivers.forEach(driver => {
dispatch({type: "SIMULATE_LIVE_TRACKING",
payload: {
driverId: driver.id,
newPosition: { lat: driver.position.lat + .001,
lng: driver.position.lng + .001 }
}
})
})
}, 1000);
//reducer
case "SIMULATE_LIVE_TRACKING":
const driver = _.remove(state.drivers, (item) => item.id === action.payload.driverId)[0];
driver.marker.position = action.payload.newPosition;
return { ...state, list: [...state.drivers, driver ] };
This is currently working but the thing is the CPU usage spiked up to 20% when the number of drivers was 15, and we currently have hundreds of them. My guess is because Markers.jsx re-renders every time the a driver's position changes but I have no idea how to prevent that.