Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
v:2.0:shipping:custom_code:google_maps_distance [2020/03/24 01:07] – [Build custom shipping code] adamv:2.0:shipping:custom_code:google_maps_distance [2020/12/09 20:44] (current) – [Build custom shipping code] adam
Line 13: Line 13:
   - On the next panel you'll be prompted to either select an existing project or create a new one. Make a selection there and continue.   - On the next panel you'll be prompted to either select an existing project or create a new one. Make a selection there and continue.
   - If prompted to create a billing account, complete that. Google has a $200 free allowance per month, but requires you assign a billing account in case you go over that allowance.   - If prompted to create a billing account, complete that. Google has a $200 free allowance per month, but requires you assign a billing account in case you go over that allowance.
-  - Once you've created your new project, you'll be redirected to the Google Maps Platform portal.+  - Once you've created your new project, you'll be redirected to the Google Maps Platform portal for your project. 
 +  - On the overview page for your project, review the "Enabled APIs" panel, and confirm that the "Distance Matrix API" is displayed there. 
 +    - If not, click the "All Google Maps APIs" link at the top of the page next to the "Overview" title, and select "Enable API".  
 +    - This will redirect you to the API marketplace. Search for the "Distance Matrix API, and select and enable it for your account.
   - Select the hamburger menu in the top left, and select "APIs & Services" and "Credentials"   - Select the hamburger menu in the top left, and select "APIs & Services" and "Credentials"
   - Click "Create Credentials" on the Credentials page, and select "API Key".   - Click "Create Credentials" on the Credentials page, and select "API Key".
Line 26: Line 29:
   - If it's not already enabled, enable the "use custom code" option at the bottom of the page.   - If it's not already enabled, enable the "use custom code" option at the bottom of the page.
   - Copy and paste the following code into the code editor that appears:<code javascript>// Google Maps API key   - Copy and paste the following code into the code editor that appears:<code javascript>// Google Maps API key
-const google_maps_api_key = 'AIzaSyDh1MmbXXaVGW__4rzmhtyb1CchnEpm2K8';+const google_maps_api_key = '';
 // Shipping Origin Address // Shipping Origin Address
 const origin_address = 'My Address 1, City, STATE, Country, 12345'; const origin_address = 'My Address 1, City, STATE, Country, 12345';
 // Unit type (either 'metric' or 'imperial') // Unit type (either 'metric' or 'imperial')
 const unit_type = 'metric'; const unit_type = 'metric';
 +// Distance will be in metres in the response from Google Maps
 +// Set this to true to convert the value to kilometres/miles based on the unit type above
 +const convert_distance = true;
 +
  
 // Get address details // Get address details
Line 45: Line 52:
     }     }
 } }
 + 
 const customer_address = address1 + ', ' + city + ', ' + region + ', ' + country + ', ' + postal_code; const customer_address = address1 + ', ' + city + ', ' + region + ', ' + country + ', ' + postal_code;
 + 
 // Get address coordinates from Google Maps // Get address coordinates from Google Maps
