Reputation: 4391
I've used Google maps in my Django project's HTML page and it works great, added multiple markers and it was good.
When I tried to catch the clicking event for each marker, it gave me this error initMap is not a function,
Here is my code:
<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>
Upvotes: 0
Views: 85
Reputation: 5701
It looks like you are ending the for loop before enclosing the marker click event listener from within. Can you please try the code below and see if you still get the same scope error?
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 %}
}
Upvotes: 1