Google Transit Layer through Google Maps API

Posted May 23, 2011

This is a followup to a post we did a while back that showed how to add the Google Transit and Google Bike layer to a google map using the Google Maps API. We've updated this with code based on Google Maps Javascript API version 3.

Google Maps API v3 now allows you to add the Bike route layer and traffic layer via the API, but there still isn't an easy way to get at the transit layer.

To add the Bike layer:


          var bikeLayer = new google.maps.BicyclingLayer();
          bikeLayer.setMap(map);
        

To add the Traffic layer:


          var trafficLayer = new google.maps.TrafficLayer();
          trafficLayer.setMap(map);
        

However, you can use the code below to add the Google Transit layer it as a custom tile layer. This will load the image tiles directly from Google's servers:


          var transitOptions = {
            getTileUrl: function(coord, zoom) {
              return "http://mt1.google.com/vt/lyrs=m@155076273,transit:comp|vm:&" +
              "hl=en&opts=r&s=Galil&z=" + zoom + "&x=" + coord.x + "&y=" + coord.y;
            },
            tileSize: new google.maps.Size(256, 256),
            isPng: true
          };
          
          var transitMapType = new google.maps.ImageMapType(transitOptions);
          
          map.overlayMapTypes.insertAt(0, transitMapType);
        

This loads the full image types, so any other styles you've applied to the basemap will get covered up. Unlike Google Transit, the stations won't be clickable and transit info won't pop up unless you add your own markers to the map, but this should work ok for just showing transit routes.

You can see this technique live in our Realtime Transit Map project.