当我尝试向标记 django 添加多个单击侦听器时,initMap 不是函数

initMap is not a function when I try to add multiple click listeners to markers django

我在 Django 项目的 HTML 页面中使用了 Google 地图,效果很好,添加了多个标记,效果很好。

当我试图捕捉每个标记的点击事件时,它给了我这个错误 initMap is not a function,

这是我的代码:

    <style>
        #map {
            height: 400px; /* The height is 400 pixels */
            width: 100%; /* The width is the width of the web page */
        }
    </style>
    <div id="map"></div>
    <script>
        // Initialize and add the map
        function initMap() {
            var gmarkers = [];
            const cairo = {lat: {{the_lat}}, lng: {{the_long}}};
            const map = new google.maps.Map(
                document.getElementById('map'), {zoom: 15, center: cairo});
            // The marker, positioned at Uluru
            {% for item in all_data %}

                var location{{ item.val.station_geohash }} = {
                    lat:{{item.val.station_latitude}},
                    lng:{{ item.val.station_longitude }}
                };
                var marker{{ item.val.station_geohash }} = new google.maps.Marker({
                    position: location{{ item.val.station_geohash }},
                    map: map,
                    draggable: false,
                    title: "{{item.val.station_name}}",
                    animation: google.maps.Animation.DROP,
                });

                gmarkers.push(marker{{ item.val.station_geohash }});
                google.maps.event.addListener(marker{{ item.val.station_geohash }}, 'click', function () {
                var name = marker.title;
                alert(name)
            }

            {% endfor %}

        );


        }
    </script>
    <script async defer
            src="https://maps.googleapis.com/maps/api/js?key=***************************&callback=initMap">
    </script>

看起来您在从内部封闭标记点击事件侦听器之前结束了 for 循环。你能试试下面的代码,看看你是否仍然得到相同的范围错误吗?

function initMap() {
  var gmarkers = [];
  const cairo = {lat: {{the_lat}}, lng: {{the_long}}};
  const map = new google.maps.Map(
      document.getElementById('map'), {zoom: 15, center: cairo});

  {% for item in all_data %}

      var location{{ item.val.station_geohash }} = {
          lat:{{item.val.station_latitude}},
          lng:{{ item.val.station_longitude }}
      };
      var marker{{ item.val.station_geohash }} = new google.maps.Marker({
          position: location{{ item.val.station_geohash }},
          map: map,
          draggable: false,
          title: "{{item.val.station_name}}",
          animation: google.maps.Animation.DROP,
      });

      gmarkers.push(marker{{ item.val.station_geohash }});
      google.maps.event.addListener(marker{{ item.val.station_geohash }}, 'click', function () {
        var name = marker.title;
        alert(name)
      });

  {% endfor %}
}