4.7 Google Places: Adding a checkbox to toggle places

You are now able to map different types of places.  Wouldn’t it be cool to be able to toggle different types of places on/off?  Let’s do so by adding a legend in the table of contents with a checkbox that will allow users to turn each category on/off.

First, let’s create an array that will let us store our places in.  Add the following to the global space:

What we need to do is to create a two-dimensional array, allowing you to store each place by their category name.  For example, all schools would be stored in an array as:

Likewise, all banks would be:

This means that we have to add a call to add each place (marker) into their respective arrays. Add the following highlighted lines inside the .each loop:

Note that the initial “if” statement checks to see whether or not the array for that place type exists or not. In other words, it checks to see if places[‘Schools’] nad places[‘Banks’] exists. If not, it creates it before adding places to the array… otherwise, it will be trying to add places to a non-existing array!

Create a toggle layer function

Before we add the checkbox for each category layer, let’s create the function that will allow us to toggle different array layers on and off.  Add the following function to the code:

This function takes in any array that has google markers in it, and turns them collectively on or off.

Adding the checkbox

Now that we have our arrays in order, let’s add a checkbox.  Since we want to add the checkbox in our table of contents, let’s create a div container for it.  Add the following div (id=layers) inside the body area of the code:

We are now ready to use jQuery to append each layer to this div. For now, add the highlighted code to the placesRequest function:

Let’s break this down. The following line is what appends the checkbox to the sidebar:

We are now familiar with the jQuery “append” function, and we see that it is adding content to the “layers” div that we created earlier. We are adding an input checkbox as follows:

Note the onClick event within the input tag. This is saying to trigger the toggle array function “up206b.toggleArrayLayer” when somebody clicks on the check box.  Note how we have to escape the single quotes with backslashes (\) in order to preserve the name of the array.

The last part of the append call displays the name of the layer (title) and adds a carriage return (<br>).

Leave a Reply