How To Embed a Shipping Location Map on the BigCommerce Order Confirmation Page

Karen White
BigCommerce Developer Blog
8 min readJun 17, 2019

Have you ever placed an order online and immediately questioned whether you entered the right shipping address? (raises hand)

Adding a map to the order confirmation page gives shoppers confidence that their order has been placed successfully and their awesome new products are on their way — to the right place. In this tutorial, we’ll build an embedded Google map that dynamically displays the location of the shopper’s shipping address on the order confirmation page. We’ll use several BigCommerce features that allow us to get data for the shopper’s shipping address during the checkout process, ensure that the address has been entered correctly, and inject JavaScript into template files:

  • Storefront Checkout API
  • Google Address Autocomplete
  • Script Manager

Before you begin, make sure you have a Google Maps API key with Embedded Maps and Places scopes enabled — you’ll need it for both the embedded map and Google Address Autocomplete.

Here’s a preview of what we’ll be building:

Pre-requisites

Before we dive into the tutorial, let’s do some quick orientation on a few of the technologies we’ll be using.

Google Address Autocomplete

Google Address Autocomplete is a BigCommerce feature that uses the Google Maps API to suggest addresses while a shopper fills out their address on the checkout form. Once a shopper selects a matching address, all of the remaining address form fields are prefilled. This is great for user experience because it can reduce the time and effort to fill out the checkout form, but it’s also great for our purposes because it ensures that the address the shopper enters is correct.

You don’t have to enable Google Address Autocomplete to complete this tutorial, but it does reduce the risk of errors due to bad user input. If the shopper supplies an address that’s misspelled or doesn’t match what Google expects, the map won’t be able to display the shipping destination.

To enable Google Address Autocomplete, navigate to Advanced Settings>Checkout in the BigCommerce control panel, opt in, and enter your Google Maps API key.

Script Manager

The BigCommerce Script Manager allows you to inject third-party JavaScript into the storefront through a control panel interface. You can specify the page type and location that you want your script to appear, for example, on the Checkout page, in the Footer. Using the Script Manager is advantageous because it gives you a visual reference for organizing the JavaScript that you’ve placed on the storefront, and scripts placed using the Script Manager will persist even if a different theme is applied to the store.

In this tutorial, we’ll be placing scripts on two page types: on the Checkout page and the Order Confirmation. In both cases, we’ll set the location to Footer and the script type to ‘Script’.

Google Maps Embed

The Google Maps Embed API allows you to embed an interactive map into a webpage. You can supply the Maps Embed API URL as the src attribute of an iframe, along with parameters that control the map’s styling and the location it points to. For example, this iframe tag:

<iframe width="600" height="450" frameborder="0" style="border:0" src="https://www.google.com/maps/embed/v1/place?q=Sydney,+New+South+Wales&key=YOUR_GOOGLE_APIKEY" allowfullscreen></iframe>

Generates this map:

The ?q= parameter defines the map’s location. You can use a Google Place ID, or an address whose spaces have been replaced with plus signs (or URL encoded).

In order to make the map dynamically show the shipping address of the shopper who just completed their order, we’ll need to capture the shipping address from the Checkout object, do a little data cleanup to grab just the fields we need, URL encode it, and then pass this in as the ?q= parameter for the map iframe src.

Building the Embedded Map

Now that we’re acquainted with the pre-requisites, let’s get down to business. We’ll be creating two scripts: one that runs on the checkout page to save the shopper’s shipping address in local storage and another that runs on the order confirmation page to create the map.

1. Get the Shipping Address

The first thing we need to do is get the shopper’s shipping address. We want the shipping address on the order confirmation page, but it isn’t surfaced there. So, we need to capture the address on the checkout page and save it in local storage so we can access it after an order has been placed.

The Storefront Checkout API allows us to make a fetch request for the checkout object, which contains the data associated with an order as it moves through the checkout process. We can return the shopper’s information, the items in the cart, and the billing and shipping address. However, the checkout object is assembled as the shopper proceeds through the steps of checkout. If we make the fetch request too soon, the shopper won’t have entered their address yet, and if we make the request too late, on the confirmation page for example, the checkout object won’t exist anymore because it’s been converted to an order.

Keeping that in mind, we’ll make the fetch request on the Payment step of checkout — when we know that the shopper has filled in their address. To do this, we can use Mutation Observer to listen for an element that exists on the Payment step, make the fetch request, and then store the shipping address in local storage so we can retrieve it later. Using the Script Manager, insert the following script onto the checkout page:

