How to change and preview map type in Google Maps Dinamically with JavaScript

If you are working on a form that allows you to customize some map view, you will need to switch from type in the map dinamically. Although this is a very simple feature, not everybody knows how to do it. To guide you, we'll initialize a simple map with the satellite view and the instance will be stored in the map variable:

<div id="map"></div>
<script>
    var map;

    function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
            center: {
                lat: -34.397, 
                lng: 150.644
            },
            zoom: 8,

            // Defining map type during the initialization
            mapTypeId: 'satellite'
        });
    }
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap" async defer></script>

Now that you have an instance, you can cast the setMapTypeId method from the map variable. Just provide the new type as a string or from the MapTypeId interface e.g:

// Using the MapTypeId interface
map.setMapTypeId(google.maps.MapTypeId.TERRAIN);

map.setMapTypeId(google.maps.MapTypeId.SATELLITE);

map.setMapTypeId(google.maps.MapTypeId.HYBRID);

map.setMapTypeId(google.maps.MapTypeId.ROADMAP);

// Using the string representation
map.setMapTypeId("roadmap");

map.setMapTypeId("hybrid");

map.setMapTypeId("satellite");

map.setMapTypeId("terrain");

Happy coding !

This could interest you
Become a more social person