How to apply Google Distance Matrix Service efficiently in React Redux?

260 views Asked by At

I'm fetching list of orders containing delivery vehicle's current location and order's destination and storing list in Redux Store.

Currently I've implement distance matrix service in a component and executing it in App.js file and passing each order one by one and updating orders using callback.

Is there any efficient approach?

Mapping orders to distance matrix component which is than being rendered in App.js:

distanceMatrix = this.props.orders.map((order, index) => {
    return (
        <DistanceMatrix
            key={index}
            order={order}
            orderIndex={index}
            callbackMethod={this.props.orderDistanceUpdate} />
    );
});

And here is the distance matrix component:

const DistanceMatrix = (props) => {

    return (
        <LoadScript
            googleMapsApiKey = {process.env.REACT_APP_GOOGLE_KEY} >
            <DistanceMatrixService
                options={{
                        destinations: [{lat: +props.order.vehicle_lat, lng: +props.order.vehicle_lon}],
                        origins: [{lng: +props.order.order_lon, lat: +props.order.order_lat}],
                        travelMode: "DRIVING",
                        }}
                callback = {(response, status) => {
                    const modResponse = {
                        planned_arrival: formatRelative(Date.parse(props.order.planned_arrival), new Date()),
                        estimated_arrival: formatRelative(addSeconds(new Date(), response.rows[0].elements[0].distance.value), new Date()),
                        estimated_distance: (response.rows[0].elements[0].distance.value / 1000).toFixed(1) + " KM",
                        destination_addresses: response.destinationAddresses[0],
                        origin_addresses: response.originAddresses[0],
                    };
                    return props.callbackMethod(props.orderIndex, props.order.order_id, modResponse);
                }}
                />
        </LoadScript>
    );
};
0

There are 0 answers