Search code examples
javascriptdjangogoogle-mapsgoogle-maps-api-3google-maps-api-2

Django template won't run Google Maps javascript inside a block


I have a base.html and an index.html that extends base.html and fills out a {% block content %}{% endblock %}. However, for some reason, the javascript that I have in the block that deals with initiating a Google Map doesn't create the map - the page is blank. Without extending the base.html (i.e. just by typing everything in base.html out in index.html explicitly), the map works fine. The code:

base.html

<!DOCTYPE html>

{% load static %}
<html>
  <head>
    <title>Title</title>
    <link rel="stylesheet" type="text/css" href='{% static "mh_app/style.css" %}' />
  </head>
  <body>
    <header id="header">
      <div class="header-cont">
        <h1>
          Title
        </h1>
        <nav id="nav">
          <ul>
            <li>
              <a href="{% url 'index' %}">Home</a>
            </li>
            <li>
              <a href="{% url 'download' %}">Download</a>
            </li>
            <li>
              <a href="{% url 'about' %}">About</a>
            </li>
          </ul>
        </nav>
      </div>
    </header>
    {% block content %}{% endblock %}
  </body>
</html>

index.html

{% block content %}
  <div id='map'></div>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <script type='text/javascript'>
    function initMap() {
      var map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: 38.3499047, lng: -100.0770253},
        zoom: 4
      });
    }
  </script>
  <script src="https://maps.googleapis.com/maps/api/js?key=<my_api_key>&callback=initMap" async defer></script>
{% endblock %}

I've tried sticking some console.log statements inside initMap(), and they run just fine, so I have no idea why the map is not appearing.

EDIT

style.css

#map {
  height: 90%;
  width: 100%;
}

Solution

  • Do you have styles for the map div ?

    Add height and width for the map div, try changing <div id="map"></div> to something like <div id="map" style="width: 500px; height: 500px;"></div>