我在点击时打开一个模式以显示谷歌地图。由于网站是响应式的,我添加了一个事件监听器,以确保地图以窗口大小调整为中心。所有这些都有效,但事件监听器仅在初始模态打开时运行。如果我关闭模态并再次打开它,则监听器不再工作/运行,并且没有地图调整大小。
想法?
// show google map
$('#datatable').on('click', '.dtMap', function () {
var data = {'activity_id': $(this).parents('tr').attr('id')};
// equals 40.0989, -83.1615, but need to make into two variables or in this case an array
var latlong = $(this).closest('tr').find('.latlong').text();
var coordinates = latlong.split(', ');
$('#modal-ajax')
//this event fires when the modal has finished the animation
//the size of #map_canvas is available now
//create the map when this event fires
.one('shown.bs.modal', function(){
latLng = new google.maps.LatLng(parseFloat(coordinates[0]), parseFloat(coordinates[1]));
var mapOptions = {
zoom: 12,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
},
map = new google.maps.Map($('#map_canvas')[0], mapOptions),
marker = new google.maps.Marker({
position: latLng,
map: map,
title: 'test'
});
// make sure the map and marker stays centered on resizing
google.maps.event.addDomListener(window, "resize", function() {
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});
})
.load('/modals/m_view_map.php', data, function() {
google.load('maps', '3',
{other_params:'sensor=false',
callback: function(){
//show the modal
$('#modal-ajax').modal('show');
}
}
);
});
});
SOLUTION:
为什么我以前从未想过这个......这使得地图/标记在任何时候都适当地调整大小......
google.maps.event.addDomListener(window, "resize", function() {
google.maps.event.trigger(map, "resize");
map.setCenter(latLng);
});
答案 0 :(得分:1)
$('#modal-ajax')
//this event fires when the modal has finished the animation
//the size of #map_canvas is available now
//create the map when this event fires
.one('shown.bs.modal', function(){
是的,它会工作一次,因为您正在使用jQuery的.one()
方法,并且所有map事件变量都在方法本身的本地范围内。因此它不起作用。
将处理程序附加到元素的事件。处理程序已执行 每个事件类型每个元素最多一次。