4.2.1 Toggle an array of circles, polygons or lines

Circles, polygons and lines are treated differently than “placemarks” in Google-land. Because of this, the functions needed to toggle an array of circles (for example), differ from that of placemarks.

For this tutorial, we will create a toggle for an array of circles (buffers).

Setting up the array

First, create an array for the circles in the global space:

1
2
// circle array
var circle = [];

createBuffer function

Then, create a function that generates a buffer around a given point:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
yoh.createBuffer = function (latitude,longitude,radius,color,i){
    var bufferOptions = {
        strokeColor: color,
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: color,
        fillOpacity: 0.35,
        map: map,
        center: new google.maps.LatLng(latitude,longitude),
        radius: radius
    };
 
    circle[i] = new google.maps.Circle(bufferOptions);
}

Notice that the function requests the following parameters:

  • latitude and longitude
  • radius
  • color
  • i: “i” represents a count for the array. This value MUST BE UNIQUE in order to ensure that each circle assumes a unique identity

Making a call to draw a circle

In order to draw a circle around a given point, the function call would be:

1
2
yoh.createBuffer(34.17229311310708,-118.83639693260193,402.336 ,'#53D4BE',1);  
yoh.createBuffer(34.17700641735229,-118.84385347366333,402.336,'#53D4BE',2);

Notice that the last parameter (for “i”) must be a unique value.

The function to toggle the circle array

Next, create the function that will toggle this circle array on/off:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//toggle array layers on/off
yoh.toggleCircleArrayLayer = function(arraylayer,id)
{
    if ($('#'+id).is(':checked')) {
        for (i in arraylayer)
        {
            arraylayer[i].setMap(map);
        }
    }
    else
    {
        for (i in arraylayer)
        {
            arraylayer[i].setMap(null);
        }
    }
}

Input checkbox

Finally, create an input checkbox field that will enable users to toggle the circle layer:

1
<input id="cityCircle_checkbox" type="checkbox" checked="checked" onClick="yoh.toggleCircleArrayLayer(cityCircle,'cityCircle_checkbox')" /> Bus Stop 1/4 Mile Ped Shed

(sample code)

Leave a Reply