My apologies that I do not have this live online right now as I have
no method of doing so yet...
According to the API docs, hiding the traffic layer is done simply by
using "setMap(null)";
I have a toggle function that handles this:
function toggleTraffic (toggle, map) {
var trafficLayer = new google.maps.TrafficLayer();
if (toggle) {
trafficLayer.setMap(map);
} else {
alert("Should Work");
trafficLayer.setMap(null);
}
}
I get the alert "Should Work", but the traffic layer persists.
My entire code is here:
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript" src="
http://maps.google.com/maps/api/js?
sensor=false"></script>
<script type="text/javascript">
var map;
var houston = new google.maps.LatLng(29.75, -95.37);
function TWControl(controlDiv, map) {
// Main Control DIV Padding
controlDiv.style.padding = '5px';
// Set CSS For Control UI
var controlUI = document.createElement('DIV');
controlUI.style.backgroundColor = 'black';
controlUI.style.color = 'white';
controlUI.style.borderColor = 'white';
controlUI.style.borderStyle = 'solid';
controlUI.style.borderWidth = '2px';
controlUI.style.cursor = 'pointer';
controlUI.style.textAlign = 'center';
// Append Div To controlDiv
controlDiv.appendChild(controlUI);
// Set CSS For Control UI Interior
var controlText = document.createElement('DIV');
controlText.style.fontFamily = 'Arial,sans-serif';
controlText.style.fontSize = '12px';
controlText.style.paddingLeft = '14px';
controlText.style.paddingRight = '14px';
controlText.innerHTML = 'Traffic On';
// Append Div To controlUI
controlUI.appendChild(controlText);
// Setup click event listeners
google.maps.event.addDomListener(controlUI, 'click',
function() {
if (controlText.innerHTML == "Traffic On") {
controlText.innerHTML = "Traffic Off";
toggleTraffic(1, map);
} else if (controlText.innerHTML == "Traffic Off") {
controlText.innerHTML = "Traffic On";
toggleTraffic(0, map);
}
});
}
function toggleTraffic (toggle, map) {
var trafficLayer = new google.maps.TrafficLayer();
if (toggle) {
trafficLayer.setMap(map);
} else {
alert("Should Work");
trafficLayer.setMap(null);
}
}
function initialize () {
var mapDiv = document.getElementById('map_canvas');
var myOptions = {
zoom: 9,
center: houston,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(mapDiv, myOptions);
var twControlDiv = document.createElement('DIV');
var twControl = new TWControl(twControlDiv, map);
map.controls[google.maps.ControlPosition.RIGHT].push(twControlDiv);
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:500px; height:400px"></div>
</body>
</html>