Search code examples
google-mapsgoogle-maps-api-3google-api-javascript-client

Make a map element blank, disappear (Google Maps JavaScript API, v3)


There are many calls for help with the maps API where a blank white div is undesirable. In my case it's desirable.

I know how to make a map appear.

map.setCenter(new google.maps.LatLng(latitude, longitude));

I know how to make directions appear.

directionsService.route(request, function(result, status) {
    if (status === google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(result);
    }
});

Occasionally I just want the map element to "go white." Later I want to put a map or directions back in there.

I've tried this:

$('#map').empty();

It works, but after that I can never make a map appear again. What's the correct way?

I suppose I could make and delete map instances but this bug report says each destroyed map instance leaks 2MB memory, and Google officially discourages the practice (here and here). I'd really rather not overlay a white rectangle, or make the map display:none. Is there no better way?

(My application is a map next to an address entry form. When sufficient detail has been entered, a map automatically appears. If the field contents are deleted, the map goes blank again.)


Solution

  • Set the map visibility to hidden.

    Better yet, use a class.

    CSS:

    .map-hide {
        visibility: hidden;
    }
    

    jQuery:

    $('#map').addClass('map-hide');
    $('#map').removeClass('map-hide');
    

    JavaScript (IE10+):

    document.getElementById("map").classList.add('map-hide');
    document.getElementById("map").classList.remove('map-hide');
    

    Add the class to blank the map. Remove it when rendering the map.

    Adding and removing a class is better in case multiple parts of the code turn visibility on or off for different reasons.

    Setting a map's visibility to hidden is better than setting its display to none, which can permanently ruin map rendering. I saw one clue to this in the docs about Map.fitBounds() breaking.