Search code examples
google-mapsgoogle-maps-api-3google-maps-styling

Styled Maps: How can I control visibility of elements for specific zoom level?


I am trying to create a styled map with map stylers in Goolge Maps API v3. Everything is working fine, except that I can't find a way to add styles for elements at a specific zoom level.

For example, I only want the road.highway displayed at a higher zoom level, otherwise the whole map is cluttered with highways. I have tried to use the weight property, but that makes the highways thinner even if on a high zoom level.

Is there a way how this can be done, if so, could you please show me how to do it?

Many thanks in advance!


Solution

  • It's done by creating different google.maps.StyledMapType objects with different styles, and then setting an event listener to listen to the 'zoom_changed' event of the Map object. This should give you some idea:

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Custom Styled Map</title>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
    <script>
    
    /***
    SEE:
    https://developers.google.com/maps/documentation/javascript/styling
    ALSO, GOOGLES STYLED MAP WIZARD:
    http://gmaps-samples-v3.googlecode.com/svn/trunk/styledmaps/wizard/index.html
    ***/
    
    function initialize() {
        var gm = google.maps,
            darkStylers = [
                {stylers:[{invert_lightness:true}]}
            ],
            lightStylers = [
                {stylers:[{saturation:-100}]}
            ],
            darkStyle = new gm.StyledMapType(darkStylers, {name: 'Dark Style'}),
            lightStyle = new gm.StyledMapType(lightStylers, {name: 'Light Style'}),
            mapOptions = {
                zoom: 7,
                mapTypeControl:false,
                center: new gm.LatLng(32.8297,-96.6486),
                mapTypeId: gm.MapTypeId.ROADMAP
            },
            map = new gm.Map(document.getElementById('map_canvas'), mapOptions);
        //add two new MapTypes to the maps mapTypes
        map.mapTypes.set('Dark_Map', darkStyle);
        map.mapTypes.set('Light_Map', lightStyle);
        //set our maps initial style
        map.setMapTypeId('Dark_Map');
        gm.event.addListener(map, 'zoom_changed', function () {
            var zoom = this.getZoom();
            if (zoom < 9) {
                map.setMapTypeId('Dark_Map');
            } else {
                map.setMapTypeId('Light_Map');
            }
        });
    }
    
    google.maps.event.addDomListener(window, 'load', initialize);
    
    </script>
    </head>
    <body>
    <div id="map_canvas" style="width:780px; height:600px; margin:10px auto;"></div>
    </body>
    </html>