-const maps_url = 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=' + origin_address + '&destinations=' + customer_address + '&units=' + unit_type + '&key=' + google_maps_api_key;+const maps_url = 'https://maps.googleapis.com/maps/api/distancematrix/json?origins='encodeURIComponent(origin_address+ '&destinations='encodeURIComponent(customer_address+ '&units=' + unit_type + '&key=' + google_maps_api_key;
 let distance = -1; let distance = -1;
 await request(maps_url, function (error, response, body) { await request(maps_url, function (error, response, body) {
     let payload = JSON.parse(body);     let payload = JSON.parse(body);
-    console.log(body); 
     if (response && response.statusCode == 200 && payload.status == 'OK' && payload.rows[0].elements[0].status == 'OK') {     if (response && response.statusCode == 200 && payload.status == 'OK' && payload.rows[0].elements[0].status == 'OK') {
         distance = payload.rows[0].elements[0].distance.value;         distance = payload.rows[0].elements[0].distance.value;
 +        if (convert_distance) {
 +            // Convert distance from metres to kilometres/miles based on unit_type if configured to
 +            distance = (unit_type == 'metric') ? distance/1000 : distance/1609.34;
 +        }
     }     }
 }); });
  
 +// Begin Custom Logic
 if (distance > -1) { if (distance > -1) {
     // Distance was calculated     // Distance was calculated
Line 70: Line 81:
   - Update the ''origin_address'' string just below that. Replace the placeholder address with the full origin address that you're wanting to calculate the distance from.   - Update the ''origin_address'' string just below that. Replace the placeholder address with the full origin address that you're wanting to calculate the distance from.
   - If you need Imperial measurements rather than Metric, update the ''unit_type'' string to be ''%%'imperial'%%'' instead.   - If you need Imperial measurements rather than Metric, update the ''unit_type'' string to be ''%%'imperial'%%'' instead.
-  - Next, you'll need to set the shipping rate and error that is displayed to customers. The snippet above sets a rate that is $5 plus 45¢ per mile/km, but you'll obviously want to customise that to show your own rates. Check out [[..:shipping:custom_code:|the documentation here on interacting with our rates]].\\ \\ Specifically you'll be editing this section:<code javascript>if (distance > -1) {+  - Google returns the distance value in metres in their API. The ''convert_distance'' variable allows you to set whether this should be converted to kilometres/miles (based on what you've set for ''unit_type''). Set to false to leave it in metres. 
 +  - Next, you'll need to set the shipping rate and error that is displayed to customers. The snippet above sets a rate that is $5 plus 45¢ per mile/km, but you'll obviously want to customise that to show your own rates. Check out [[..:custom_code:|the documentation here on interacting with our rates]].\\ \\ Specifically you'll be editing this section:<code javascript>//Begin Custom Logic 
 +if (distance > -1) {
     // Distance was calculated     // Distance was calculated
     let shipping = 5 + (0.45 * Math.ceil(distance));     let shipping = 5 + (0.45 * Math.ceil(distance));
Line 81: Line 94:
   - Wait 15-20 seconds and refresh the page to ensure the shipping code has saved (it's a separate system so takes a moment to initialize)   - Wait 15-20 seconds and refresh the page to ensure the shipping code has saved (it's a separate system so takes a moment to initialize)
   - If you haven't already, you'll also need to update any categories that will use this shipping rate code to have a delivery type of "Shipped using live shipping rates".   - If you haven't already, you'll also need to update any categories that will use this shipping rate code to have a delivery type of "Shipped using live shipping rates".
 +
 +==== Example: Delivery surcharge based on distance ====
 +
 +One other good use case for this integration is to charge a surcharge if a customer lives outside a specific range from your shipping point. Here's an example of what the custom logic for that could look like as part of the snippet above. This example charges a $20 flat fee, but adds $15 if the customer's address is greater than 35 miles/kilometres away, but also provides free shipping if the order is $150 or more:
 +
 +<code javascript>
 +if (shipment['total_item_price'] < 150) {
 +    let shipping = 20;
 +    if (distance > 35) {
 +        // Customers address is more than 35 miles away
 +        shipping += 15;
 +    }
 +    rates.add(10000, shipping, '', 'Standard Delivery');
 +} else {
 +    rates.add(10001, 0, '', 'Free Delivery');
 +}
 +</code>
 +
 +You'll still need to include the rest of the snippet as detailed above - but this replaces the custom logic at the bottom of the snippet.
  
 ===== Add custom template code ===== ===== Add custom template code =====
Line 111: Line 143:
  
 At this stage - you've completed all the configuration! You should now be able to add a product to your cart, proceed to the checkout, and enter shipping addresses that are inside and outside of your shippable zone to test it out. At this stage - you've completed all the configuration! You should now be able to add a product to your cart, proceed to the checkout, and enter shipping addresses that are inside and outside of your shippable zone to test it out.
 +
 +====Troubleshooting====
 +
 +To see what's returned in the API, you can use the following url. Fill in the values needed, then put the url directly in your address bar:
 +<code>https://maps.googleapis.com/maps/api/distancematrix/json?origins=YOUR_ORIGIN_ADDRESS&destinations=YOUR_DESTINATION_ADDRESS&units=metric&key=YOUR_API_KEY</code>
 +
 +Note that this will be the raw response - and so the distance value will be in metres. Depending on your configuration of the snippet above, the value you will be referencing as ''distance'' in the custom code may have been converted to kilometres or miles.

Site Tools