Custom Google Maps layers via API?

This applies to the Google Maps API v3:

When you draw various Polylines , Polygons , MapLabels or any other Overlay elements in a custom Google map, it draws them on mapPane . Is it possible to somehow create several custom layers on which you can draw Overlay objects, and then easily enable / disable (show / hide) these layers?

I see layer documentation here: https://developers.google.com/maps/documentation/javascript/layers

But nothing about custom layers.

+7
source share
1 answer

You can create your own OverlayView to do this:

 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, after adding your overlays to LayerOverlay you can show or hide them with just 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); 
+6
source

All Articles