如何为每个地图标记点击调用单独的函数?
对于我的例子,我尝试在点击时滚动到div,但它总是带我到最后一个地图标记的div。当我点击单独的地图标记时,如何滚动到单独的div,或者当有多个地图标记时,是否有可能在地图标记点击上触发单独的功能?
正在进行的实验 - http://nayague.com/development/tour/multiple-map-click.html
from django import template
register = template.Library()
@register.simple_tag
def multiply_by_two(value):
return float(value) * 2.0
答案 0 :(得分:0)
您的marker
变量需要关闭功能。 (问题解决了类似的问题:InfoWindows的Google Maps JS API v3 - Simple Multiple Marker Example,使用IIFE)。
// function closure on marker variable for the click event
google.maps.event.addListener(marker, 'click', (function(marker) {
return function(evt) {
console.log('click');
var elem = $(marker.url);
console.log(elem);
$('html, body').animate({
scrollTop: elem.offset().top
}, 1000);
}
}(marker)))
代码段
jQuery(function($) {
// Asynchronously Load the map API
var script = document.createElement('script');
script.src =
"https://maps.googleapis.com/maps/api/js?callback=initialize";
document.body.appendChild(script);
});
function initialize() {
var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap'
};
// Display a map on the page
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
map.setTilt(45);
// Multiple Markers
var markers = [
['Anuradhapura', 8.3372688, 80.3619399, '#1'],
['Sigiriya', 7.9568242, 80.7434198, '#2'],
['Hotel See Kandy', 7.2930541, 80.6159102, '#3']
];
// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow(),
marker, i;
// Loop through our array of markers & place each one on the map
for (i = 0; i < markers.length; i++) {
var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0],
url: markers[i][3]
});
// function closure on marker variable for the click event
google.maps.event.addListener(marker, 'click', (function(marker) {
return function(evt) {
var elem = $(marker.url);
$('html, body').animate({
scrollTop: elem.offset().top
}, 1000);
}
}(marker)))
// Automatically center the map fitting all markers on the screen
map.fitBounds(bounds);
}
// Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(8);
google.maps.event.removeListener(boundsListener);
});
}
html,
body,
#map_canvas {
height: 100%;
width: 100%;
padding: 0px;
margin: 0px;
}
.location-details {
background-color: blue;
color: white;
width: 100%;
display: inline-block;
height: 100vh;
}
.location-details:nth-child(odd) {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='map_canvas' style="width: 100%;height: 100vh"></div>
<div class="location-details" id='1'>1</div>
<div class="location-details" id='2'>2</div>
<div class="location-details" id='3'>3</div>