【问题标题】:Django template won't run Google Maps javascript inside a blockDjango 模板不会在块内运行 Google Maps javascript
【发布时间】:2017-07-06 04:32:11
【问题描述】:

我有一个 base.html 和一个扩展 base.html 并填写 {% block content %}{% endblock %} 的 index.html。但是,由于某种原因,我在处理启动 Google 地图的块中的 javascript 不会创建地图 - 页面是空白的。如果不扩展 base.html(即,只需在 index.html 中明确键入 base.html 中的所有内容),地图就可以正常工作。代码:

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 %}

我尝试在initMap() 中添加一些console.log 语句,它们运行良好,所以我不知道为什么地图没有出现。

编辑

style.css

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

【问题讨论】:

    标签: javascript django google-maps google-maps-api-3 google-maps-api-2


    【解决方案1】:

    你有map div 的样式吗?

    map div 添加高度和宽度,尝试将&lt;div id="map"&gt;&lt;/div&gt; 更改为&lt;div id="map" style="width: 500px; height: 500px;"&gt;&lt;/div&gt; 之类的内容

    【讨论】:

    • 虽然宽度不是强制性的,但您至少必须设置一个高度。确实如此。但我们不知道应用了什么,因为 OP 没有发布任何 CSS。
    • 这成功了!通过将高度设置为 500px,地图弹出。然而,以前,我将高度设置为 90% - 关于为什么 90% 设置没有做任何事情的任何想法?
    • 没关系,想通了!这是因为我没有将父容器 - body 和 html - 设置为 100%
    • 除非可以确定父元素的大小,否则不能使用百分比。在您的情况下,如果您将主体设置为 100% 高度,您应该能够在地图容器上设置 % 高度。
    猜你喜欢
    • 2017-03-27
    • 2020-09-09
    • 2018-11-25
    • 1970-01-01
    • 2014-07-17
    • 1970-01-01
    • 1970-01-01
    • 2012-12-11
    相关资源
    最近更新 更多