Skip to content Skip to sidebar Skip to footer

Adding Custom Control To Google Map (adding Toggle For Traffic Layer)

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

Solution 1:

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:

functioninit() {
    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.

Post a Comment for "Adding Custom Control To Google Map (adding Toggle For Traffic Layer)"