Main site

Sample codes > Using distance

Using distance

As with any LLM AI model outputs, always verify the generated code for accuracy before deploying it live.

For the sample prompts here, your might get different responses since AI models have random elements.

AI Prompt:

I'd like a shipping rate calculator that calculates the distance in km between the origin and destination addresses using Google Distance Matrix API (in driving mode) and the resulting distance in km is multiplied by 0.02 cents for shipping cost.
The codes implement the Google Distance Matrix distance calculator. The API access key will be provided as part of the environment variable object.
If the total items price is more than $500, provide 5% discount from the shipping cost.
The maximum delivery date is 8 days from now, and the minimum delivery date is 5 days from now.

AI Output:

export async function calculateShippingRates(DATA, env) {
    try {
        //This assumed you have saved the Google api key in the secret variable "googleApiKey" in the settings page
        const googleApiKey = env.googleApiKey;
        const origin = `${DATA.origin.address1}, ${DATA.origin.city}, ${DATA.origin.province}, ${DATA.origin.postal_code}, ${DATA.origin.country}`;
        const destination = `${DATA.destination.address1}, ${DATA.destination.city}, ${DATA.destination.province}, ${DATA.destination.postal_code}, ${DATA.destination.country}`;
        
        // Construct the Google Distance Matrix API URL
        const apiUrl = `https://maps.googleapis.com/maps/api/distancematrix/json?origins=${encodeURIComponent(origin)}&destinations=${encodeURIComponent(destination)}&mode=driving&key=${googleApiKey}`;

        // Fetch the distance data from Google Distance Matrix API
        const response = await fetch(apiUrl);
        const data = await response.json();

        if (data.status !== 'OK') {
            throw new Error('Error fetching distance data from Google API');
        }

        const distanceInMeters = data.rows[0].elements[0].distance.value;
        const distanceInKm = distanceInMeters / 1000;
        
        // Calculate shipping cost: distance in km * 0.02 cents
        let shippingCost = distanceInKm * 0.02;

        // Calculate the total items price in dollars
        const totalItemsPrice = DATA.items.reduce((sum, item) => sum + (item.price * item.quantity), 0) / 100;

        // Apply discount if total items price is more than $500
        if (totalItemsPrice > 500) {
            shippingCost *= 0.95; // 5% discount
        }

        // Calculate delivery dates
        const currentDate = new Date();
        const minDeliveryDate = new Date(currentDate.getTime() + (5 * 24 * 60 * 60 * 1000)); // 5 days from now
        const maxDeliveryDate = new Date(currentDate.getTime() + (8 * 24 * 60 * 60 * 1000)); // 8 days from now

        // Prepare shipping rate
        const rates = [{
            service_name: "Standard Shipping",
            service_code: "STD",
            total_price: (shippingCost * 100).toFixed(0), // Convert to cents
            description: "Distance-based Shipping Rate",
            currency: DATA.currency,
            min_delivery_date: minDeliveryDate.toISOString().split('T')[0],
            max_delivery_date: maxDeliveryDate.toISOString().split('T')[0]
        }];

        return { rates };
    } catch (error) {
        // Return error message in case of exceptions
        return { 
            rates: [{
                service_name: "Error",
                service_code: "ERR",
                total_price: null,
                description: error.message,
                currency: DATA.currency,
                min_delivery_date: "",
                max_delivery_date: ""
            }]
        };
    }
}