(Adapted from Ryan Morr’s blog post: Using Mutation Observers to Watch for Element Availability)

A word of caution about interacting directly with DOM elements on the BigCommerce checkout page. Although the BigCommerce team is mindful to keep elements the same across updates, we can’t guarantee that classes will always stay the same — so be sure not to tie any mission critical functionality to those DOM elements. This tutorial is provided on an as-is basis, and you should weigh the risks before adding custom JavaScript to your checkout page. **End Disclaimer**

Okay, let’s break down what’s happening in this request:

fetch('/api/storefront/checkouts/{{checkout.id}}', {credentials: 'include'})
.then(res => res.json())
.then(data => localStorage.setItem("shippingAddress", (JSON.stringify(data.consignments[0].shippingAddress))))
});

First, we’re making a fetch request for the current checkout, using {{checkout.id}} to dynamically provide the ID for the current cart. We parse the response as JSON, then set a local storage item that has the key “shippingAddress.” The value will be set to the first shipping address in the consignments array returned in the Checkout API response. The reason we’re selecting the first item in the array is that an order can have multiple shipping addresses. We’ll use the first one to populate the map.

Using Chrome Dev Tools, we can see that we have a shippingAddress key in local storage once the shopper proceeds to the payment step:

2. Generate the Map

Now, we’ll create a script to generate the map embed and pass in the shopper’s location data. The first function we’ll define generates the HTML markup for the map and appends it to the order confirmation page content. In that markup, we’re creating a link to the customer’s order history page in case they want to view their full order details and status, but we want to make sure that the link only shows if the shopper is logged in to a customer account. If the shopper is a guest, we should hide the link. We’re using the {{#if}} Handlebars helper to render the link conditionally, depending on whether the shopper is logged in or not.

Also note that we’re generating an iframe tag, but we haven’t set a source for it yet. We’ll do that in the next function we define.

function generateMarkup(){
const confirmation = document.querySelector('.orderConfirmation-
section:last-of-type');
confirmation.innerHTML += `<div id="shippingMap" >
<h2 id="mapHeader" style="margin-bottom: 15px;">We're sending
your order to:</h3>
{{#if customer}}
<a href="/account.php?action=order_status"
style="display:block;">Check my order status</a>
{{/if}}
<iframe id="map" width="450" height="300" ></iframe>
</div>`;
createIframeSrc();
}

Next, we’ll create a second function to retrieve the shipping address from local storage and build the iframe source.

function createIframeSrc() {
const shipping = JSON.parse(localStorage.shippingAddress);
const street = shipping.address1 + ", ";
const city = shipping.city + ", ";
const state = shipping.stateOrProvince;
const fullAddress = street.concat(city, state);
const q = encodeURIComponent(fullAddress); document
.getElementById("map")
.setAttribute(
"src", "https://www.google.com/maps/embed/v1/placekey=YOUR_GOOGLE_API_KEY"+q);
}

We’re retrieving the shipping address from local storage and converting it from a string back to JSON so we can work with it. We don’t need all of the fields in the shipping address object — just the Address line 1, the city, and the state — so we save each of those fields to variables and concatenate them into the full address. Then, we URL encode the address so it’s ready to go into the iframe src. The last thing the function does is select the iframe element by its id and use the setAttribute method to specify the Google Maps Embed URL as the src.

Finally, we’re going to call the generateMarkup() function on a one second timeout, to make sure that the order confirmation page has fully loaded before we try to append our markup to the DOM. We’re using setTimeout instead of a method like window.onload because the content for the order confirmation page loads from a React app, and the onload event can fire when the element the app mounts to has loaded but the content itself isn’t present yet.

setTimeout(generateMarkup, 1000);

Here’s the final script, which should be added to the Order Confirmation page via the Script Manager:

Conclusion

And there you have it — a map on the order confirmation page that displays the shopper’s shipping address.

While you could stop there, consider this tutorial a starting point to spark your creativity. What other uses can you think of for the shopper’s shipping address? How might you restyle the map embed? We encourage you to adapt and remix what you see here to create your own customized solution.

Did you find this tutorial helpful, or see something that can be improved? Let us know in the comments or by tweeting @BigCommerceDevs.

--

--

Karen White
BigCommerce Developer Blog

Developer Marketing at Atlassian. Formerly at BigCommerce, Rasa. I think Voyager was the best Star Trek.