I am trying to load the javascript google maps api function 'initMap()' in a div upon click of a button. The map loads and disappears. How do I get it to stay?

I have created a map div and a button that calls the initMap function

<button id="getLocation" onclick="initMap()">Get Location</button>
<div id="map" style="width: 100%; height: 300px; border: 1px solid red;"> 

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

    // Try HTML5 geolocation.
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        var pos = {
          lat: position.coords.latitude,
          lng: position.coords.longitude

        infoWindow.setContent('Location found.');
      }, function() {
        handleLocationError(true, infoWindow, map.getCenter());
    } else {
      // Browser doesn't support Geolocation
      handleLocationError(false, infoWindow, map.getCenter());

  function handleLocationError(browserHasGeolocation, infoWindow, pos) {
    infoWindow.setContent(browserHasGeolocation ?
                          'Error: The Geolocation service failed.' :
                          'Error: Your browser doesn\'t support geolocation.');
<script async defer

The map appears and immediately disappears

0 Answers