我目前正在构建一个 cms,它应该能够动态呈现多个 Google Maps 实例。我目前的方法是找到所有具有“gMapsCanvas”类的div,并为每个div初始化Gmap。Google Maps 的地址是从 div 的“data-address”属性中取出来的。
HTML 示例:
<div class="gMapsCanvas" data-address="Hauptplatz 22, 4002 Linz, Austria"></div>
CSS:
.gMapsCanvas
{
width: 100%;
height: 100%;
}
JavaScript
var GoogleMap = function(canvas, address)
{
var _parent = this;
this.location = new google.maps.LatLng(-34.397, 150.644);
var options =
{
center: this.location,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControlOptions:
{
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
position: google.maps.ControlPosition.TOP_CENTER
},
streetViewControl: false
};
this.map = new google.maps.Map(canvas, options);
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status)
{
if (status != google.maps.GeocoderStatus.OK)
return;
_parent.location = results[0].geometry.location;
var marker = new google.maps.Marker(
{
map: _parent.map,
position: _parent.location
});
_parent.resize();
});
};
GoogleMap.prototype.resize = function()
{
google.maps.event.trigger(this.map, "resize");
this.map.setCenter(this.location);
}
var Maps = function(classes)
{
var _parent = this;
this.maps = new Array();
classes.each(function()
{
_parent.maps.push(new GoogleMap($(this).get(), $(this).attr("data-address")));
});
};
Maps.prototype.resize = function()
{
for (var cnt = 0; cnt < this.maps.length; cnt++)
{
this.maps[cnt].resize();
}
};
var maps;
$(window).load(function()
{
maps = new Maps($(".gMapsCanvas"));
});
我需要全局“地图”变量和调整大小方法,以便能够全局调整地图大小(我的布局是动态的)。
我的问题是它不起作用:在所有浏览器中,画布保持空白,在 Firefox 中,我收到以下错误代码:
NS_ERROR_FAILURE: Component returned failure code: 0x80004005 (NS_ERROR_FAILURE) [nsIDOMWindow.getComputedStyle]
使用标准“getElementById”方法时,所有代码都可以正常工作,因此问题似乎是我使用 JQuery 选择 div 的方式。