Check if address is within custom defined area on Map

How to set up and use custom delivery areas using the Maps Javascript API from Google

Key Links

Example App Editor Example App Preview Maps Javascript API Documentation

Overview

On a high level, we will create a polygon area using geographic address values and then use those addresses as a reference for determining if the users location is within the delivery area.

For the delivery area you need to create a list of address to represent the edges of the defined area. This will require at least 3 address values but can be as many as you need.

We won't go through the process of creating the polygon area but it's important to remember that the list of addresses needs to be in consecutive order around the perimeter of the area.

Setting up the elements and workflows

Step 1 - Load the library from Google

Add the following script to the Page HTML Header

<script async src="https://maps.googleapis.com/maps/api/js?key=[API_KEY]&libraries=geometry"></script>

Replace the [API_KEY] placeholder with the Google Maps API key for your app

Step 2 - Javascript to Bubble element

Add a Javascript to Bubble element to the page and set the 'bubble_fn_suffix' value to 'isInArea'. Check the Trigger event and Publish value options and set the Value type to yes/no.

When we check if an address is within the map area, we will trigger this event and pass it a yes or no value to indicate whether the location is valid or not.

In the workflows, set up a workflow using the Javascript to Bubble A event. When testing, it's a good practice to set up an alert that indicates the response received for easy feedback.

Step 3 - Check the location

To check the location, you will need to use a Run Javascript action. Add the following code to that action:

const coordPolygon = new google.maps.Polygon({
paths: [ ARRAY_OF_ADDRESSES ]
});
var currPosition = new google.maps.LatLng( ADDRESS_LAT, ADDRESS_LNG )
const inside = google.maps.geometry.poly.containsLocation(
currPosition,
coordPolygon
) ? true : false;
bubble_fn_isInArea(inside)

Replace the placeholders with dynamic data from your app as follows:

  • ADDRESS_LAT = Latitude of the user's address

  • ADDRESS_LNG = Longitude of the user's address

  • ARRAY_OF_ADDRESSES = This will be an array of the address establishing the defined area you want to search in. Create this by retrieving the list of addresses and formatting the list of text like this:

For reference, this is an array of objects and the final result should look something like this:

[
{lat: 34.829838, lng: -82.6015206},
{lat: 34.85261759999999, lng: -82.3940104},
{lat: 34.7917845, lng: -82.4929054},
{lat: 34.78789100000001, lng: -82.69235909999999}
]

Step 4 - Test it!

That should be it. Everything is set up and ready to go. View the Example App for a working setup and to explore the features.