我试图将一个数组传递给一个函数,然后使用该数组中的信息来初始化一个谷歌地图。但是,当我单击地图上的标记时,会产生一个错误,上面写着:
无法获取属性“popupHtml”的值:对象为空或未定义
创建该函数的原因是可以将 javascript 代码移动到单独的 .js 文件中,从而与 html 文件分开。无论如何,这个问题可以纠正吗?这是我的所有代码(我在其中添加了注释以标记错误发生的位置......):
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
window.onload = function ()
{
function loadMap(markers)
{
var options =
{
center: new google.maps.LatLng(40.775813, -73.970786),
zoom: 17,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'), options);
var points = new Array();
for (var i = 0; i < markers.length; i++)
points.push(new google.maps.LatLng(markers[i].lat, markers[i].lon));
var infoWindow = new google.maps.InfoWindow();
for (var i = 0; i < markers.length; i++)
{
var googleMarker = new google.maps.Marker({ position: points[i], map: map, title: markers[i].title });
google.maps.event.addListener(
googleMarker,
'click',
function ()
{
// The following line is where the error is occuring:
infoWindow.setContent(markers[i].popupHtml);
infoWindow.open(map, googleMarker);
});
}
};
loadMap([{
"lat": "40.776512",
"lon": "-73.970293",
"popupHtml": "\u003cdiv\u003eHello world - from marker 1!\u003c/div\u003e",
"title": "Marker 1!"
},
{
"lat": "40.774659",
"lon": "-73.971548",
"popupHtml": "\u003cdiv\u003eHello world - from marker 2!\u003c/div\u003e",
"title": "Marker 2!"
}]);
};
</script>
</head>
<body>
<div id="map" style="width: 680px; height: 400px;"></div>
</body>
</html>