Reputation: 29
I am trying to add the Google Maps Traffic Layer with a control, and since I am so new with this, I cannot figure it out. I have gotten the below script from the internet with some fine tuning, but I cannot figure out how to get the control into the map. I just need a way to toggle the traffic layer on and off for the average user, so if there is a better way than to add the control to the map, I am up for anything. Thanks.
var map;
var chicago = new google.maps.LatLngBounds();
function HomeControl(controlDiv, map) {
controlDiv.style.padding = '5px';
var controlUI = document.createElement('div');
controlUI.style.backgroundColor = 'white';
controlUI.style.borderStyle = 'solid';
controlUI.style.borderWidth = '2px';
controlUI.style.cursor = 'pointer';
controlUI.style.textAlign = 'center';
controlUI.title = 'Click to set the map to Home';
controlDiv.appendChild(conrolUI);
var controlText = document.createElement('div');
controlText.style.fontFamily = 'Arial.sans-serif';
controlText.style.fontSize = '12px';
controlText.style.paddingLeft = '4px';
controlText.style.paddingRight = '4px';
controlText.innerHTML = '<b>Home</b>';
controlUI.appendChild(controlText);
googlemaps.event.addDomListener(controlUI, 'click', function() {
map.setCenter(chicago)
});
}
function addtrafficlayer() {
var myLatlng = new google.maps.LatLngBounds();
var mapDiv = document.getElementById('map');
var mapOptions = {
zoom: 13,
maxWidth: 60,
}
map = new google.maps.Map(mapDiv, mapOptions);
var homeControlDiv = document.createElement('div');
var homeControl = newHomeControl(homeControlDiv, map);
homeControlDiv.index = 1;
map.controls(google.maps.ControlPosition.TOP_RIGHT).push(homeControlDiv);
var trafficLayer = new google.maps.TrafficLayer();
trafficLayer.setMap(map);
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
}
google.maps.event.addDomListener(window, 'load', addtrafficlayer);
Upvotes: 0
Views: 4457
Reputation: 4305
First of all, your addTrafficLayer
function actually initializes the map... twice. This function should be named init
or something similar instead. Here's what should go in it:
function init() {
var options = {
zoom: 16,
center: new google.maps.LatLng(40.747688, -74.004142),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), options);
trafficLayer = new google.maps.TrafficLayer();
google.maps.event.addDomListener(document.getElementById('trafficToggle'), 'click', toggleTraffic);
}
The toggleTraffic
is pretty simple:
function toggleTraffic(){
if(trafficLayer.getMap() == null){
//traffic layer is disabled.. enable it
trafficLayer.setMap(map);
} else {
//traffic layer is enabled.. disable it
trafficLayer.setMap(null);
}
}
Then you just need some markup to get it going:
<div id="map"></div>
<button id="trafficToggle">Toggle Traffic Layer</button>
See this code in action here.
Upvotes: 6