Custom Google Maps Layers via API?

google-maps, google-maps-api-3

Solution

You can create a custom OverlayView to do that :

var LayerOverlay = function () {
  this.overlays = [];
}
LayerOverlay.prototype = new google.maps.OverlayView();
LayerOverlay.prototype.addOverlay = function (overlay) {
  this.overlays.push(overlay);
};
LayerOverlay.prototype.updateOverlays = function () {
  for (var i = 0; i < this.overlays.length; i++) {
    this.overlays[i].setMap(this.getMap());
  }
};
LayerOverlay.prototype.draw = function () {};
LayerOverlay.prototype.onAdd = LayerOverlay.prototype.updateOverlays;
LayerOverlay.prototype.onRemove = LayerOverlay.prototype.updateOverlays;

Then once added your overlays to `LayerOverlay`, you can show or hide them only with one `setMap` :

var layer1 = new LayerOverlay();
layer1.addOverlay(createMarker());
layer1.addOverlay(createMarker());
layer1.addOverlay(createMarker());

// hide all markers
layer1.setMap(null);

// show all markers
layer1.setMap(map);

Problem

This is regarding Google Maps API v3: When you draw various `Polylines`, `Polygons`, `MapLabels` or any of the other Overlay elements in a custom Google Map, it draws them on the `mapPane`. Is it possible to somehow create multiple custom layers that you can draw Overlay objects on and then easily enabled/disable (show/hide) those layers? I see documentation about layers here: https://developers.google.com/maps/documentation/javascript/layers But nothing about custom layers.

Original source