initMap не является функцией, когда я пытаюсь добавить несколько слушателей кликов к маркерам django - PullRequest
0 голосов
/ 22 октября 2019

Я использовал карты Google на HTML-странице моего проекта Django, и он отлично работает, добавил несколько маркеров, и это было хорошо.

Когда я пытался отловить событие нажатия для каждого маркера, он дал мне этоошибка 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>

1 Ответ

1 голос
/ 25 октября 2019

Похоже, что вы заканчиваете цикл for перед тем, как заключить прослушиватель события click маркера изнутри. Можете ли вы попробовать код ниже и посмотреть, если вы все еще получаете ту же ошибку области видимости?

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