Search code examples
javascriptgoogle-mapscanvasinitialization

Google Maps, initialize and fetch map when clicking button and not on page load


I have create two fiddles:

The first one (https://jsfiddle.net/az5tk8ns/5/) works perfectly and initializes on page load with the follwoing syntax: google.maps.event.addDomListener(window, 'load', initialize);

the second fiddle (https://jsfiddle.net/az5tk8ns/8/) is exactly the same code except that the google canvas and related HTML is contained inside a DIV that is hidden by default. I click the button to un-hide the div and initialize the map. initialize();

The problem is that the maps part from the API is working great as I can see the source, destination and distance that the API has calculated, I am just unable to see the map.

what do I have to do with the initialize call to ensure that the google mpa is displayed correctly.

the entire initialize syntax is:

function initialize() {
  directionsDisplay = new google.maps.DirectionsRenderer();
  var chicago = new google.maps.LatLng(-28.5710903,26.0826083);
  var mapOptions = {
    zoom: 7,
    center: chicago
  };
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
  directionsDisplay.setMap(map);
  calcRoute();
}

thanks for the help as always


Solution

  • Your problem is not the code, it is the CSS:

    html, body, #map-canvas {
      height: 100%;
      margin: 0px;
      padding: 0px
    }
    

    The <div id="testdiv"> doesn't have a size. Changing it to this works for me:

    html,body, #map-canvas, #testdiv {
      height: 100%;
      margin: 0px;
      padding: 0px
    }
    

    proof of concept fiddle

    code snippet:

    var directionsDisplay;
    var directionsService = new google.maps.DirectionsService();
    var map;
    
    function initialize() {
      directionsDisplay = new google.maps.DirectionsRenderer();
      var chicago = new google.maps.LatLng(-28.5710903, 26.0826083);
      var mapOptions = {
        zoom: 7,
        center: chicago
      };
      map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
      directionsDisplay.setMap(map);
      calcRoute();
    }
    var origin = "pietermaritzburg, south africa",
      destinations = ["", "durban, south africa", "amanzimtoti, south africa", "ixopo, south africa"]
    
    
    service = new google.maps.DistanceMatrixService();
    
    function calcRoute() {
      var waypts = [];
      for (var i = 1; i < destinations.length - 1; i++) {
        waypts.push({
          location: destinations[i],
          stopover: true
        });
      }
      var request = {
        origin: origin,
        destination: destinations[destinations.length - 1],
        waypoints: waypts,
        optimizeWaypoints: true,
        travelMode: google.maps.TravelMode.DRIVING
      };
      directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
          directionsDisplay.setDirections(response);
          var orig = document.getElementById("orig"),
            dest = document.getElementById("dest"),
            dist = document.getElementById("dist");
    
          orig.value = response.routes[0].legs[0].start_address;
          dest.value = response.routes[0].legs[0].end_address;
          var total_distance = 0.0;
          for (var i = 0; i < response.routes[0].legs.length; i++) {
            total_distance += response.routes[0].legs[i].distance.value;
          }
          dist.value = total_distance + " meters";
        }
      });
    }
    
    function testmap() {
      $('#testdiv').show();
      initialize();
    }
    html,
    body,
    #map-canvas,
    #testdiv {
      height: 100%;
      margin: 0px;
      padding: 0px
    }
    #panel {
      position: absolute;
      top: 5px;
      left: 50%;
      margin-left: -180px;
      z-index: 5;
      background-color: #fff;
      padding: 5px;
      border: 1px solid #999;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://maps.googleapis.com/maps/api/js"></script>
    <div style='display:none' id="testdiv">
    
      <div id="map-canvas"></div>
      <div id="mileage-details">Origin:
        <input id="orig" type="text" style="width:35em">
        <br>
        <br>Destination:
        <input id="dest" type="text" style="width:35em">
        <br>
        <br>Distance:
        <input id="dist" type="text" style="width:35em">
      </div>
    </div>
    <input type="button" onclick='testmap()' value="getmap">