【发布时间】:2011-10-25 03:19:13
【问题描述】:
我有一组 jQuery UI 选项卡,每个选项卡都使用 ajax 加载 project.php。根据传递给脚本的参数,使用 project.php 中的以下 JavaScript 显示不同的 Google 地图:
var tab_index = $('#tabs').tabs('option', 'selected');
$('.site_map:visible').css('height','300px');
MapID = $('.site_map:visible').attr('id');
if (MapID !== 'map-new'){
var map_id = 'map-'+tab_index;
$('.site_map:visible').attr('id', map_id);
} else {
MapNewSite();
}
var latlng = new google.maps.LatLng(19,-70.4);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
arrMaps[tab_index] = new google.maps.Map(document.getElementById("map-" + tab_index), myOptions);
arrInfoWindows[tab_index] = new google.maps.InfoWindow();
placeMarker($('.site_details:visible .inpLat').val(), $('.site_details:visible .inpLng').val(), tab_index);
function MapNewSite(){
arrMaps[tab_index] = new google.maps.Map(document.getElementById("map-new"), myOptions);
placeMarker(19,-70.4,tab_index);
arrInfoWindows[tab_index] = new google.maps.InfoWindow();
}
使用我的数据库查询返回的参数加载的每个地图都没有任何问题。但是,在最后一个实例中,我将 project.php 加载到一个没有任何参数的选项卡中,以便有一个空白选项卡供用户操作。不使用数据库坐标加载地图的信号是其 div 的 id 是“map-new”。
在此选项卡中生成的地图会加载,但随后会出现“a is null”错误,这通常意味着它找不到指定 id 的 div 来初始化地图。即使在地图加载后导致此错误的原因是什么?如何阻止错误发生?
这是包含标签站点的父页面中的 JavaScript:
var arrMaps = {};
var arrInfoWindows = {};
var arrMarkers = {};
function placeMarker(lat, lng, tab_index){
map = arrMaps[tab_index];
var bounds = new google.maps.LatLngBounds();
var latlng = new google.maps.LatLng(
parseFloat(lat),
parseFloat(lng)
);
bounds.extend(latlng);
createMarker(latlng, tab_index);
map.fitBounds(bounds);
zoomChangeBoundsListener =
google.maps.event.addListener(map, 'bounds_changed', function(event) {
if (this.getZoom()){
this.setZoom(10);
}
google.maps.event.removeListener(zoomChangeBoundsListener);
});
}
function createMarker(latlng, tab_index) {
var html = '<a href="#" target="_blank" onclick="OpenMapDialog();return false;">Click here to move marker</a>';
arrMarkers[tab_index] = new google.maps.Marker({
map: arrMaps[tab_index],
position: latlng
});
arrInfoWindows[tab_index] = new google.maps.InfoWindow();
google.maps.event.addListener(arrMarkers[tab_index], 'click', function() {
arrInfoWindows[tab_index].setContent(html);
arrInfoWindows[tab_index].open(arrMaps[tab_index], arrMarkers[tab_index]);
});
}
$(function() {
$( "#tabs" ).tabs({
ajaxOptions: {
error: function( xhr, status, index, anchor ) {
$( anchor.hash ).html(
"Couldn't load this tab. We'll try to fix this as soon as possible. " +
"If this wouldn't be a demo." );
}
},
cache: true
});
});
【问题讨论】:
-
你能在 jsfiddle 中放一个有效的例子吗?
标签: javascript jquery jquery-ui google-maps jquery-tabs